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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0bf3d7dc7b2e69af1124b03cbc866eb47d986376 | 1446f520c1db37e157b631385707cc28a17a595e | /stage0/src/Init/Lean/Meta/SynthInstance.lean | 8b61f7e32d08ab41f49dce310a4134061b28c645 | [
"Apache-2.0"
] | permissive | bdbabiak/lean4 | cab06b8a2606d99a168dd279efdd404edb4e825a | 3f4d0d78b2ce3ef541cb643bbe21496bd6b057ac | refs/heads/master | 1,615,045,275,530 | 1,583,793,696,000 | 1,583,793,696,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 24,134 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Daniel Selsam, Leonardo de Moura
Type class instance synthesizer using tabled resolution.
-/
import Init.Lean.Meta.Basic
import Init.Lean.Meta.Instances
import Init.Lean.Meta.LevelDefEq
import Init.Lean.Meta.AbstractMVars
namespace Lean
namespace Meta
namespace SynthInstance
def mkInferTCGoalsLRAttr : IO TagAttribute :=
registerTagAttribute `inferTCGoalsLR "instruct type class resolution procedure to solve goals from left to right for this instance"
@[init mkInferTCGoalsLRAttr]
constant inferTCGoalsLRAttr : TagAttribute := arbitrary _
def hasInferTCGoalsLRAttribute (env : Environment) (constName : Name) : Bool :=
inferTCGoalsLRAttr.hasTag env constName
structure GeneratorNode :=
(mvar : Expr)
(key : Expr)
(mctx : MetavarContext)
(instances : Array Expr)
(currInstanceIdx : Nat)
instance GeneratorNode.inhabited : Inhabited GeneratorNode := ⟨⟨arbitrary _, arbitrary _, arbitrary _, arbitrary _, 0⟩⟩
structure ConsumerNode :=
(mvar : Expr)
(key : Expr)
(mctx : MetavarContext)
(subgoals : List Expr)
instance Consumernode.inhabited : Inhabited ConsumerNode := ⟨⟨arbitrary _, arbitrary _, arbitrary _, []⟩⟩
inductive Waiter
| consumerNode : ConsumerNode → Waiter
| root : Waiter
def Waiter.isRoot : Waiter → Bool
| Waiter.consumerNode _ => false
| Waiter.root => true
/-
In tabled resolution, we creating a mapping from goals (e.g., `HasCoe Nat ?x`) to
answers and waiters. Waiters are consumer nodes that are waiting for answers for a
particular node.
We implement this mapping using a `HashMap` where the keys are
normalized expressions. That is, we replace assignable metavariables
with auxiliary free variables of the form `_tc.<idx>`. We do
not declare these free variables in any local context, and we should
view them as "normalized names" for metavariables. For example, the
term `f ?m ?m ?n` is normalized as
`f _tc.0 _tc.0 _tc.1`.
This approach is structural, and we may visit the same goal more
than once if the different occurrences are just definitionally
equal, but not structurally equal.
Remark: a metavariable is assignable only if its depth is equal to
the metavar context depth.
-/
namespace MkTableKey
structure State :=
(nextIdx : Nat := 0)
(lmap : HashMap MVarId Level := {})
(emap : HashMap MVarId Expr := {})
abbrev M := ReaderT MetavarContext (StateM State)
partial def normLevel : Level → M Level
| u => if !u.hasMVar then pure u else
match u with
| Level.succ v _ => do v ← normLevel v; pure $ u.updateSucc! v
| Level.max v w _ => do v ← normLevel v; w ← normLevel w; pure $ u.updateMax! v w
| Level.imax v w _ => do v ← normLevel v; w ← normLevel w; pure $ u.updateIMax! v w
| Level.mvar mvarId _ => do
mctx ← read;
if !mctx.isLevelAssignable mvarId then pure u
else do
s ← get;
match s.lmap.find? mvarId with
| some u' => pure u'
| none => do
let u' := mkLevelParam $ mkNameNum `_tc s.nextIdx;
modify $ fun s => { nextIdx := s.nextIdx + 1, lmap := s.lmap.insert mvarId u', .. s };
pure u'
| u => pure u
partial def normExpr : Expr → M Expr
| e => if !e.hasMVar then pure e else
match e with
| Expr.const _ us _ => do us ← us.mapM normLevel; pure $ e.updateConst! us
| Expr.sort u _ => do u ← normLevel u; pure $ e.updateSort! u
| Expr.app f a _ => do f ← normExpr f; a ← normExpr a; pure $ e.updateApp! f a
| Expr.letE _ t v b _ => do t ← normExpr t; v ← normExpr v; b ← normExpr b; pure $ e.updateLet! t v b
| Expr.forallE _ d b _ => do d ← normExpr d; b ← normExpr b; pure $ e.updateForallE! d b
| Expr.lam _ d b _ => do d ← normExpr d; b ← normExpr b; pure $ e.updateLambdaE! d b
| Expr.mdata _ b _ => do b ← normExpr b; pure $ e.updateMData! b
| Expr.proj _ _ b _ => do b ← normExpr b; pure $ e.updateProj! b
| Expr.mvar mvarId _ => do
mctx ← read;
if !mctx.isExprAssignable mvarId then pure e
else do
s ← get;
match s.emap.find? mvarId with
| some e' => pure e'
| none => do
let e' := mkFVar $ mkNameNum `_tc s.nextIdx;
modify $ fun s => { nextIdx := s.nextIdx + 1, emap := s.emap.insert mvarId e', .. s };
pure e'
| _ => pure e
end MkTableKey
/- Remark: `mkTableKey` assumes `e` does not contain assigned metavariables. -/
def mkTableKey (mctx : MetavarContext) (e : Expr) : Expr :=
(MkTableKey.normExpr e mctx).run' {}
structure Answer :=
(result : AbstractMVarsResult)
(resultType : Expr)
instance Answer.inhabited : Inhabited Answer := ⟨⟨arbitrary _, arbitrary _⟩⟩
structure TableEntry :=
(waiters : Array Waiter)
(answers : Array Answer := #[])
/-
Remark: the SynthInstance.State is not really an extension of `Meta.State`.
The field `postponed` is not needed, and the field `mctx` is misleading since
`synthInstance` methods operate over different `MetavarContext`s simultaneously.
That being said, we still use `extends` because it makes it simpler to move from
`M` to `MetaM`.
-/
structure State extends Meta.State :=
(result : Option Expr := none)
(generatorStack : Array GeneratorNode := #[])
(resumeStack : Array (ConsumerNode × Answer) := #[])
(tableEntries : HashMap Expr TableEntry := {})
abbrev SynthM := ReaderT Context (EStateM Exception State)
instance SynthM.inhabited {α} : Inhabited (SynthM α) := ⟨throw $ Exception.other ""⟩
def getTraceState : SynthM TraceState := do s ← get; pure s.traceState
def getOptions : SynthM Options := do ctx ← read; pure ctx.config.opts
def addContext (msg : MessageData) : SynthM MessageData := do
ctx ← read;
s ← get;
pure $ MessageData.withContext { env := s.env, mctx := s.mctx, lctx := ctx.lctx, opts := ctx.config.opts } msg
instance tracer : SimpleMonadTracerAdapter SynthM :=
{ getOptions := getOptions,
getTraceState := getTraceState,
addContext := addContext,
modifyTraceState := fun f => modify $ fun s => { traceState := f s.traceState, .. s } }
@[inline] def liftMeta {α} (x : MetaM α) : SynthM α :=
adaptState (fun (s : State) => (s.toState, s)) (fun s' s => { toState := s', .. s }) x
instance meta2Synth {α} : HasCoe (MetaM α) (SynthM α) := ⟨liftMeta⟩
@[inline] def withMCtx {α} (mctx : MetavarContext) (x : SynthM α) : SynthM α := do
mctx' ← getMCtx;
modify $ fun s => { mctx := mctx, .. s };
finally x (modify $ fun s => { mctx := mctx', .. s })
/-- Return globals and locals instances that may unify with `type` -/
def getInstances (type : Expr) : MetaM (Array Expr) :=
forallTelescopeReducing type $ fun _ type => do
className? ← isClass type;
match className? with
| none => throwEx $ Exception.notInstance type
| some className => do
globalInstances ← getGlobalInstances;
result ← globalInstances.getUnify type;
result ← result.mapM $ fun c => match c with
| Expr.const constName us _ => do us ← us.mapM (fun _ => mkFreshLevelMVar); pure $ c.updateConst! us
| _ => panic! "global instance is not a constant";
trace! `Meta.synthInstance.globalInstances (type ++ " " ++ result);
localInstances ← getLocalInstances;
let result := localInstances.foldl
(fun (result : Array Expr) linst => if linst.className == className then result.push linst.fvar else result)
result;
pure result
/-- Create a new generator node for `mvar` and add `waiter` as its waiter.
`key` must be `mkTableKey mctx mvarType`. -/
def newSubgoal (mctx : MetavarContext) (key : Expr) (mvar : Expr) (waiter : Waiter) : SynthM Unit :=
withMCtx mctx $ do
trace! `Meta.synthInstance.newSubgoal key;
mvarType ← inferType mvar;
mvarType ← instantiateMVars mvarType;
instances ← getInstances mvarType;
mctx ← getMCtx;
if instances.isEmpty then pure ()
else do
let node : GeneratorNode := {
mvar := mvar,
key := key,
mctx := mctx,
instances := instances,
currInstanceIdx := instances.size
};
let entry : TableEntry := { waiters := #[waiter] };
modify $ fun s =>
{ generatorStack := s.generatorStack.push node,
tableEntries := s.tableEntries.insert key entry,
.. s }
def findEntry? (key : Expr) : SynthM (Option TableEntry) := do
s ← get;
pure $ s.tableEntries.find? key
def getEntry (key : Expr) : SynthM TableEntry := do
entry? ← findEntry? key;
match entry? with
| none => panic! "invalid key at synthInstance"
| some entry => pure entry
/--
Create a `key` for the goal associated with the given metavariable.
That is, we create a key for the type of the metavariable.
We must instantiate assigned metavariables before we invoke `mkTableKey`. -/
def mkTableKeyFor (mctx : MetavarContext) (mvar : Expr) : SynthM Expr :=
withMCtx mctx $ do
mvarType ← inferType mvar;
mvarType ← instantiateMVars mvarType;
pure $ mkTableKey mctx mvarType
/- See `getSubgoals` and `getSubgoalsAux`
We use the parameter `j` to reduce the number of `instantiate*` invocations.
It is the same approach we use at `forallTelescope` and `lambdaTelescope`.
Given `getSubgoalsAux args j subgoals instVal type`,
we have that `type.instantiateRevRange j args.size args` does not have loose bound variables. -/
structure SubgoalsResult : Type :=
(subgoals : List Expr)
(instVal : Expr)
(instTypeBody : Expr)
private partial def getSubgoalsAux (lctx : LocalContext) (localInsts : LocalInstances) (xs : Array Expr)
: Array Expr → Nat → List Expr → Expr → Expr → MetaM SubgoalsResult
| args, j, subgoals, instVal, Expr.forallE n d b c => do
let d := d.instantiateRevRange j args.size args;
mvarType ← mkForall xs d;
mvar ← mkFreshExprMVarAt lctx localInsts mvarType;
let arg := mkAppN mvar xs;
let instVal := mkApp instVal arg;
let subgoals := if c.binderInfo.isInstImplicit then mvar::subgoals else subgoals;
let args := args.push (mkAppN mvar xs);
getSubgoalsAux args j subgoals instVal b
| args, j, subgoals, instVal, type => do
let type := type.instantiateRevRange j args.size args;
type ← whnf type;
if type.isForall then
getSubgoalsAux args args.size subgoals instVal type
else
pure ⟨subgoals, instVal, type⟩
/--
`getSubgoals lctx localInsts xs inst` creates the subgoals for the instance `inst`.
The subgoals are in the context of the free variables `xs`, and
`(lctx, localInsts)` is the local context and instances before we added the free variables to it.
This extra complication is required because
1- We want all metavariables created by `synthInstance` to share the same local context.
2- We want to ensure that applications such as `mvar xs` are higher order patterns.
The method `getGoals` create a new metavariable for each parameter of `inst`.
For example, suppose the type of `inst` is `forall (x_1 : A_1) ... (x_n : A_n), B x_1 ... x_n`.
Then, we create the metavariables `?m_i : forall xs, A_i`, and return the subset of these
metavariables that are instance implicit arguments, and the expressions:
- `inst (?m_1 xs) ... (?m_n xs)` (aka `instVal`)
- `B (?m_1 xs) ... (?m_n xs)` -/
def getSubgoals (lctx : LocalContext) (localInsts : LocalInstances) (xs : Array Expr) (inst : Expr) : MetaM SubgoalsResult := do
instType ← inferType inst;
result ← getSubgoalsAux lctx localInsts xs #[] 0 [] inst instType;
match inst.getAppFn with
| Expr.const constName _ _ => do
env ← getEnv;
if hasInferTCGoalsLRAttribute env constName then
pure { subgoals := result.subgoals.reverse, .. result }
else
pure result
| _ => pure result
def tryResolveCore (mvar : Expr) (inst : Expr) : MetaM (Option (MetavarContext × List Expr)) := do
mvarType ← inferType mvar;
lctx ← getLCtx;
localInsts ← getLocalInstances;
forallTelescopeReducing mvarType $ fun xs mvarTypeBody => do
⟨subgoals, instVal, instTypeBody⟩ ← getSubgoals lctx localInsts xs inst;
trace! `Meta.synthInstance.tryResolve (mvarTypeBody ++ " =?= " ++ instTypeBody);
condM (isDefEq mvarTypeBody instTypeBody)
(do instVal ← mkLambda xs instVal;
condM (isDefEq mvar instVal)
(do trace! `Meta.synthInstance.tryResolve "success";
mctx ← getMCtx;
pure (some (mctx, subgoals)))
(do trace! `Meta.synthInstance.tryResolve "failure assigning";
pure none))
(do trace! `Meta.synthInstance.tryResolve "failure";
pure none)
/--
Try to synthesize metavariable `mvar` using the instance `inst`.
Remark: `mctx` contains `mvar`.
If it succeeds, the result is a new updated metavariable context and a new list of subgoals.
A subgoal is created for each instance implicit parameter of `inst`. -/
def tryResolve (mctx : MetavarContext) (mvar : Expr) (inst : Expr) : SynthM (Option (MetavarContext × List Expr)) :=
traceCtx `Meta.synthInstance.tryResolve $ withMCtx mctx $ tryResolveCore mvar inst
/--
Assign a precomputed answer to `mvar`.
If it succeeds, the result is a new updated metavariable context and a new list of subgoals. -/
def tryAnswer (mctx : MetavarContext) (mvar : Expr) (answer : Answer) : SynthM (Option MetavarContext) :=
withMCtx mctx $ do
(_, _, val) ← openAbstractMVarsResult answer.result;
condM (isDefEq mvar val)
(do mctx ← getMCtx; pure $ some mctx)
(pure none)
/-- Move waiters that are waiting for the given answer to the resume stack. -/
def wakeUp (answer : Answer) : Waiter → SynthM Unit
| Waiter.root =>
if answer.result.paramNames.isEmpty && answer.result.numMVars == 0 then do
modify $ fun s => { result := answer.result.expr, .. s }
else do
(_, _, answerExpr) ← openAbstractMVarsResult answer.result;
trace! `Meta.synthInstance ("skip answer containing metavariables " ++ answerExpr);
pure ()
| Waiter.consumerNode cNode => modify $ fun s => { resumeStack := s.resumeStack.push (cNode, answer), .. s }
def isNewAnswer (oldAnswers : Array Answer) (answer : Answer) : Bool :=
oldAnswers.all $ fun oldAnswer => do
-- Remark: isDefEq here is too expensive. TODO: if `==` is too imprecise, add some light normalization to `resultType` at `addAnswer`
-- iseq ← isDefEq oldAnswer.resultType answer.resultType; pure (!iseq)
oldAnswer.resultType != answer.resultType
/--
Create a new answer after `cNode` resolved all subgoals.
That is, `cNode.subgoals == []`.
And then, store it in the tabled entries map, and wakeup waiters. -/
def addAnswer (cNode : ConsumerNode) : SynthM Unit := do
answer ← withMCtx cNode.mctx $ do {
traceM `Meta.synthInstance.newAnswer $ do { mvarType ← inferType cNode.mvar; pure mvarType };
val ← instantiateMVars cNode.mvar;
result ← abstractMVars val; -- assignable metavariables become parameters
resultType ← inferType result.expr;
pure { Answer . result := result, resultType := resultType }
};
-- Remark: `answer` does not contain assignable or assigned metavariables.
let key := cNode.key;
entry ← getEntry key;
when (isNewAnswer entry.answers answer) $ do
let newEntry := { answers := entry.answers.push answer, .. entry };
modify $ fun s => { tableEntries := s.tableEntries.insert key newEntry, .. s };
entry.waiters.forM (wakeUp answer)
/-- Process the next subgoal in the given consumer node. -/
def consume (cNode : ConsumerNode) : SynthM Unit :=
match cNode.subgoals with
| [] => addAnswer cNode
| mvar::_ => do
let waiter := Waiter.consumerNode cNode;
key ← mkTableKeyFor cNode.mctx mvar;
entry? ← findEntry? key;
match entry? with
| none => newSubgoal cNode.mctx key mvar waiter
| some entry => modify $ fun s =>
{ resumeStack := entry.answers.foldl (fun s answer => s.push (cNode, answer)) s.resumeStack,
tableEntries := s.tableEntries.insert key { waiters := entry.waiters.push waiter, .. entry },
.. s }
def getTop : SynthM GeneratorNode := do
s ← get; pure s.generatorStack.back
@[inline] def modifyTop (f : GeneratorNode → GeneratorNode) : SynthM Unit :=
modify $ fun s => { generatorStack := s.generatorStack.modify (s.generatorStack.size - 1) f, .. s }
/-- Try the next instance in the node on the top of the generator stack. -/
def generate : SynthM Unit := do
gNode ← getTop;
if gNode.currInstanceIdx == 0 then
modify $ fun s => { generatorStack := s.generatorStack.pop, .. s }
else do
let key := gNode.key;
let idx := gNode.currInstanceIdx - 1;
let inst := gNode.instances.get! idx;
let mctx := gNode.mctx;
let mvar := gNode.mvar;
trace! `Meta.synthInstance.generate ("instance " ++ inst);
modifyTop $ fun gNode => { currInstanceIdx := idx, .. gNode };
result? ← tryResolve mctx mvar inst;
match result? with
| none => pure ()
| some (mctx, subgoals) => consume { key := key, mvar := mvar, subgoals := subgoals, mctx := mctx }
def getNextToResume : SynthM (ConsumerNode × Answer) := do
s ← get;
let r := s.resumeStack.back;
modify $ fun s => { resumeStack := s.resumeStack.pop, .. s };
pure r
/--
Given `(cNode, answer)` on the top of the resume stack, continue execution by using `answer` to solve the
next subgoal. -/
def resume : SynthM Unit := do
(cNode, answer) ← getNextToResume;
match cNode.subgoals with
| [] => panic! "resume found no remaining subgoals"
| mvar::rest => do
result? ← tryAnswer cNode.mctx mvar answer;
match result? with
| none => pure ()
| some mctx => do
withMCtx mctx $ traceM `Meta.synthInstance.resume $ do {
goal ← inferType cNode.mvar;
subgoal ← inferType mvar;
pure (goal ++ " <== " ++ subgoal)
};
consume { key := cNode.key, mvar := cNode.mvar, subgoals := rest, mctx := mctx }
def step : SynthM Bool := do
s ← get;
if !s.resumeStack.isEmpty then do resume; pure true
else if !s.generatorStack.isEmpty then do generate; pure true
else pure false
def getResult : SynthM (Option Expr) := do
s ← get; pure s.result
def synth : Nat → SynthM (Option Expr)
| 0 => do
trace! `Meta.synthInstance "synthInstance is out of fuel";
pure none
| fuel+1 => do
trace! `Meta.synthInstance ("remaining fuel " ++ toString fuel);
condM step
(do result? ← getResult;
match result? with
| none => synth fuel
| some result => pure result)
(do trace! `Meta.synthInstance "failed";
pure none)
def main (type : Expr) (fuel : Nat) : MetaM (Option Expr) :=
traceCtx `Meta.synthInstance $ do
trace! `Meta.synthInstance ("main goal " ++ type);
mvar ← mkFreshExprMVar type;
mctx ← getMCtx;
let key := mkTableKey mctx type;
adaptState' (fun (s : Meta.State) => { State . .. s }) (fun (s : State) => s.toState) $ do {
newSubgoal mctx key mvar Waiter.root;
synth fuel
}
end SynthInstance
/-
Type class parameters can be annotated with `outParam` annotations.
Given `C a_1 ... a_n`, we replace `a_i` with a fresh metavariable `?m_i` IF
`a_i` is an `outParam`.
The result is type correct because we reject type class declarations IF
it contains a regular parameter X that depends on an `out` parameter Y.
Then, we execute type class resolution as usual.
If it succeeds, and metavariables ?m_i have been assigned, we try to unify
the original type `C a_1 ... a_n` witht the normalized one.
-/
private def preprocess (type : Expr) : MetaM Expr :=
forallTelescopeReducing type $ fun xs type => do
type ← whnf type;
mkForall xs type
private def preprocessLevels (us : List Level) : MetaM (List Level) := do
us ← us.foldlM
(fun (r : List Level) (u : Level) => do
u ← instantiateLevelMVars u;
if u.hasMVar then do
u' ← mkFreshLevelMVar;
pure (u'::r)
else
pure (u::r))
[];
pure $ us.reverse
private partial def preprocessArgs : Expr → Nat → Array Expr → MetaM (Array Expr)
| type, i, args =>
if h : i < args.size then do
type ← whnf type;
match type with
| Expr.forallE _ d b _ => do
let arg := args.get ⟨i, h⟩;
arg ← if isOutParam d then mkFreshExprMVar d else pure arg;
let args := args.set ⟨i, h⟩ arg;
preprocessArgs (b.instantiate1 arg) (i+1) args
| _ =>
throw $ Exception.other "type class resolution failed, insufficient number of arguments" -- TODO improve error message
else
pure args
private def preprocessOutParam (type : Expr) : MetaM Expr :=
forallTelescope type $ fun xs typeBody =>
match typeBody.getAppFn with
| c@(Expr.const constName us _) => do
env ← getEnv;
if !hasOutParams env constName then pure type
else do
let args := typeBody.getAppArgs;
us ← preprocessLevels us;
let c := mkConst constName us;
cType ← inferType c;
args ← preprocessArgs cType 0 args;
mkForall xs (mkAppN c args)
| _ => pure type
@[init] def maxStepsOption : IO Unit :=
registerOption `synthInstance.maxSteps { defValue := (10000 : Nat), group := "", descr := "maximum steps for the type class instance synthesis procedure" }
private def getMaxSteps (opts : Options) : Nat :=
opts.getNat `synthInstance.maxSteps 10000
def synthInstance? (type : Expr) : MetaM (Option Expr) := do
opts ← getOptions;
let fuel := getMaxSteps opts;
inputConfig ← getConfig;
withConfig (fun config => { transparency := TransparencyMode.reducible, foApprox := true, ctxApprox := true, .. config }) $ do
type ← instantiateMVars type;
type ← preprocess type;
s ← get;
match s.cache.synthInstance.find? type with
| some result => pure result
| none => do
result? ← withNewMCtxDepth $ do {
normType ← preprocessOutParam type;
trace! `Meta.synthInstance (type ++ " ==> " ++ normType);
result? ← SynthInstance.main normType fuel;
match result? with
| none => pure none
| some result => do
trace! `Meta.synthInstance ("FOUND result " ++ result);
result ← instantiateMVars result;
condM (hasAssignableMVar result)
(pure none)
(pure (some result))
};
result? ← match result? with
| none => pure none
| some result => do {
trace! `Meta.synthInstance ("result " ++ result);
resultType ← inferType result;
condM (withConfig (fun _ => inputConfig) $ isDefEq type resultType)
(do result ← instantiateMVars result;
pure (some result))
(pure none)
};
if type.hasMVar then
pure result?
else do
modify $ fun s => { cache := { synthInstance := s.cache.synthInstance.insert type result?, .. s.cache }, .. s };
pure result?
/--
Return `LOption.some r` if succeeded, `LOption.none` if it failed, and `LOption.undef` if
instance cannot be synthesized right now because `type` contains metavariables. -/
def trySynthInstance (type : Expr) : MetaM (LOption Expr) :=
adaptReader (fun (ctx : Context) => { config := { isDefEqStuckEx := true, .. ctx.config }, .. ctx }) $
catch
(toLOptionM $ synthInstance? type)
(fun ex => match ex with
| Exception.isExprDefEqStuck _ _ _ => pure LOption.undef
| Exception.isLevelDefEqStuck _ _ _ => pure LOption.undef
| _ => throw ex)
def synthInstance (type : Expr) : MetaM Expr := do
result? ← synthInstance? type;
match result? with
| some result => pure result
| none => throwEx $ Exception.synthInstance type
@[init] private def regTraceClasses : IO Unit := do
registerTraceClass `Meta.synthInstance;
registerTraceClass `Meta.synthInstance.globalInstances;
registerTraceClass `Meta.synthInstance.newSubgoal;
registerTraceClass `Meta.synthInstance.tryResolve;
registerTraceClass `Meta.synthInstance.resume;
registerTraceClass `Meta.synthInstance.generate
end Meta
end Lean
|
45082f2738720f8389347a741d311c353a2a37f4 | 556aeb81a103e9e0ac4e1fe0ce1bc6e6161c3c5e | /src/starkware/cairo/lean/semantics/air_encoding/constraints.lean | 9aa513c9b7bacc4e300622d3c1ba2566728784a5 | [
"Apache-2.0"
] | permissive | starkware-libs/formal-proofs | d6b731604461bf99e6ba820e68acca62a21709e8 | f5fa4ba6a471357fd171175183203d0b437f6527 | refs/heads/master | 1,691,085,444,753 | 1,690,507,386,000 | 1,690,507,386,000 | 410,476,629 | 32 | 9 | Apache-2.0 | 1,690,506,773,000 | 1,632,639,790,000 | Lean | UTF-8 | Lean | false | false | 14,197 | lean | /-
The constraints specifying the trace of a Cairo execution.
-/
import algebra.field.basic data.nat.basic data.fin.basic tactic.norm_num
import starkware.cairo.lean.semantics.cpu -- for names of flags
open_locale big_operators
structure input_data_aux (F : Type*) :=
(T : nat)
(rc16_len : nat) -- number of 16-bit range-checked elements
(pc_I : F)
(pc_F : F)
(ap_I : F)
(ap_F : F)
(mem_star : F → option F)
(rc_min : nat)
(rc_max : nat)
(initial_rc_addr : nat) -- for range check builtin, first range-checked address
(rc_len : nat) -- for range check builtin, number of range-checked values
(rc_to_rc16 : fin rc_len → fin 8 → fin rc16_len)
/- constraints -/
(h_rc_lt : rc_max < 2^16)
(h_rc_le : rc_min ≤ rc_max)
/- functions for accessing `mem_star` -/
/-- the domain of the partial memory specification -/
def mem_dom {F : Type*} (mem_star : F → option F) :=
{ x // option.is_some (mem_star x) }
/-- the value of the memory -/
def mem_val {F : Type*} {mem_star : F → option F} (a : mem_dom mem_star) : F :=
option.get a.property
instance {F : Type*} [fintype F] (mem_star : F → option F) : fintype (mem_dom mem_star) :=
by {rw mem_dom, apply_instance}
/- auxiliary functions for talking about flags extracted from f_tilde -/
/-- a sequence of trace cells for storing a bitvector of flags -/
def tilde_type (F : Type*) := fin 16 → F
namespace tilde_type
variables {F : Type*} [field F] (f_tilde : tilde_type F)
def to_f := λ i : fin 15, f_tilde i.cast_succ - 2 * f_tilde i.succ
def f_dst_reg := f_tilde.to_f DST_REG
def f_op0_reg := f_tilde.to_f OP0_REG
def f_op1_imm := f_tilde.to_f OP1_IMM
def f_op1_fp := f_tilde.to_f OP1_FP
def f_op1_ap := f_tilde.to_f OP1_AP
def f_res_add := f_tilde.to_f RES_ADD
def f_res_mul := f_tilde.to_f RES_MUL
def f_pc_jump_abs := f_tilde.to_f PC_JUMP_ABS
def f_pc_jump_rel := f_tilde.to_f PC_JUMP_REL
def f_pc_jnz := f_tilde.to_f PC_JNZ
def f_ap_add := f_tilde.to_f AP_ADD
def f_ap_add1 := f_tilde.to_f AP_ADD1
def f_opcode_call := f_tilde.to_f OPCODE_CALL
def f_opcode_ret := f_tilde.to_f OPCODE_RET
def f_opcode_assert_eq := f_tilde.to_f OPCODE_ASSERT_EQ
def instruction_size := f_tilde.f_op1_imm + 1
end tilde_type
/-
The constraints on how information is stored in memory.
For some reason, elaboration was too slow (and timed out) before I split this into smaller
structures.
-/
structure memory_embedding_constraints {F : Type*} [field F] [fintype F]
(T : nat)
(rc_len : nat)
(pc : fin T → F)
(inst : fin T → F)
(dst_addr : fin T → F)
(dst : fin T → F)
(op0_addr : fin T → F)
(op0 : fin T → F)
(op1_addr : fin T → F)
(op1 : fin T → F)
(rc_addr : fin rc_len → F) -- range check builtin
(rc_val : fin rc_len → F)
(mem_star : F → option F)
(n : nat)
(a : fin (n + 1) → F)
(v : fin (n + 1) → F) :=
/- embedding of data -/
(embed_inst : fin T → fin (n + 1))
(embed_dst : fin T → fin (n + 1))
(embed_op0 : fin T → fin (n + 1))
(embed_op1 : fin T → fin (n + 1))
(embed_rc : fin rc_len → fin (n + 1))
(embed_mem : mem_dom mem_star → fin (n + 1))
(h_embed_pc : ∀ i, a (embed_inst i) = pc i)
(h_embed_inst : ∀ i, v (embed_inst i) = inst i)
(h_embed_dst_addr : ∀ i, a (embed_dst i) = dst_addr i)
(h_embed_dst : ∀ i, v (embed_dst i) = dst i)
(h_embed_op0_addr : ∀ i, a (embed_op0 i) = op0_addr i)
(h_embed_op0 : ∀ i, v (embed_op0 i) = op0 i)
(h_embed_op1_addr : ∀ i, a (embed_op1 i) = op1_addr i)
(h_embed_op1 : ∀ i, v (embed_op1 i) = op1 i)
(h_embed_rc_addr : ∀ i, a (embed_rc i) = rc_addr i)
(h_embed_rc : ∀ i, v (embed_rc i) = rc_val i)
(h_embed_dom : ∀ i : mem_dom mem_star, a (embed_mem i) = 0)
(h_embed_val : ∀ i : mem_dom mem_star, v (embed_mem i) = 0)
(h_embed_mem_inj : function.injective embed_mem)
(h_embed_mem_disj_inst : ∀ i j, embed_mem i ≠ embed_inst j)
(h_embed_mem_disj_dst : ∀ i j, embed_mem i ≠ embed_dst j)
(h_embed_mem_disj_op0 : ∀ i j, embed_mem i ≠ embed_op0 j)
(h_embed_mem_disj_op1 : ∀ i j, embed_mem i ≠ embed_op1 j)
(h_embed_mem_disj_rc : ∀ i j, embed_mem i ≠ embed_rc j)
structure memory_block_constraints {F : Type*} [field F] [fintype F]
(n : nat)
(a : fin (n + 1) → F)
(v : fin (n + 1) → F)
(mem_star : F → option F) :=
(a' : fin (n + 1) → F)
(v' : fin (n + 1) → F)
(p : fin (n + 1) → F)
(alpha : F)
(z : F)
(h_continuity : ∀ i : fin n, (a' i.succ - a' i.cast_succ) * (a' i.succ - a' i.cast_succ - 1) = 0)
(h_single_valued : ∀ i : fin n, (v' i.succ - v' i.cast_succ) * (a' i.succ - a' i.cast_succ - 1) = 0)
(h_initial : (z - (a' 0 + alpha * v' 0)) * p 0 = z - (a 0 + alpha * v 0))
(h_cumulative : ∀ i : fin n, (z - (a' i.succ + alpha * v' i.succ)) * p i.succ =
(z - (a i.succ + alpha * v i.succ)) * p i.cast_succ)
(h_final : p (fin.last n) * ∏ a : mem_dom mem_star, (z - (a.val + alpha * mem_val a)) =
z^(fintype.card (mem_dom mem_star)))
structure memory_constraints {F : Type*} [field F] [fintype F]
(T : nat)
(rc_len : nat)
(pc : fin T → F)
(inst : fin T → F)
(dst_addr : fin T → F)
(dst : fin T → F)
(op0_addr : fin T → F)
(op0 : fin T → F)
(op1_addr : fin T → F)
(op1 : fin T → F)
(rc_addr : fin rc_len → F) -- range check builtin
(rc_val : fin rc_len → F)
(mem_star : F → option F) :=
(n : nat)
(a : fin (n + 1) → F)
(v : fin (n + 1) → F)
(em : memory_embedding_constraints T rc_len pc inst dst_addr dst op0_addr op0 op1_addr op1
rc_addr rc_val mem_star n a v)
(mb : memory_block_constraints n a v mem_star)
(h_n_lt : n < ring_char F)
/-
Range check constraints.
-/
structure range_check_constraints {F : Type*} [field F]
(T : nat)
(rc16_len : nat)
(off_op0_tilde : fin T → F)
(off_op1_tilde : fin T → F)
(off_dst_tilde : fin T → F)
(rc16_val : fin rc16_len → F)
(rc_min : nat)
(rc_max : nat) :=
(n : nat)
(a : fin (n + 1) → F)
(a' : fin (n + 1) → F)
(p : fin (n + 1) → F)
(z : F)
/- embedding of `op0`, `op1`, and `dst` data in `a` -/
(embed_off_op0 : fin T → fin (n + 1))
(embed_off_op1 : fin T → fin (n + 1))
(embed_off_dst : fin T → fin (n + 1))
(embed_rc16_vals : fin rc16_len → fin (n + 1))
(h_embed_op0 : ∀ i, a (embed_off_op0 i) = off_op0_tilde i)
(h_embed_op1 : ∀ i, a (embed_off_op1 i) = off_op1_tilde i)
(h_embed_dst : ∀ i, a (embed_off_dst i) = off_dst_tilde i)
(h_embed_rc16 : ∀ i, a (embed_rc16_vals i) = rc16_val i)
/- constraints -/
(h_continuity : ∀ i : fin n, (a' i.succ - a' i.cast_succ) * (a' i.succ - a' i.cast_succ - 1) = 0)
(h_initial : (z - a' 0) * p 0 = z - a 0)
(h_cumulative : ∀ i : fin n, (z - a' i.succ) * p i.succ = (z - a i.succ) * p i.cast_succ)
(h_final : p (fin.last n) = 1)
(h_rc_min : a' 0 = rc_min)
(h_rc_max : a' (fin.last n) = rc_max)
(h_n_lt : n < ring_char F)
/-
Constraints for each instruction.
-/
structure instruction_constraints {F : Type*} [field F]
(inst : F)
(off_op0_tilde : F)
(off_op1_tilde : F)
(off_dst_tilde : F)
(f_tilde : tilde_type F) :=
(h_instruction : inst = off_dst_tilde + 2^16 * off_op0_tilde + 2^32 * off_op1_tilde +
2^48 * f_tilde 0)
(h_bit : ∀ i : fin 15, f_tilde.to_f i * (f_tilde.to_f i - 1) = 0)
(h_last_value : f_tilde ⟨15, by norm_num⟩ = 0)
/-
Constraints relating each state to the next one.
-/
structure step_constraints {F : Type*} [field F]
(off_op0_tilde : F)
(off_op1_tilde : F)
(off_dst_tilde : F)
(f_tilde : tilde_type F)
(fp : F)
(ap : F)
(pc : F)
(next_fp : F)
(next_ap : F)
(next_pc : F)
(dst_addr : F)
(op0_addr : F)
(op1_addr : F)
(dst : F)
(op0 : F)
(op1 : F) :=
(mul : F)
(res : F)
(t0 : F)
(t1 : F)
(h_dst_addr : dst_addr = f_tilde.f_dst_reg * fp + (1 - f_tilde.f_dst_reg) * ap +
(off_dst_tilde - 2^15))
(h_op0_addr : op0_addr = f_tilde.f_op0_reg * fp + (1 - f_tilde.f_op0_reg) * ap +
(off_op0_tilde - 2^15))
(h_op1_addr : op1_addr = f_tilde.f_op1_imm * pc + f_tilde.f_op1_ap * ap +
f_tilde.f_op1_fp * fp +
(1 - f_tilde.f_op1_imm - f_tilde.f_op1_ap - f_tilde.f_op1_fp) * op0 +
(off_op1_tilde - 2^15))
(h_mul : mul = op0 * op1)
(h_res : (1 - f_tilde.f_pc_jnz) * res =
f_tilde.f_res_add * (op0 + op1) + f_tilde.f_res_mul * mul +
(1 - f_tilde.f_res_add - f_tilde.f_res_mul - f_tilde.f_pc_jnz) * op1)
(h_t0_eq : t0 = f_tilde.f_pc_jnz * dst)
(h_t1_eq : t1 = t0 * res)
(h_next_pc_eq : (t1 - f_tilde.f_pc_jnz) * (next_pc - (pc + (f_tilde.f_op1_imm + 1))) = 0)
(h_next_pc_eq' : t0 * (next_pc - (pc + op1)) + (1 - f_tilde.f_pc_jnz) * next_pc -
((1 - f_tilde.f_pc_jump_abs - f_tilde.f_pc_jump_rel - f_tilde.f_pc_jnz) *
(pc + (f_tilde.f_op1_imm + 1)) +
f_tilde.f_pc_jump_abs * res + f_tilde.f_pc_jump_rel * (pc + res))
= 0)
(h_opcode_call : f_tilde.f_opcode_call * (dst - fp) = 0)
(h_opcode_call' : f_tilde.f_opcode_call * (op0 - (pc + (f_tilde.f_op1_imm + 1))) = 0)
(h_opcode_assert_eq : f_tilde.f_opcode_assert_eq * (dst - res) = 0)
(h_next_ap : next_ap = ap + f_tilde.f_ap_add * res + f_tilde.f_ap_add1 +
f_tilde.f_opcode_call * 2)
(h_next_fp : next_fp = f_tilde.f_opcode_ret * dst + f_tilde.f_opcode_call * (ap + 2) +
(1 - f_tilde.f_opcode_ret - f_tilde.f_opcode_call) * fp)
/-
Constraints defining the range check builtin.
-/
structure rc_builtin_constraints {F : Type*} [field F]
(rc16_len : ℕ)
(initial_rc_addr : ℕ)
(rc_len : ℕ)
(rc16_val : fin rc16_len → F)
(rc_addr : fin rc_len → F) -- rc_builtin__mem__addr
(rc_val : fin rc_len → F) -- rc_builtin__mem__value
(rc_to_rc16 : fin rc_len → fin 8 → fin rc16_len) :=
(h_rc_init_addr : ∀ h : 0 < rc_len, rc_addr ⟨0, h⟩ = initial_rc_addr)
(h_rc_addr_step : ∀ i : ℕ, ∀ h : i.succ < rc_len,
rc_addr ⟨i.succ, h⟩ = rc_addr ⟨i, (nat.lt_succ_self _).trans h⟩ + 1)
(h_rc_value : ∀ i : fin rc_len,
rc_val i = (((((((rc16_val (rc_to_rc16 i 0))
* 2^16 + rc16_val (rc_to_rc16 i 1))
* 2^16 + rc16_val (rc_to_rc16 i 2))
* 2^16 + rc16_val (rc_to_rc16 i 3))
* 2^16 + rc16_val (rc_to_rc16 i 4))
* 2^16 + rc16_val (rc_to_rc16 i 5))
* 2^16 + rc16_val (rc_to_rc16 i 6))
* 2^16 + rc16_val (rc_to_rc16 i 7))
/-
All the trace data and constraints (except for the probabilistic assumptions, and assumption
`char F > 2^16`)
-/
structure constraints {F : Type*} [field F] [fintype F] (inp : input_data_aux F) :=
/- the execution trace -/
(fp : fin (inp.T + 1) → F)
(ap : fin (inp.T + 1) → F)
(pc : fin (inp.T + 1) → F)
/- the sequence of instructions -/
(inst : fin inp.T → F)
(off_op0_tilde : fin inp.T → F)
(off_op1_tilde : fin inp.T → F)
(off_dst_tilde : fin inp.T → F)
(rc16_val : fin inp.rc16_len → F)
(f_tilde : fin inp.T → tilde_type F)
/- the memory accesses-/
(dst_addr : fin inp.T → F)
(dst : fin inp.T → F)
(op0_addr : fin inp.T → F)
(op0 : fin inp.T → F)
(op1_addr : fin inp.T → F)
(op1 : fin inp.T → F)
(rc_addr : fin inp.rc_len → F)
(rc_val : fin inp.rc_len → F)
/- starting and ending constraints -/
(h_pc_I : pc 0 = inp.pc_I)
(h_ap_I : ap 0 = inp.ap_I)
(h_fp_I : fp 0 = inp.ap_I)
(h_pc_F : pc (fin.last inp.T) = inp.pc_F)
(h_ap_F : ap (fin.last inp.T) = inp.ap_F)
/- the main constraints -/
(mc : memory_constraints inp.T inp.rc_len (λ i : fin inp.T, pc (i.cast_succ)) inst
dst_addr dst op0_addr op0 op1_addr op1 rc_addr rc_val inp.mem_star)
(rc : range_check_constraints inp.T inp.rc16_len off_op0_tilde off_op1_tilde off_dst_tilde
rc16_val inp.rc_min inp.rc_max)
(ic : ∀ i : fin inp.T, instruction_constraints
(inst i)
(off_op0_tilde i)
(off_op1_tilde i)
(off_dst_tilde i)
(f_tilde i))
(sc : ∀ i : fin inp.T, step_constraints
(off_op0_tilde i)
(off_op1_tilde i)
(off_dst_tilde i)
(f_tilde i)
(fp i.cast_succ)
(ap i.cast_succ)
(pc i.cast_succ)
(fp i.succ)
(ap i.succ)
(pc i.succ)
(dst_addr i)
(op0_addr i)
(op1_addr i)
(dst i)
(op0 i)
(op1 i))
(rcb : rc_builtin_constraints
inp.rc16_len
inp.initial_rc_addr
inp.rc_len
rc16_val
rc_addr
rc_val
inp.rc_to_rc16)
|
224748f81994d8b8938e60bd60adc9b099016df7 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/topology/metric_space/contracting.lean | 29fc63fb6e2502fc7b30687cd833e5ba1b6674cd | [
"Apache-2.0"
] | permissive | jjgarzella/mathlib | 96a345378c4e0bf26cf604aed84f90329e4896a2 | 395d8716c3ad03747059d482090e2bb97db612c8 | refs/heads/master | 1,686,480,124,379 | 1,625,163,323,000 | 1,625,163,323,000 | 281,190,421 | 2 | 0 | Apache-2.0 | 1,595,268,170,000 | 1,595,268,169,000 | null | UTF-8 | Lean | false | false | 15,248 | lean | /-
Copyright (c) 2019 Rohan Mitta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Rohan Mitta, Kevin Buzzard, Alistair Tucker, Johannes Hölzl, Yury Kudryashov
-/
import analysis.specific_limits
import data.setoid.basic
import dynamics.fixed_points.topology
/-!
# Contracting maps
A Lipschitz continuous self-map with Lipschitz constant `K < 1` is called a *contracting map*.
In this file we prove the Banach fixed point theorem, some explicit estimates on the rate
of convergence, and some properties of the map sending a contracting map to its fixed point.
## Main definitions
* `contracting_with K f` : a Lipschitz continuous self-map with `K < 1`;
* `efixed_point` : given a contracting map `f` on a complete emetric space and a point `x`
such that `edist x (f x) < ∞`, `efixed_point f hf x hx` is the unique fixed point of `f`
in `emetric.ball x ∞`;
* `fixed_point` : the unique fixed point of a contracting map on a complete nonempty metric space.
## Tags
contracting map, fixed point, Banach fixed point theorem
-/
open_locale nnreal topological_space classical ennreal
open filter function
variables {α : Type*}
/-- A map is said to be `contracting_with K`, if `K < 1` and `f` is `lipschitz_with K`. -/
def contracting_with [emetric_space α] (K : ℝ≥0) (f : α → α) :=
(K < 1) ∧ lipschitz_with K f
namespace contracting_with
variables [emetric_space α] [cs : complete_space α] {K : ℝ≥0} {f : α → α}
open emetric set
lemma to_lipschitz_with (hf : contracting_with K f) : lipschitz_with K f := hf.2
lemma one_sub_K_pos' (hf : contracting_with K f) : (0:ℝ≥0∞) < 1 - K := by simp [hf.1]
lemma one_sub_K_ne_zero (hf : contracting_with K f) : (1:ℝ≥0∞) - K ≠ 0 :=
ne_of_gt hf.one_sub_K_pos'
lemma one_sub_K_ne_top : (1:ℝ≥0∞) - K ≠ ⊤ :=
by { norm_cast, exact ennreal.coe_ne_top }
lemma edist_inequality (hf : contracting_with K f) {x y} (h : edist x y < ⊤) :
edist x y ≤ (edist x (f x) + edist y (f y)) / (1 - K) :=
suffices edist x y ≤ edist x (f x) + edist y (f y) + K * edist x y,
by rwa [ennreal.le_div_iff_mul_le (or.inl hf.one_sub_K_ne_zero) (or.inl one_sub_K_ne_top),
mul_comm, ennreal.sub_mul (λ _ _, ne_of_lt h), one_mul, ennreal.sub_le_iff_le_add],
calc edist x y ≤ edist x (f x) + edist (f x) (f y) + edist (f y) y : edist_triangle4 _ _ _ _
... = edist x (f x) + edist y (f y) + edist (f x) (f y) : by rw [edist_comm y, add_right_comm]
... ≤ edist x (f x) + edist y (f y) + K * edist x y : add_le_add (le_refl _) (hf.2 _ _)
lemma edist_le_of_fixed_point (hf : contracting_with K f) {x y}
(h : edist x y < ⊤) (hy : is_fixed_pt f y) :
edist x y ≤ (edist x (f x)) / (1 - K) :=
by simpa only [hy.eq, edist_self, add_zero] using hf.edist_inequality h
lemma eq_or_edist_eq_top_of_fixed_points (hf : contracting_with K f) {x y}
(hx : is_fixed_pt f x) (hy : is_fixed_pt f y) :
x = y ∨ edist x y = ⊤ :=
begin
cases eq_or_lt_of_le (le_top : edist x y ≤ ⊤), from or.inr h,
refine or.inl (edist_le_zero.1 _),
simpa only [hx.eq, edist_self, add_zero, ennreal.zero_div]
using hf.edist_le_of_fixed_point h hy
end
/-- If a map `f` is `contracting_with K`, and `s` is a forward-invariant set, then
restriction of `f` to `s` is `contracting_with K` as well. -/
lemma restrict (hf : contracting_with K f) {s : set α} (hs : maps_to f s s) :
contracting_with K (hs.restrict f s s) :=
⟨hf.1, λ x y, hf.2 x y⟩
include cs
/-- Banach fixed-point theorem, contraction mapping theorem, `emetric_space` version.
A contracting map on a complete metric space has a fixed point.
We include more conclusions in this theorem to avoid proving them again later.
The main API for this theorem are the functions `efixed_point` and `fixed_point`,
and lemmas about these functions. -/
theorem exists_fixed_point (hf : contracting_with K f) (x : α) (hx : edist x (f x) < ⊤) :
∃ y, is_fixed_pt f y ∧ tendsto (λ n, f^[n] x) at_top (𝓝 y) ∧
∀ n:ℕ, edist (f^[n] x) y ≤ (edist x (f x)) * K^n / (1 - K) :=
have cauchy_seq (λ n, f^[n] x),
from cauchy_seq_of_edist_le_geometric K (edist x (f x)) (ennreal.coe_lt_one_iff.2 hf.1)
(ne_of_lt hx) (hf.to_lipschitz_with.edist_iterate_succ_le_geometric x),
let ⟨y, hy⟩ := cauchy_seq_tendsto_of_complete this in
⟨y, is_fixed_pt_of_tendsto_iterate hy hf.2.continuous.continuous_at, hy,
edist_le_of_edist_le_geometric_of_tendsto K (edist x (f x))
(hf.to_lipschitz_with.edist_iterate_succ_le_geometric x) hy⟩
variable (f) -- avoid `efixed_point _` in pretty printer
/-- Let `x` be a point of a complete emetric space. Suppose that `f` is a contracting map,
and `edist x (f x) < ∞`. Then `efixed_point` is the unique fixed point of `f`
in `emetric.ball x ∞`. -/
noncomputable def efixed_point (hf : contracting_with K f) (x : α) (hx : edist x (f x) < ⊤) :
α :=
classical.some $ hf.exists_fixed_point x hx
variables {f}
lemma efixed_point_is_fixed_pt (hf : contracting_with K f) {x : α} (hx : edist x (f x) < ⊤) :
is_fixed_pt f (efixed_point f hf x hx) :=
(classical.some_spec $ hf.exists_fixed_point x hx).1
lemma tendsto_iterate_efixed_point (hf : contracting_with K f) {x : α} (hx : edist x (f x) < ⊤) :
tendsto (λn, f^[n] x) at_top (𝓝 $ efixed_point f hf x hx) :=
(classical.some_spec $ hf.exists_fixed_point x hx).2.1
lemma apriori_edist_iterate_efixed_point_le (hf : contracting_with K f)
{x : α} (hx : edist x (f x) < ⊤) (n : ℕ) :
edist (f^[n] x) (efixed_point f hf x hx) ≤ (edist x (f x)) * K^n / (1 - K) :=
(classical.some_spec $ hf.exists_fixed_point x hx).2.2 n
lemma edist_efixed_point_le (hf : contracting_with K f) {x : α} (hx : edist x (f x) < ⊤) :
edist x (efixed_point f hf x hx) ≤ (edist x (f x)) / (1 - K) :=
by { convert hf.apriori_edist_iterate_efixed_point_le hx 0, simp only [pow_zero, mul_one] }
lemma edist_efixed_point_lt_top (hf : contracting_with K f) {x : α} (hx : edist x (f x) < ⊤) :
edist x (efixed_point f hf x hx) < ⊤ :=
lt_of_le_of_lt (hf.edist_efixed_point_le hx) (ennreal.mul_lt_top hx $
ennreal.lt_top_iff_ne_top.2 $ ennreal.inv_ne_top.2 hf.one_sub_K_ne_zero)
lemma efixed_point_eq_of_edist_lt_top (hf : contracting_with K f) {x : α} (hx : edist x (f x) < ⊤)
{y : α} (hy : edist y (f y) < ⊤) (h : edist x y < ⊤) :
efixed_point f hf x hx = efixed_point f hf y hy :=
begin
refine (hf.eq_or_edist_eq_top_of_fixed_points _ _).elim id (λ h', false.elim (ne_of_lt _ h'));
try { apply efixed_point_is_fixed_pt },
change edist_lt_top_setoid.rel _ _,
transitivity x, by { symmetry, exact hf.edist_efixed_point_lt_top hx },
transitivity y,
exacts [h, hf.edist_efixed_point_lt_top hy]
end
omit cs
/-- Banach fixed-point theorem for maps contracting on a complete subset. -/
theorem exists_fixed_point' {s : set α} (hsc : is_complete s) (hsf : maps_to f s s)
(hf : contracting_with K $ hsf.restrict f s s) {x : α} (hxs : x ∈ s) (hx : edist x (f x) < ⊤) :
∃ y ∈ s, is_fixed_pt f y ∧ tendsto (λ n, f^[n] x) at_top (𝓝 y) ∧
∀ n:ℕ, edist (f^[n] x) y ≤ (edist x (f x)) * K^n / (1 - K) :=
begin
haveI := hsc.complete_space_coe,
rcases hf.exists_fixed_point ⟨x, hxs⟩ hx with ⟨y, hfy, h_tendsto, hle⟩,
refine ⟨y, y.2, subtype.ext_iff_val.1 hfy, _, λ n, _⟩,
{ convert (continuous_subtype_coe.tendsto _).comp h_tendsto, ext n,
simp only [(∘), maps_to.iterate_restrict, maps_to.coe_restrict_apply, subtype.coe_mk] },
{ convert hle n,
rw [maps_to.iterate_restrict, eq_comm, maps_to.coe_restrict_apply, subtype.coe_mk] }
end
variable (f) -- avoid `efixed_point _` in pretty printer
/-- Let `s` be a complete forward-invariant set of a self-map `f`. If `f` contracts on `s`
and `x ∈ s` satisfies `edist x (f x) < ⊤`, then `efixed_point'` is the unique fixed point
of the restriction of `f` to `s ∩ emetric.ball x ⊤`. -/
noncomputable def efixed_point' {s : set α} (hsc : is_complete s) (hsf : maps_to f s s)
(hf : contracting_with K $ hsf.restrict f s s) (x : α) (hxs : x ∈ s) (hx : edist x (f x) < ⊤) :
α :=
classical.some $ hf.exists_fixed_point' hsc hsf hxs hx
variables {f}
lemma efixed_point_mem' {s : set α} (hsc : is_complete s) (hsf : maps_to f s s)
(hf : contracting_with K $ hsf.restrict f s s) {x : α} (hxs : x ∈ s) (hx : edist x (f x) < ⊤) :
efixed_point' f hsc hsf hf x hxs hx ∈ s :=
(classical.some_spec $ hf.exists_fixed_point' hsc hsf hxs hx).fst
lemma efixed_point_is_fixed_pt' {s : set α} (hsc : is_complete s) (hsf : maps_to f s s)
(hf : contracting_with K $ hsf.restrict f s s) {x : α} (hxs : x ∈ s) (hx : edist x (f x) < ⊤) :
is_fixed_pt f (efixed_point' f hsc hsf hf x hxs hx) :=
(classical.some_spec $ hf.exists_fixed_point' hsc hsf hxs hx).snd.1
lemma tendsto_iterate_efixed_point' {s : set α} (hsc : is_complete s) (hsf : maps_to f s s)
(hf : contracting_with K $ hsf.restrict f s s) {x : α} (hxs : x ∈ s) (hx : edist x (f x) < ⊤) :
tendsto (λn, f^[n] x) at_top (𝓝 $ efixed_point' f hsc hsf hf x hxs hx) :=
(classical.some_spec $ hf.exists_fixed_point' hsc hsf hxs hx).snd.2.1
lemma apriori_edist_iterate_efixed_point_le' {s : set α} (hsc : is_complete s)
(hsf : maps_to f s s) (hf : contracting_with K $ hsf.restrict f s s) {x : α} (hxs : x ∈ s)
(hx : edist x (f x) < ⊤) (n : ℕ) :
edist (f^[n] x) (efixed_point' f hsc hsf hf x hxs hx) ≤ (edist x (f x)) * K^n / (1 - K) :=
(classical.some_spec $ hf.exists_fixed_point' hsc hsf hxs hx).snd.2.2 n
lemma edist_efixed_point_le' {s : set α} (hsc : is_complete s) (hsf : maps_to f s s)
(hf : contracting_with K $ hsf.restrict f s s) {x : α} (hxs : x ∈ s) (hx : edist x (f x) < ⊤) :
edist x (efixed_point' f hsc hsf hf x hxs hx) ≤ (edist x (f x)) / (1 - K) :=
by { convert hf.apriori_edist_iterate_efixed_point_le' hsc hsf hxs hx 0,
rw [pow_zero, mul_one] }
lemma edist_efixed_point_lt_top' {s : set α} (hsc : is_complete s) (hsf : maps_to f s s)
(hf : contracting_with K $ hsf.restrict f s s) {x : α} (hxs : x ∈ s) (hx : edist x (f x) < ⊤) :
edist x (efixed_point' f hsc hsf hf x hxs hx) < ⊤ :=
lt_of_le_of_lt (hf.edist_efixed_point_le' hsc hsf hxs hx) (ennreal.mul_lt_top hx $
ennreal.lt_top_iff_ne_top.2 $ ennreal.inv_ne_top.2 hf.one_sub_K_ne_zero)
/-- If a globally contracting map `f` has two complete forward-invariant sets `s`, `t`,
and `x ∈ s` is at a finite distance from `y ∈ t`, then the `efixed_point'` constructed by `x`
is the same as the `efixed_point'` constructed by `y`.
This lemma takes additional arguments stating that `f` contracts on `s` and `t` because this way
it can be used to prove the desired equality with non-trivial proofs of these facts. -/
lemma efixed_point_eq_of_edist_lt_top' (hf : contracting_with K f)
{s : set α} (hsc : is_complete s) (hsf : maps_to f s s)
(hfs : contracting_with K $ hsf.restrict f s s) {x : α} (hxs : x ∈ s) (hx : edist x (f x) < ⊤)
{t : set α} (htc : is_complete t) (htf : maps_to f t t)
(hft : contracting_with K $ htf.restrict f t t) {y : α} (hyt : y ∈ t) (hy : edist y (f y) < ⊤)
(hxy : edist x y < ⊤) :
efixed_point' f hsc hsf hfs x hxs hx = efixed_point' f htc htf hft y hyt hy :=
begin
refine (hf.eq_or_edist_eq_top_of_fixed_points _ _).elim id (λ h', false.elim (ne_of_lt _ h'));
try { apply efixed_point_is_fixed_pt' },
change edist_lt_top_setoid.rel _ _,
transitivity x, by { symmetry, apply edist_efixed_point_lt_top' },
transitivity y,
exact hxy,
apply edist_efixed_point_lt_top'
end
end contracting_with
namespace contracting_with
variables [metric_space α] {K : ℝ≥0} {f : α → α} (hf : contracting_with K f)
include hf
lemma one_sub_K_pos (hf : contracting_with K f) : (0:ℝ) < 1 - K := sub_pos.2 hf.1
lemma dist_le_mul (x y : α) : dist (f x) (f y) ≤ K * dist x y :=
hf.to_lipschitz_with.dist_le_mul x y
lemma dist_inequality (x y) : dist x y ≤ (dist x (f x) + dist y (f y)) / (1 - K) :=
suffices dist x y ≤ dist x (f x) + dist y (f y) + K * dist x y,
by rwa [le_div_iff hf.one_sub_K_pos, mul_comm, sub_mul, one_mul, sub_le_iff_le_add],
calc dist x y ≤ dist x (f x) + dist y (f y) + dist (f x) (f y) : dist_triangle4_right _ _ _ _
... ≤ dist x (f x) + dist y (f y) + K * dist x y :
add_le_add_left (hf.dist_le_mul _ _) _
lemma dist_le_of_fixed_point (x) {y} (hy : is_fixed_pt f y) :
dist x y ≤ (dist x (f x)) / (1 - K) :=
by simpa only [hy.eq, dist_self, add_zero] using hf.dist_inequality x y
theorem fixed_point_unique' {x y} (hx : is_fixed_pt f x) (hy : is_fixed_pt f y) : x = y :=
(hf.eq_or_edist_eq_top_of_fixed_points hx hy).resolve_right (edist_ne_top _ _)
/-- Let `f` be a contracting map with constant `K`; let `g` be another map uniformly
`C`-close to `f`. If `x` and `y` are their fixed points, then `dist x y ≤ C / (1 - K)`. -/
lemma dist_fixed_point_fixed_point_of_dist_le' (g : α → α)
{x y} (hx : is_fixed_pt f x) (hy : is_fixed_pt g y) {C} (hfg : ∀ z, dist (f z) (g z) ≤ C) :
dist x y ≤ C / (1 - K) :=
calc dist x y = dist y x : dist_comm x y
... ≤ (dist y (f y)) / (1 - K) : hf.dist_le_of_fixed_point y hx
... = (dist (f y) (g y)) / (1 - K) : by rw [hy.eq, dist_comm]
... ≤ C / (1 - K) : (div_le_div_right hf.one_sub_K_pos).2 (hfg y)
noncomputable theory
variables [nonempty α] [complete_space α]
variable (f)
/-- The unique fixed point of a contracting map in a nonempty complete metric space. -/
def fixed_point : α :=
efixed_point f hf _ (edist_lt_top (classical.choice ‹nonempty α›) _)
variable {f}
/-- The point provided by `contracting_with.fixed_point` is actually a fixed point. -/
lemma fixed_point_is_fixed_pt : is_fixed_pt f (fixed_point f hf) :=
hf.efixed_point_is_fixed_pt _
lemma fixed_point_unique {x} (hx : is_fixed_pt f x) : x = fixed_point f hf :=
hf.fixed_point_unique' hx hf.fixed_point_is_fixed_pt
lemma dist_fixed_point_le (x) : dist x (fixed_point f hf) ≤ (dist x (f x)) / (1 - K) :=
hf.dist_le_of_fixed_point x hf.fixed_point_is_fixed_pt
/-- Aposteriori estimates on the convergence of iterates to the fixed point. -/
lemma aposteriori_dist_iterate_fixed_point_le (x n) :
dist (f^[n] x) (fixed_point f hf) ≤ (dist (f^[n] x) (f^[n+1] x)) / (1 - K) :=
by { rw [iterate_succ'], apply hf.dist_fixed_point_le }
lemma apriori_dist_iterate_fixed_point_le (x n) :
dist (f^[n] x) (fixed_point f hf) ≤ (dist x (f x)) * K^n / (1 - K) :=
le_trans (hf.aposteriori_dist_iterate_fixed_point_le x n) $
(div_le_div_right hf.one_sub_K_pos).2 $
hf.to_lipschitz_with.dist_iterate_succ_le_geometric x n
lemma tendsto_iterate_fixed_point (x) :
tendsto (λn, f^[n] x) at_top (𝓝 $ fixed_point f hf) :=
begin
convert tendsto_iterate_efixed_point hf (edist_lt_top x _),
refine (fixed_point_unique _ _).symm,
apply efixed_point_is_fixed_pt
end
lemma fixed_point_lipschitz_in_map {g : α → α} (hg : contracting_with K g)
{C} (hfg : ∀ z, dist (f z) (g z) ≤ C) :
dist (fixed_point f hf) (fixed_point g hg) ≤ C / (1 - K) :=
hf.dist_fixed_point_fixed_point_of_dist_le' g hf.fixed_point_is_fixed_pt
hg.fixed_point_is_fixed_pt hfg
end contracting_with
|
a497bf121201bff3b61ccd9a362c8ed2a3f67869 | 43390109ab88557e6090f3245c47479c123ee500 | /src/Topology/Material/fundamental_group.lean | d8cd0617d6328a2e9a13b082502da775683aacc7 | [
"Apache-2.0"
] | permissive | Ja1941/xena-UROP-2018 | 41f0956519f94d56b8bf6834a8d39473f4923200 | b111fb87f343cf79eca3b886f99ee15c1dd9884b | refs/heads/master | 1,662,355,955,139 | 1,590,577,325,000 | 1,590,577,325,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 10,189 | lean | /-
Copyright (c) 2018 Luca Gerolla. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Luca Gerolla, Kevin Buzzard
Fundamental Group of pointed space, inverse, reparametrisation for fundamental group.
-/
import analysis.topology.continuity
import analysis.topology.topological_space
import analysis.topology.infinite_sum
import analysis.topology.topological_structures
import analysis.topology.uniform_space
import analysis.real
import data.real.basic tactic.norm_num
import data.set.basic
import Topology.Material.pasting_lemma
import Topology.Material.path
import Topology.Material.homotopy
import Topology.Material.homotopy_results
open set filter lattice classical
---------------------------------------------------
---------------------------------------------------
---- FUNDAMENTAL GROUP
namespace fundamental_group
open homotopy_results
open homotopy
open path
section
variables {α : Type*} [topological_space α ] {x y : α }
instance setoid_hom_path (x : α) : setoid (path x x) :=
setoid.mk is_homotopic_to (is_equivalence)
instance setoid_hom_loop (x : α) : setoid (loop x) :=
by unfold loop; apply_instance
definition space_π₁ (x : α) := quotient (fundamental_group.setoid_hom_loop x)
def eq_class ( f : loop x ) : space_π₁ x := quotient.mk f
--
-- Definition of identity and inverse classes
def id_eq_class (x : α ) : space_π₁ x := ⟦ loop_const x ⟧
lemma inv_eq_class_aux : ∀ (a b : path x x),
a ≈ b → ⟦ inv_of_path a ⟧ = ⟦ inv_of_path b ⟧ :=
begin
intros a b Hab, apply quotient.sound,
cases Hab, existsi _,
exact path_homotopy_of_inv_path Hab,
end
def inv_eq_class : space_π₁ x → space_π₁ x :=
quotient.lift ( λ f, ⟦ inv_of_path f ⟧ ) inv_eq_class_aux
-- Definition of multiplication on π₁
lemma mul_aux : ∀ (a₁ a₂ b₁ b₂ : loop x), a₁ ≈ b₁ → a₂ ≈ b₂ →
⟦comp_of_path a₁ a₂⟧ = ⟦comp_of_path b₁ b₂⟧ :=
begin
intros a₁ a₂ b₁ b₂ H₁ H₂, apply quotient.sound,
cases H₁ , cases H₂ , existsi _,
exact path_homotopy_of_comp_path H₁ H₂,
end
protected noncomputable def mul : space_π₁ x → space_π₁ x → space_π₁ x :=
quotient.lift₂ (λ f g, ⟦comp_of_path f g⟧) mul_aux
-- Interface
instance coe_loop_π₁ : has_coe (loop x) (space_π₁ x) := ⟨eq_class⟩
-- To break down mul proofs and use quotient.sound
lemma quotient.out_eq' ( F : space_π₁ x) : F = ⟦ quotient.out F ⟧ :=
begin apply eq.symm, exact quotient.out_eq _, end
---------------------------------------------
local notation `fg_mul` := fundamental_group.mul
local attribute [instance] classical.prop_decidable
-----------------------------------------------
-- Identity Elememt
---- Right identity - mul_one
noncomputable def p1 : repar_I01 :=
{ to_fun := λ t, (paste cover_I01 (λ s, par zero_lt_half s ) (λ s, 1) ) t ,
at_zero := begin unfold paste, rw dif_pos, swap, exact help_T1, simp end,
at_one := begin unfold paste, rw dif_neg, exact help_02 end,
cont := begin simp, refine cont_of_paste _ _ _ (continuous_par _) continuous_const,
exact T1_is_closed,
exact T2_is_closed,
unfold match_of_fun, intros x B1 B2,
have Int : x ∈ set.inter T1 T2, exact ⟨ B1 , B2 ⟩ ,
rwa [inter_T] at Int,
have V : x.val = 1/2, rwa [mem_set_of_eq] at Int,
have xeq : x = (⟨ 1/2 , help_01 ⟩ : I01 ) , apply subtype.eq, rw V,
simp [xeq, -one_div_eq_inv],
show par zero_lt_half ⟨⟨1 / 2, help_01⟩, help_half_T1⟩ = 1, exact eqn_1,
end
}
--mul a (id_eq_class x) = a
noncomputable def hom_f_const_to_f ( f : path x y) : path_homotopy (comp_of_path f (loop_const y)) f :=
begin
have H : comp_of_path f (loop_const y) = repar_path f p1,
{ apply path_equal.2, unfold comp_of_path repar_path, simp, unfold fa_path fb_path fgen_path loop_const p1, simp, unfold par, funext,
unfold paste, split_ifs, simp [-one_div_eq_inv], simp,
},
rw H, exact hom_repar_path_to_path f p1,
end
-- f ⬝ c ≈ f by using homotopy f → f ⬝ c above -- NOT NEEDED for mul_one
lemma path_const_homeq_path ( f : path x y) : is_homotopic_to (comp_of_path f (loop_const y)) f :=
begin unfold is_homotopic_to, refine nonempty.intro (hom_f_const_to_f f), end
-- Now prove [f]*[c] = [f]
theorem mul_one ( F : space_π₁ x) : fg_mul F (id_eq_class x) = F :=
begin
unfold fundamental_group.mul, unfold id_eq_class eq_class, rw [quotient.out_eq' F],
apply quotient.sound, existsi _,
exact hom_f_const_to_f (quotient.out F),
end
--------
---- Left identity - one_mul
noncomputable def p2 : repar_I01 :=
{ to_fun := λ t, (paste cover_I01 (λ s, 0 )(λ s, par half_lt_one s ) ) t ,
at_zero := begin unfold paste, rw dif_pos, exact help_T1, end,
at_one := begin unfold paste, rw dif_neg, exact eqn_end , exact help_02 end,
cont := begin simp, refine cont_of_paste _ _ _ continuous_const (continuous_par _),
exact T1_is_closed,
exact T2_is_closed,
unfold match_of_fun, intros x B1 B2,
have Int : x ∈ set.inter T1 T2, exact ⟨ B1 , B2 ⟩ ,
rwa [inter_T] at Int,
have V : x.val = 1/2, rwa [mem_set_of_eq] at Int,
have xeq : x = (⟨ 1/2 , help_01 ⟩ : I01 ) , apply subtype.eq, rw V,
simp [xeq, -one_div_eq_inv],
show 0 = par half_lt_one ⟨⟨1 / 2, help_01⟩, help_half_T2⟩, apply eq.symm, exact eqn_2
end
}
--mul (id_eq_class x) a = a
noncomputable def hom_const_f_to_f ( f : path x y) : path_homotopy (comp_of_path (loop_const x) f ) f:=
begin
have H : comp_of_path (loop_const x) f = repar_path f p2,
{ apply path_equal.2, unfold comp_of_path repar_path, simp, unfold fa_path fb_path fgen_path loop_const p2, simp, unfold par, funext,
unfold paste, split_ifs, simp [-one_div_eq_inv],
},
rw H, exact hom_repar_path_to_path f p2,
end
-- Now prove [c]*[f] = [f]
theorem one_mul ( F : space_π₁ x) : fg_mul (id_eq_class x) F = F :=
begin
unfold fundamental_group.mul, unfold id_eq_class eq_class, rw [quotient.out_eq' F],
apply quotient.sound, existsi _,
exact hom_const_f_to_f (quotient.out F),
end
--------------------------
----------------------------------------------------
-- Inverse Element
theorem mul_left_inv (F : space_π₁ x) : fg_mul (inv_eq_class F) F = id_eq_class x :=
begin
unfold fundamental_group.mul, unfold id_eq_class eq_class inv_eq_class, rw [quotient.out_eq' F],
apply quotient.sound, existsi _, exact hom_inv_comp_to_const (quotient.out F)
end
---------------------------------------------------
-- Associativity
theorem mul_assoc (F G H: space_π₁ x) : fg_mul (fg_mul F G) H = fg_mul F (fg_mul G H) :=
begin
unfold fundamental_group.mul, rw [quotient.out_eq' F ,quotient.out_eq' G , quotient.out_eq' H],
apply quotient.sound,
existsi _, exact path_homotopy_inverse (
hom_comp_f_g_h (quotient.out F) (quotient.out G) (quotient.out H)),
end
-------------
-- Group π₁ (α , x)
noncomputable def π₁_group (x : α ) : group ( space_π₁ x) :=
{
mul := fundamental_group.mul ,
mul_assoc := fundamental_group.mul_assoc,
one := id_eq_class x ,
one_mul := fundamental_group.one_mul ,
mul_one := fundamental_group.mul_one ,
inv := inv_eq_class ,
mul_left_inv := fundamental_group.mul_left_inv
}
end
----------------------------------------------------------------------
-- Section on π₁ (ℝ , x ) to show ℝ is contractible
section
variable {x : ℝ }
noncomputable theory
-- x in {} or ()?
def c : loop x := loop_const x
def C : space_π₁ x := id_eq_class x
lemma trivial_check (x : ℝ ) : C = ⟦@c x⟧ :=
by unfold C id_eq_class c
-- Define homotopy to show that any loop f in ℝ is homotopic to the constant loop c_x (based at x)
def homotopy_real_fun ( f : loop x ) : I01 × I01 → ℝ :=
λ st, (1 - st.1.1) * f.to_fun (st.2) + st.1.1 * f.to_fun (0)
lemma homotopy_real_start_pt ( f : loop x ) : ∀ (s : I01), homotopy_real_fun f (s, 0) = x :=
begin
intro s, unfold homotopy_real_fun, simp [-sub_eq_add_neg , sub_mul, add_sub, add_sub_assoc, sub_self (s.val * x )],
end
lemma homotopy_real_end_pt ( f : loop x ) : ∀ (s : I01), homotopy_real_fun f (s, 1) = x :=
begin
intro s, unfold homotopy_real_fun, simp [-sub_eq_add_neg , sub_mul, add_sub, add_sub_assoc, sub_self (s.val * x )],
end
lemma homotopy_real_at_zero ( f : loop x ) : ∀ (y : I01), homotopy_real_fun f (0, y) = f.to_fun y :=
begin
intro t, unfold homotopy_real_fun, have a₁ : (0:I01).val = (0:ℝ), trivial,
simp [-sub_eq_add_neg , a₁ , sub_zero , zero_mul],
end
lemma homotopy_real_at_one ( f : loop x ) : ∀ (y : I01), homotopy_real_fun f (1, y) = (@c x ).to_fun y :=
begin
intro t, unfold homotopy_real_fun c loop_const, have a₁ : (1:I01).val = (1:ℝ), trivial,
simp [a₁],
end
lemma homotopy_real_cont ( f : loop x ) : continuous (homotopy_real_fun f):=
begin
unfold homotopy_real_fun, refine continuous_add _ _,
{ refine continuous_mul _ _,
{ refine continuous_add _ _, exact continuous_const,
exact continuous.comp (continuous.comp continuous_fst continuous_subtype_val) (continuous_neg continuous_id),
},
exact continuous.comp continuous_snd f.cont,
},
refine continuous_mul _ continuous_const,
exact continuous.comp continuous_fst continuous_subtype_val,
end
--Use the above lemmas to define homotopy with path_homotopy.mk' constructor
definition homotopy_real ( f : loop x ) : path_homotopy f c :=
path_homotopy.mk' (homotopy_real_fun f) (homotopy_real_start_pt f) (homotopy_real_end_pt f)
(homotopy_real_at_zero f) (homotopy_real_at_one f) (homotopy_real_cont f)
--------------------------
theorem real_trivial_eq_class (F : space_π₁ x) : F = C :=
begin
rw quotient.out_eq' F, rw trivial_check, apply quotient.sound, existsi _,
exact homotopy_real (quotient.out F),
end
end
--set_option trace.simplify.rewrite true
--set_option pp.implicit true
end fundamental_group |
12c7ce06bdc3a020005c5e878b2226475b08ccc8 | 0c6b99c0daded009943e570c13367c8cc7d3bcae | /chapter8.lean | 16c2e670e794c8fbe7234d35f4ea9c719f98b20d | [] | no_license | TateKennington/logic-and-proof-exercises | e3c5c5b12b6238b47b0c5acf8717923bd471a535 | acca8882026e7b643453eb096d3021cd043005bd | refs/heads/main | 1,687,638,489,616 | 1,626,858,474,000 | 1,626,858,474,000 | 371,871,374 | 4 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,403 | lean | variable U: Type
variables A B C: U → Prop
section
example: (∀x, A x → B x) → ((∀x, A x) → (∀x, B x)) :=
assume h,
assume all_Ax,
assume x,
have Ax: A x, from all_Ax x,
have Ax_imp_Bx: A x → B x , from h x,
show B x, from Ax_imp_Bx Ax
end
section
example (all_Ax_or_Bx: ∀x, A x ∨ B x) (all_nAy: ∀y, ¬A y):
∀x, B x :=
assume x,
have Ax_or_Bx: A x ∨ B x, from all_Ax_or_Bx x,
have nAx: ¬A x, from all_nAy x,
have h₁: A x → B x, from assume Ax: A x, false.elim (nAx Ax),
have h₂: B x → B x, from assume Bx: B x, Bx,
or.elim Ax_or_Bx h₁ h₂
end
section
example: (∃x, A x) ∨ (∃x, B x) → ∃x, A x ∨ B x :=
assume h,
have h₁: (∃x, A x) → ∃x, A x ∨ B x, from
assume h_ex,
exists.elim h_ex $
assume x (Ax: A x),
have A x ∨ B x, from or.inl Ax,
exists.intro x this,
have h₂: (∃x, B x) → ∃x, A x ∨ B x, from
assume h_ex,
exists.elim h_ex $
assume x (Bx: B x),
have A x ∨ B x, from or.inr Bx,
exists.intro x this,
or.elim h h₁ h₂
end
section
example (ex_A_and_B: ∃x, A x ∧ B x) (all_A_and_B_imp_C: ∀x, A x ∧ B x → C x)
: ∃x, A x ∧ C x :=
exists.elim ex_A_and_B $
assume x (Ax_and_Bx: A x ∧ B x),
have Ax_and_Bx_imp_Cx: A x ∧ B x → C x, from all_A_and_B_imp_C x,
have Cx: C x, from Ax_and_Bx_imp_Cx Ax_and_Bx,
have Ax: A x, from and.left Ax_and_Bx,
have Ax_and_Cx: A x ∧ C x, from and.intro Ax Cx,
exists.intro x Ax_and_Cx
end
section
variable P: U → Prop
variable T: U → U → Prop
example (h: ∀x y, P x → ¬T y x): ∀x y, T y x → ¬P x :=
assume x y,
assume Tyx,
show ¬P x, from
assume Px,
have Px_imp_nTyx: P x → ¬T y x, from h x y,
have nTyx: ¬T y x, from Px_imp_nTyx Px,
show false, from nTyx Tyx
example (h: ∀x y, T y x → ¬P x): ∀x y, P x → ¬T y x :=
assume x y,
assume Px,
show ¬T y x, from
assume Tyx,
have Tyx_imp_nPx: T y x → ¬P x, from h x y,
have nPx: ¬P x, from Tyx_imp_nPx Tyx,
show false, from nPx Px
end
section
variables Y H: U → Prop
variable h₁: ∀x, Y x ∧ H x → B x
variable h₂: ∀x, A x → H x
variable h₃: ∃x, Y x ∧ A x
example: ∃x, B x :=
exists.elim h₃ $
assume x (Yx_and_Ax: Y x ∧ A x),
have Yx: Y x, from and.left Yx_and_Ax,
have Ax: A x, from and.right Yx_and_Ax,
have Hx: H x, from h₂ x Ax,
have Y x ∧ H x, from and.intro Yx Hx,
have Bx: B x, from h₁ x this,
exists.intro x Bx
end
section
example: ∀(x:U) y z, x = z → z = y → x = y :=
assume x y z (h₁: x = z) (h₂: z = y),
calc
x = z: h₁
... = y: by rw h₂
end
section
variables x y : U
variable h₁: ∀(x: U), x = x
variable h₂: ∀(u:U) v w, u = w → v = w → u = v
example: x = y → y = x :=
assume h,
have y = y, from h₁ y,
show y = x, from (h₂ y x y) ‹y = y› h
end
section
example: (¬∃x,A x ∧ B x) ↔ (∀x,A x → ¬B x) :=
have h₁: (¬∃x,A x ∧ B x) → (∀x,A x → ¬B x), from
assume h,
assume x,
assume Ax,
show ¬B x, from
assume Bx,
have Ax_and_Bx: A x ∧ B x, from and.intro Ax Bx,
have ∃x, A x ∧ B x, from exists.intro x Ax_and_Bx,
show false, from h this,
have h₂: (∀x,A x → ¬B x) → (¬∃x,A x ∧ B x) , from
assume h,
show ¬∃x,A x ∧ B x, from
assume h_ex,
show false, from exists.elim h_ex $
assume x (Ax_and_Bx: A x ∧ B x),
have Ax: A x, from and.left Ax_and_Bx,
have Bx: B x, from and.right Ax_and_Bx,
have Ax_imp_nBx: A x → ¬B x, from h x,
have nBx: ¬B x, from Ax_imp_nBx Ax,
show false, from nBx Bx,
iff.intro h₁ h₂
end
section
open classical
example: (¬∀x, A x → B x) ↔ (∃x, A x ∧ ¬B x) :=
have h₁: (¬∀x, A x → B x) → (∃x, A x ∧ ¬B x), from
assume h,
show ∃x, A x ∧ ¬B x, from by_contradiction $
assume h_nex: ¬∃x, A x ∧ ¬B x,
show false, from
have ∀x, A x → B x, from
assume x,
assume Ax,
show B x, from by_contradiction $
assume nBx,
have A x ∧ ¬B x, from and.intro Ax nBx,
have h_ex: ∃x, A x ∧ ¬B x, from exists.intro x this,
show false, from h_nex h_ex,
show false, from h this,
have h₂: (∃x, A x ∧ ¬B x) → (¬∀x, A x → B x) :=
assume h,
assume h_all,
show false, from
exists.elim h $
assume x (Ax_and_nBx: A x ∧ ¬B x),
have Ax_imp_Bx: A x → B x, from h_all x,
have A x, from and.left Ax_and_nBx,
have Bx: B x, from Ax_imp_Bx this,
have nBx: ¬B x, from and.right Ax_and_nBx,
show false, from nBx Bx,
iff.intro h₁ h₂
end
section
example(h:∃x, A x ∧ ∀y, A y → y = x): ∃x, A x ∧ ∀y,∀z, A y ∧ A z → y = z :=
exists.elim h $
assume x (h₁: A x ∧ ∀y, A y → y = x),
have Ax: A x, from and.left h₁,
have all_A_imp_eq_x: ∀y, A y → y = x, from and.right h₁,
have ∀y,∀z, A y ∧ A z → y = z, from
assume (y:U) (z:U) (Ay_and_Az: A y ∧ A z),
have Ay_imp_y_eq_x: A y → y = x, from all_A_imp_eq_x y,
have Az_imp_z_eq_x: A z → z = x, from all_A_imp_eq_x z,
have A y, from and.left Ay_and_Az,
have y_eq_x: y = x, from Ay_imp_y_eq_x this,
have A z, from and.right Ay_and_Az,
have z_eq_x: z = x, from Az_imp_z_eq_x this,
show y = z, by rw [y_eq_x, z_eq_x],
exists.intro x (and.intro Ax this)
example(h:∃x, A x ∧ ∀y,∀z, A y ∧ A z → y = z): ∃x, A x ∧ ∀y, A y → y = x :=
exists.elim h $
assume x (h₁: A x ∧ ∀y,∀z, A y ∧ A z → y = z),
have Ax: A x, from and.left h₁,
have h₂: ∀y,∀z, A y ∧ A z → y = z, from and.right h₁,
have ∀y, A y → y = x, from
assume y Ay,
have A y ∧ A x → y = x, from h₂ y x,
show y = x, from this (and.intro Ay Ax),
exists.intro x (and.intro Ax this)
end |
2ab3b14f20219e622b37d08978f24f9dadb620a7 | 75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2 | /library/data/nat/sub.lean | 652c074f086a0fd66489f5892ac108ec64abc54b | [
"Apache-2.0"
] | permissive | jroesch/lean | 30ef0860fa905d35b9ad6f76de1a4f65c9af6871 | 3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2 | refs/heads/master | 1,586,090,835,348 | 1,455,142,203,000 | 1,455,142,277,000 | 51,536,958 | 1 | 0 | null | 1,455,215,811,000 | 1,455,215,811,000 | null | UTF-8 | Lean | false | false | 15,954 | lean | /-
Copyright (c) 2014 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn, Jeremy Avigad
Subtraction on the natural numbers, as well as min, max, and distance.
-/
import .order
open eq.ops
namespace nat
/- subtraction -/
protected theorem sub_zero [simp] (n : ℕ) : n - 0 = n :=
rfl
theorem sub_succ [simp] (n m : ℕ) : n - succ m = pred (n - m) :=
rfl
protected theorem zero_sub [simp] (n : ℕ) : 0 - n = 0 :=
nat.induction_on n (by simp) (by simp)
theorem succ_sub_succ [simp] (n m : ℕ) : succ n - succ m = n - m :=
succ_sub_succ_eq_sub n m
protected theorem sub_self [simp] (n : ℕ) : n - n = 0 :=
nat.induction_on n (by simp) (by simp)
local attribute nat.add_succ [simp]
protected theorem add_sub_add_right [simp] (n k m : ℕ) : (n + k) - (m + k) = n - m :=
nat.induction_on k (by simp) (by simp)
protected theorem add_sub_add_left [simp] (k n m : ℕ) : (k + n) - (k + m) = n - m :=
nat.induction_on k (by simp) (by simp)
protected theorem add_sub_cancel [simp] (n m : ℕ) : n + m - m = n :=
nat.induction_on m (by simp) (by simp)
protected theorem add_sub_cancel_left [simp] (n m : ℕ) : n + m - n = m :=
nat.induction_on n (by simp) (by simp)
protected theorem sub_sub [simp] (n m k : ℕ) : (: n - m - k :) = (: n - (m + k) :) :=
nat.induction_on k (by simp) (by simp)
theorem succ_sub_sub_succ [simp] (n m k : ℕ) : succ n - m - succ k = n - m - k :=
by simp
theorem sub_self_add [simp] (n m : ℕ) : n - (n + m) = 0 :=
by inst_simp
protected theorem sub.right_comm (m n k : ℕ) : m - n - k = m - k - n :=
by simp
theorem sub_one (n : ℕ) : n - 1 = pred n :=
rfl
theorem succ_sub_one [simp] (n : ℕ) : succ n - 1 = n :=
rfl
local attribute nat.succ_mul nat.mul_succ [simp]
/- interaction with multiplication -/
theorem mul_pred_left [simp] (n m : ℕ) : pred n * m = n * m - m :=
nat.induction_on n (by simp) (by simp)
theorem mul_pred_right [simp] (n m : ℕ) : n * pred m = n * m - n :=
by inst_simp
protected theorem mul_sub_right_distrib [simp] (n m k : ℕ) : (n - m) * k = n * k - m * k :=
nat.induction_on m (by simp) (by simp)
protected theorem mul_sub_left_distrib [simp] (n m k : ℕ) : n * (m - k) = n * m - n * k :=
by inst_simp
protected theorem mul_self_sub_mul_self_eq (a b : nat) : a * a - b * b = (a + b) * (a - b) :=
by rewrite [nat.mul_sub_left_distrib, *right_distrib, mul.comm b a, add.comm (a*a) (a*b),
nat.add_sub_add_left]
local attribute succ_eq_add_one right_distrib left_distrib [simp]
theorem succ_mul_succ_eq (a : nat) : succ a * succ a = a*a + a + a + 1 :=
by simp
/- interaction with inequalities -/
theorem succ_sub {m n : ℕ} : m ≥ n → succ m - n = succ (m - n) :=
sub_induction n m
(take k, assume H : 0 ≤ k, rfl)
(take k,
assume H : succ k ≤ 0,
absurd H !not_succ_le_zero)
(take k l,
assume IH : k ≤ l → succ l - k = succ (l - k),
take H : succ k ≤ succ l,
calc
succ (succ l) - succ k = succ l - k : succ_sub_succ
... = succ (l - k) : IH (le_of_succ_le_succ H)
... = succ (succ l - succ k) : succ_sub_succ)
theorem sub_eq_zero_of_le {n m : ℕ} (H : n ≤ m) : n - m = 0 :=
obtain (k : ℕ) (Hk : n + k = m), from le.elim H, Hk ▸ !sub_self_add
theorem add_sub_of_le {n m : ℕ} : n ≤ m → n + (m - n) = m :=
sub_induction n m
(take k,
assume H : 0 ≤ k,
calc
0 + (k - 0) = k - 0 : zero_add
... = k : nat.sub_zero)
(take k, assume H : succ k ≤ 0, absurd H !not_succ_le_zero)
(take k l,
assume IH : k ≤ l → k + (l - k) = l,
take H : succ k ≤ succ l,
calc
succ k + (succ l - succ k) = succ k + (l - k) : succ_sub_succ
... = succ (k + (l - k)) : succ_add
... = succ l : IH (le_of_succ_le_succ H))
theorem add_sub_of_ge {n m : ℕ} (H : n ≥ m) : n + (m - n) = n :=
calc
n + (m - n) = n + 0 : sub_eq_zero_of_le H
... = n : add_zero
protected theorem sub_add_cancel {n m : ℕ} : n ≥ m → n - m + m = n :=
!add.comm ▸ !add_sub_of_le
theorem sub_add_of_le {n m : ℕ} : n ≤ m → n - m + m = m :=
!add.comm ▸ add_sub_of_ge
theorem sub.cases {P : ℕ → Prop} {n m : ℕ} (H1 : n ≤ m → P 0) (H2 : ∀k, m + k = n -> P k)
: P (n - m) :=
or.elim !le.total
(assume H3 : n ≤ m, (sub_eq_zero_of_le H3)⁻¹ ▸ (H1 H3))
(assume H3 : m ≤ n, H2 (n - m) (add_sub_of_le H3))
theorem exists_sub_eq_of_le {n m : ℕ} (H : n ≤ m) : ∃k, m - k = n :=
obtain (k : ℕ) (Hk : n + k = m), from le.elim H,
exists.intro k
(calc
m - k = n + k - k : by rewrite Hk
... = n : nat.add_sub_cancel)
protected theorem add_sub_assoc {m k : ℕ} (H : k ≤ m) (n : ℕ) : n + m - k = n + (m - k) :=
have l1 : k ≤ m → n + m - k = n + (m - k), from
sub_induction k m
(by simp)
(take k : ℕ, assume H : succ k ≤ 0, absurd H !not_succ_le_zero)
(take k m,
assume IH : k ≤ m → n + m - k = n + (m - k),
take H : succ k ≤ succ m,
calc
n + succ m - succ k = succ (n + m) - succ k : add_succ
... = n + m - k : succ_sub_succ
... = n + (m - k) : IH (le_of_succ_le_succ H)
... = n + (succ m - succ k) : succ_sub_succ),
l1 H
theorem le_of_sub_eq_zero {n m : ℕ} : n - m = 0 → n ≤ m :=
sub.cases
(assume H1 : n ≤ m, assume H2 : 0 = 0, H1)
(take k : ℕ,
assume H1 : m + k = n,
assume H2 : k = 0,
have H3 : n = m, from !add_zero ▸ H2 ▸ H1⁻¹,
H3 ▸ !le.refl)
theorem sub_sub.cases {P : ℕ → ℕ → Prop} {n m : ℕ} (H1 : ∀k, n = m + k -> P k 0)
(H2 : ∀k, m = n + k → P 0 k) : P (n - m) (m - n) :=
or.elim !le.total
(assume H3 : n ≤ m,
(sub_eq_zero_of_le H3)⁻¹ ▸ (H2 (m - n) (add_sub_of_le H3)⁻¹))
(assume H3 : m ≤ n,
(sub_eq_zero_of_le H3)⁻¹ ▸ (H1 (n - m) (add_sub_of_le H3)⁻¹))
protected theorem sub_eq_of_add_eq {n m k : ℕ} (H : n + m = k) : k - n = m :=
have H2 : k - n + n = m + n, from
calc
k - n + n = k : nat.sub_add_cancel (le.intro H)
... = n + m : H⁻¹
... = m + n : !add.comm,
add.right_cancel H2
protected theorem eq_sub_of_add_eq {a b c : ℕ} (H : a + c = b) : a = b - c :=
(nat.sub_eq_of_add_eq (!add.comm ▸ H))⁻¹
protected theorem sub_eq_of_eq_add {a b c : ℕ} (H : a = c + b) : a - b = c :=
nat.sub_eq_of_add_eq (!add.comm ▸ H⁻¹)
protected theorem sub_le_sub_right {n m : ℕ} (H : n ≤ m) (k : ℕ) : n - k ≤ m - k :=
obtain (l : ℕ) (Hl : n + l = m), from le.elim H,
or.elim !le.total
(assume H2 : n ≤ k, (sub_eq_zero_of_le H2)⁻¹ ▸ !zero_le)
(assume H2 : k ≤ n,
have H3 : n - k + l = m - k, from
calc
n - k + l = l + (n - k) : by simp
... = l + n - k : nat.add_sub_assoc H2 l
... = m - k : by simp,
le.intro H3)
protected theorem sub_le_sub_left {n m : ℕ} (H : n ≤ m) (k : ℕ) : k - m ≤ k - n :=
obtain (l : ℕ) (Hl : n + l = m), from le.elim H,
sub.cases
(assume H2 : k ≤ m, !zero_le)
(take m' : ℕ,
assume Hm : m + m' = k,
have H3 : n ≤ k, from le.trans H (le.intro Hm),
have H4 : m' + l + n = k - n + n, by simp,
le.intro (add.right_cancel H4))
protected theorem sub_pos_of_lt {m n : ℕ} (H : m < n) : n - m > 0 :=
assert H1 : n = n - m + m, from (nat.sub_add_cancel (le_of_lt H))⁻¹,
have H2 : 0 + m < n - m + m, begin rewrite [zero_add, -H1], exact H end,
!lt_of_add_lt_add_right H2
protected theorem lt_of_sub_pos {m n : ℕ} (H : n - m > 0) : m < n :=
lt_of_not_ge
(take H1 : m ≥ n,
have H2 : n - m = 0, from sub_eq_zero_of_le H1,
!lt.irrefl (H2 ▸ H))
protected theorem lt_of_sub_lt_sub_right {n m k : ℕ} (H : n - k < m - k) : n < m :=
lt_of_not_ge
(assume H1 : m ≤ n,
have H2 : m - k ≤ n - k, from nat.sub_le_sub_right H1 _,
not_le_of_gt H H2)
protected theorem lt_of_sub_lt_sub_left {n m k : ℕ} (H : n - m < n - k) : k < m :=
lt_of_not_ge
(assume H1 : m ≤ k,
have H2 : n - k ≤ n - m, from nat.sub_le_sub_left H1 _,
not_le_of_gt H H2)
protected theorem sub_lt_sub_add_sub (n m k : ℕ) : n - k ≤ (n - m) + (m - k) :=
sub.cases
(assume H : n ≤ m, (zero_add (m - k))⁻¹ ▸ nat.sub_le_sub_right H k)
(take mn : ℕ,
assume Hmn : m + mn = n,
sub.cases
(assume H : m ≤ k,
have H2 : n - k ≤ n - m, from nat.sub_le_sub_left H n,
assert H3 : n - k ≤ mn, from nat.sub_eq_of_add_eq Hmn ▸ H2,
show n - k ≤ mn + 0, begin rewrite add_zero, assumption end)
(take km : ℕ,
assume Hkm : k + km = m,
have H : k + (mn + km) = n, from
calc
k + (mn + km) = k + km + mn : by simp
... = m + mn : Hkm
... = n : Hmn,
have H2 : n - k = mn + km, from nat.sub_eq_of_add_eq H,
H2 ▸ !le.refl))
protected theorem sub_lt_self {m n : ℕ} (H1 : m > 0) (H2 : n > 0) : m - n < m :=
calc
m - n = succ (pred m) - n : succ_pred_of_pos H1
... = succ (pred m) - succ (pred n) : succ_pred_of_pos H2
... = pred m - pred n : succ_sub_succ
... ≤ pred m : sub_le
... < succ (pred m) : lt_succ_self
... = m : succ_pred_of_pos H1
protected theorem le_sub_of_add_le {m n k : ℕ} (H : m + k ≤ n) : m ≤ n - k :=
calc
m = m + k - k : nat.add_sub_cancel
... ≤ n - k : nat.sub_le_sub_right H k
protected theorem lt_sub_of_add_lt {m n k : ℕ} (H : m + k < n) (H2 : k ≤ n) : m < n - k :=
lt_of_succ_le (nat.le_sub_of_add_le (calc
succ m + k = succ (m + k) : succ_add_eq_succ_add
... ≤ n : succ_le_of_lt H))
protected theorem sub_lt_of_lt_add {v n m : nat} (h₁ : v < n + m) (h₂ : n ≤ v) : v - n < m :=
have succ v ≤ n + m, from succ_le_of_lt h₁,
have succ (v - n) ≤ m, from
calc succ (v - n) = succ v - n : succ_sub h₂
... ≤ n + m - n : nat.sub_le_sub_right this n
... = m : nat.add_sub_cancel_left,
lt_of_succ_le this
/- distance -/
definition dist [reducible] (n m : ℕ) := (n - m) + (m - n)
theorem dist.comm (n m : ℕ) : dist n m = dist m n :=
by simp
theorem dist_self (n : ℕ) : dist n n = 0 :=
by simp
theorem eq_of_dist_eq_zero {n m : ℕ} (H : dist n m = 0) : n = m :=
have H2 : n - m = 0, from eq_zero_of_add_eq_zero_right H,
have H3 : n ≤ m, from le_of_sub_eq_zero H2,
have H4 : m - n = 0, from eq_zero_of_add_eq_zero_left H,
have H5 : m ≤ n, from le_of_sub_eq_zero H4,
le.antisymm H3 H5
theorem dist_eq_zero {n m : ℕ} (H : n = m) : dist n m = 0 :=
by substvars; rewrite [↑dist, *nat.sub_self, add_zero]
theorem dist_eq_sub_of_le {n m : ℕ} (H : n ≤ m) : dist n m = m - n :=
calc
dist n m = 0 + (m - n) : {sub_eq_zero_of_le H}
... = m - n : zero_add
theorem dist_eq_sub_of_lt {n m : ℕ} (H : n < m) : dist n m = m - n :=
dist_eq_sub_of_le (le_of_lt H)
theorem dist_eq_sub_of_ge {n m : ℕ} (H : n ≥ m) : dist n m = n - m :=
!dist.comm ▸ dist_eq_sub_of_le H
theorem dist_eq_sub_of_gt {n m : ℕ} (H : n > m) : dist n m = n - m :=
dist_eq_sub_of_ge (le_of_lt H)
theorem dist_zero_right (n : ℕ) : dist n 0 = n :=
dist_eq_sub_of_ge !zero_le ⬝ !nat.sub_zero
theorem dist_zero_left (n : ℕ) : dist 0 n = n :=
dist_eq_sub_of_le !zero_le ⬝ !nat.sub_zero
theorem dist.intro {n m k : ℕ} (H : n + m = k) : dist k n = m :=
calc
dist k n = k - n : dist_eq_sub_of_ge (le.intro H)
... = m : nat.sub_eq_of_add_eq H
theorem dist_add_add_right (n k m : ℕ) : dist (n + k) (m + k) = dist n m :=
calc
dist (n + k) (m + k) = ((n+k) - (m+k)) + ((m+k)-(n+k)) : rfl
... = (n - m) + ((m + k) - (n + k)) : nat.add_sub_add_right
... = (n - m) + (m - n) : nat.add_sub_add_right
theorem dist_add_add_left (k n m : ℕ) : dist (k + n) (k + m) = dist n m :=
begin rewrite [add.comm k n, add.comm k m]; apply dist_add_add_right end
theorem dist_add_eq_of_ge {n m : ℕ} (H : n ≥ m) : dist n m + m = n :=
calc
dist n m + m = n - m + m : {dist_eq_sub_of_ge H}
... = n : nat.sub_add_cancel H
theorem dist_eq_intro {n m k l : ℕ} (H : n + m = k + l) : dist n k = dist l m :=
calc
dist n k = dist (n + m) (k + m) : dist_add_add_right
... = dist (k + l) (k + m) : H
... = dist l m : dist_add_add_left
theorem dist_sub_eq_dist_add_left {n m : ℕ} (H : n ≥ m) (k : ℕ) :
dist (n - m) k = dist n (k + m) :=
have H2 : n - m + (k + m) = k + n, from
calc
n - m + (k + m) = n - m + m + k : by simp
... = n + k : nat.sub_add_cancel H
... = k + n : by simp,
dist_eq_intro H2
theorem dist_sub_eq_dist_add_right {k m : ℕ} (H : k ≥ m) (n : ℕ) :
dist n (k - m) = dist (n + m) k :=
dist.comm (k - m) n ▸ dist.comm k (n + m) ▸ dist_sub_eq_dist_add_left H n
theorem dist.triangle_inequality (n m k : ℕ) : dist n k ≤ dist n m + dist m k :=
have (n - m) + (m - k) + ((k - m) + (m - n)) = (n - m) + (m - n) + ((m - k) + (k - m)), by simp,
this ▸ add_le_add !nat.sub_lt_sub_add_sub !nat.sub_lt_sub_add_sub
theorem dist_add_add_le_add_dist_dist (n m k l : ℕ) : dist (n + m) (k + l) ≤ dist n k + dist m l :=
assert H : dist (n + m) (k + m) + dist (k + m) (k + l) = dist n k + dist m l,
by rewrite [dist_add_add_left, dist_add_add_right],
by rewrite -H; apply dist.triangle_inequality
theorem dist_mul_right (n k m : ℕ) : dist (n * k) (m * k) = dist n m * k :=
assert ∀ n m, dist n m = n - m + (m - n), from take n m, rfl,
by rewrite [this, this n m, right_distrib, *nat.mul_sub_right_distrib]
theorem dist_mul_left (k n m : ℕ) : dist (k * n) (k * m) = k * dist n m :=
begin rewrite [mul.comm k n, mul.comm k m, dist_mul_right, mul.comm] end
theorem dist_mul_dist (n m k l : ℕ) : dist n m * dist k l = dist (n * k + m * l) (n * l + m * k) :=
have aux : ∀k l, k ≥ l → dist n m * dist k l = dist (n * k + m * l) (n * l + m * k), from
take k l : ℕ,
assume H : k ≥ l,
have H2 : m * k ≥ m * l, from !mul_le_mul_left H,
have H3 : n * l + m * k ≥ m * l, from le.trans H2 !le_add_left,
calc
dist n m * dist k l = dist n m * (k - l) : dist_eq_sub_of_ge H
... = dist (n * (k - l)) (m * (k - l)) : dist_mul_right
... = dist (n * k - n * l) (m * k - m * l) : by rewrite [*nat.mul_sub_left_distrib]
... = dist (n * k) (m * k - m * l + n * l) : dist_sub_eq_dist_add_left (!mul_le_mul_left H)
... = dist (n * k) (n * l + (m * k - m * l)) : add.comm
... = dist (n * k) (n * l + m * k - m * l) : nat.add_sub_assoc H2 (n * l)
... = dist (n * k + m * l) (n * l + m * k) : dist_sub_eq_dist_add_right H3 _,
or.elim !le.total
(assume H : k ≤ l, !dist.comm ▸ !dist.comm ▸ aux l k H)
(assume H : l ≤ k, aux k l H)
lemma dist_eq_max_sub_min {i j : nat} : dist i j = (max i j) - min i j :=
or.elim (lt_or_ge i j)
(suppose i < j,
by rewrite [max_eq_right_of_lt this, min_eq_left_of_lt this, dist_eq_sub_of_lt this])
(suppose i ≥ j,
by rewrite [max_eq_left this , min_eq_right this, dist_eq_sub_of_ge this])
lemma dist_succ {i j : nat} : dist (succ i) (succ j) = dist i j :=
by rewrite [↑dist, *succ_sub_succ]
lemma dist_le_max {i j : nat} : dist i j ≤ max i j :=
begin rewrite dist_eq_max_sub_min, apply sub_le end
lemma dist_pos_of_ne {i j : nat} : i ≠ j → dist i j > 0 :=
assume Pne, lt.by_cases
(suppose i < j, begin rewrite [dist_eq_sub_of_lt this], apply nat.sub_pos_of_lt this end)
(suppose i = j, by contradiction)
(suppose i > j, begin rewrite [dist_eq_sub_of_gt this], apply nat.sub_pos_of_lt this end)
end nat
|
b7bbbc8d75b0cb36d106be23f2b2ea53e63c1fa7 | 31f556cdeb9239ffc2fad8f905e33987ff4feab9 | /src/Lean/Compiler/LCNF.lean | dc8ed5af6fa636d33c4bdcd66cffbafa05498693 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | tobiasgrosser/lean4 | ce0fd9cca0feba1100656679bf41f0bffdbabb71 | ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f | refs/heads/master | 1,673,103,412,948 | 1,664,930,501,000 | 1,664,930,501,000 | 186,870,185 | 0 | 0 | Apache-2.0 | 1,665,129,237,000 | 1,557,939,901,000 | Lean | UTF-8 | Lean | false | false | 1,310 | lean | /-
Copyright (c) 2022 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Compiler.LCNF.AlphaEqv
import Lean.Compiler.LCNF.Basic
import Lean.Compiler.LCNF.Bind
import Lean.Compiler.LCNF.Check
import Lean.Compiler.LCNF.CompilerM
import Lean.Compiler.LCNF.CSE
import Lean.Compiler.LCNF.DependsOn
import Lean.Compiler.LCNF.ElimDead
import Lean.Compiler.LCNF.FixedArgs
import Lean.Compiler.LCNF.InferType
import Lean.Compiler.LCNF.JoinPoints
import Lean.Compiler.LCNF.LCtx
import Lean.Compiler.LCNF.Level
import Lean.Compiler.LCNF.Main
import Lean.Compiler.LCNF.Passes
import Lean.Compiler.LCNF.PassManager
import Lean.Compiler.LCNF.PhaseExt
import Lean.Compiler.LCNF.PrettyPrinter
import Lean.Compiler.LCNF.PullFunDecls
import Lean.Compiler.LCNF.PullLetDecls
import Lean.Compiler.LCNF.ReduceJpArity
import Lean.Compiler.LCNF.Simp
import Lean.Compiler.LCNF.Specialize
import Lean.Compiler.LCNF.SpecInfo
import Lean.Compiler.LCNF.Testing
import Lean.Compiler.LCNF.ToDecl
import Lean.Compiler.LCNF.ToExpr
import Lean.Compiler.LCNF.ToLCNF
import Lean.Compiler.LCNF.Types
import Lean.Compiler.LCNF.Util
import Lean.Compiler.LCNF.ConfigOptions
import Lean.Compiler.LCNF.ForEachExpr
import Lean.Compiler.LCNF.MonoTypes |
53971203f62cf049b2855fc739df6d11165879a7 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/combinatorics/simple_graph/subgraph.lean | ea5721223bd426457cb09b714c319dfa40eefa6a | [
"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 | 39,247 | lean | /-
Copyright (c) 2021 Hunter Monroe. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Hunter Monroe, Kyle Miller, Alena Gusakov
-/
import combinatorics.simple_graph.basic
/-!
# Subgraphs of a simple graph
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
A subgraph of a simple graph consists of subsets of the graph's vertices and edges such that the
endpoints of each edge are present in the vertex subset. The edge subset is formalized as a
sub-relation of the adjacency relation of the simple graph.
## Main definitions
* `subgraph G` is the type of subgraphs of a `G : simple_graph`
* `subgraph.neighbor_set`, `subgraph.incidence_set`, and `subgraph.degree` are like their
`simple_graph` counterparts, but they refer to vertices from `G` to avoid subtype coercions.
* `subgraph.coe` is the coercion from a `G' : subgraph G` to a `simple_graph G'.verts`.
(This cannot be a `has_coe` instance since the destination type depends on `G'`.)
* `subgraph.is_spanning` for whether a subgraph is a spanning subgraph and
`subgraph.is_induced` for whether a subgraph is an induced subgraph.
* Instances for `lattice (subgraph G)` and `bounded_order (subgraph G)`.
* `simple_graph.to_subgraph`: If a `simple_graph` is a subgraph of another, then you can turn it
into a member of the larger graph's `simple_graph.subgraph` type.
* Graph homomorphisms from a subgraph to a graph (`subgraph.map_top`) and between subgraphs
(`subgraph.map`).
## Implementation notes
* Recall that subgraphs are not determined by their vertex sets, so `set_like` does not apply to
this kind of subobject.
## Todo
* Images of graph homomorphisms as subgraphs.
-/
universes u v
namespace simple_graph
/-- A subgraph of a `simple_graph` is a subset of vertices along with a restriction of the adjacency
relation that is symmetric and is supported by the vertex subset. They also form a bounded lattice.
Thinking of `V → V → Prop` as `set (V × V)`, a set of darts (i.e., half-edges), then
`subgraph.adj_sub` is that the darts of a subgraph are a subset of the darts of `G`. -/
@[ext]
structure subgraph {V : Type u} (G : simple_graph V) :=
(verts : set V)
(adj : V → V → Prop)
(adj_sub : ∀ {v w : V}, adj v w → G.adj v w)
(edge_vert : ∀ {v w : V}, adj v w → v ∈ verts)
(symm : symmetric adj . obviously)
variables {ι : Sort*} {V : Type u} {W : Type v}
/-- The one-vertex subgraph. -/
@[simps]
protected def singleton_subgraph (G : simple_graph V) (v : V) : G.subgraph :=
{ verts := {v},
adj := ⊥,
adj_sub := by simp [-set.bot_eq_empty],
edge_vert := by simp [-set.bot_eq_empty] }
/-- The one-edge subgraph. -/
@[simps]
def subgraph_of_adj (G : simple_graph V) {v w : V} (hvw : G.adj v w) : G.subgraph :=
{ verts := {v, w},
adj := λ a b, ⟦(v, w)⟧ = ⟦(a, b)⟧,
adj_sub := λ a b h, by { rw [← G.mem_edge_set, ← h], exact hvw },
edge_vert := λ a b h, by { apply_fun (λ e, a ∈ e) at h, simpa using h } }
namespace subgraph
variables {G : simple_graph V} {G₁ G₂ : G.subgraph} {a b : V}
protected lemma loopless (G' : subgraph G) : irreflexive G'.adj :=
λ v h, G.loopless v (G'.adj_sub h)
lemma adj_comm (G' : subgraph G) (v w : V) : G'.adj v w ↔ G'.adj w v :=
⟨λ x, G'.symm x, λ x, G'.symm x⟩
@[symm] lemma adj_symm (G' : subgraph G) {u v : V} (h : G'.adj u v) : G'.adj v u := G'.symm h
protected lemma adj.symm {G' : subgraph G} {u v : V} (h : G'.adj u v) : G'.adj v u := G'.symm h
protected lemma adj.adj_sub {H : G.subgraph} {u v : V} (h : H.adj u v) : G.adj u v := H.adj_sub h
protected lemma adj.fst_mem {H : G.subgraph} {u v : V} (h : H.adj u v) : u ∈ H.verts :=
H.edge_vert h
protected lemma adj.snd_mem {H : G.subgraph} {u v : V} (h : H.adj u v) : v ∈ H.verts :=
h.symm.fst_mem
protected lemma adj.ne {H : G.subgraph} {u v : V} (h : H.adj u v) : u ≠ v := h.adj_sub.ne
/-- Coercion from `G' : subgraph G` to a `simple_graph ↥G'.verts`. -/
@[simps] protected def coe (G' : subgraph G) : simple_graph G'.verts :=
{ adj := λ v w, G'.adj v w,
symm := λ v w h, G'.symm h,
loopless := λ v h, loopless G v (G'.adj_sub h) }
@[simp] lemma coe_adj_sub (G' : subgraph G) (u v : G'.verts) (h : G'.coe.adj u v) : G.adj u v :=
G'.adj_sub h
/- Given `h : H.adj u v`, then `h.coe : H.coe.adj ⟨u, _⟩ ⟨v, _⟩`. -/
protected lemma adj.coe {H : G.subgraph} {u v : V} (h : H.adj u v) :
H.coe.adj ⟨u, H.edge_vert h⟩ ⟨v, H.edge_vert h.symm⟩ := h
/-- A subgraph is called a *spanning subgraph* if it contains all the vertices of `G`. -/
def is_spanning (G' : subgraph G) : Prop := ∀ (v : V), v ∈ G'.verts
lemma is_spanning_iff {G' : subgraph G} : G'.is_spanning ↔ G'.verts = set.univ :=
set.eq_univ_iff_forall.symm
/-- Coercion from `subgraph G` to `simple_graph V`. If `G'` is a spanning
subgraph, then `G'.spanning_coe` yields an isomorphic graph.
In general, this adds in all vertices from `V` as isolated vertices. -/
@[simps] protected def spanning_coe (G' : subgraph G) : simple_graph V :=
{ adj := G'.adj,
symm := G'.symm,
loopless := λ v hv, G.loopless v (G'.adj_sub hv) }
@[simp] lemma adj.of_spanning_coe {G' : subgraph G} {u v : G'.verts}
(h : G'.spanning_coe.adj u v) : G.adj u v := G'.adj_sub h
@[simp] lemma spanning_coe_inj : G₁.spanning_coe = G₂.spanning_coe ↔ G₁.adj = G₂.adj :=
by simp [subgraph.spanning_coe]
/-- `spanning_coe` is equivalent to `coe` for a subgraph that `is_spanning`. -/
@[simps] def spanning_coe_equiv_coe_of_spanning (G' : subgraph G) (h : G'.is_spanning) :
G'.spanning_coe ≃g G'.coe :=
{ to_fun := λ v, ⟨v, h v⟩,
inv_fun := λ v, v,
left_inv := λ v, rfl,
right_inv := λ ⟨v, hv⟩, rfl,
map_rel_iff' := λ v w, iff.rfl }
/-- A subgraph is called an *induced subgraph* if vertices of `G'` are adjacent if
they are adjacent in `G`. -/
def is_induced (G' : subgraph G) : Prop :=
∀ {v w : V}, v ∈ G'.verts → w ∈ G'.verts → G.adj v w → G'.adj v w
/-- `H.support` is the set of vertices that form edges in the subgraph `H`. -/
def support (H : subgraph G) : set V := rel.dom H.adj
lemma mem_support (H : subgraph G) {v : V} : v ∈ H.support ↔ ∃ w, H.adj v w := iff.rfl
lemma support_subset_verts (H : subgraph G) : H.support ⊆ H.verts := λ v ⟨w, h⟩, H.edge_vert h
/-- `G'.neighbor_set v` is the set of vertices adjacent to `v` in `G'`. -/
def neighbor_set (G' : subgraph G) (v : V) : set V := set_of (G'.adj v)
lemma neighbor_set_subset (G' : subgraph G) (v : V) : G'.neighbor_set v ⊆ G.neighbor_set v :=
λ w h, G'.adj_sub h
lemma neighbor_set_subset_verts (G' : subgraph G) (v : V) : G'.neighbor_set v ⊆ G'.verts :=
λ _ h, G'.edge_vert (adj_symm G' h)
@[simp] lemma mem_neighbor_set (G' : subgraph G) (v w : V) : w ∈ G'.neighbor_set v ↔ G'.adj v w :=
iff.rfl
/-- A subgraph as a graph has equivalent neighbor sets. -/
def coe_neighbor_set_equiv {G' : subgraph G} (v : G'.verts) :
G'.coe.neighbor_set v ≃ G'.neighbor_set v :=
{ to_fun := λ w, ⟨w, by { obtain ⟨w', hw'⟩ := w, simpa using hw' }⟩,
inv_fun := λ w, ⟨⟨w, G'.edge_vert (G'.adj_symm w.2)⟩, by simpa using w.2⟩,
left_inv := λ w, by simp,
right_inv := λ w, by simp }
/-- The edge set of `G'` consists of a subset of edges of `G`. -/
def edge_set (G' : subgraph G) : set (sym2 V) := sym2.from_rel G'.symm
lemma edge_set_subset (G' : subgraph G) : G'.edge_set ⊆ G.edge_set :=
λ e, quotient.ind (λ e h, G'.adj_sub h) e
@[simp]
lemma mem_edge_set {G' : subgraph G} {v w : V} : ⟦(v, w)⟧ ∈ G'.edge_set ↔ G'.adj v w := iff.rfl
lemma mem_verts_if_mem_edge {G' : subgraph G} {e : sym2 V} {v : V}
(he : e ∈ G'.edge_set) (hv : v ∈ e) : v ∈ G'.verts :=
begin
refine quotient.ind (λ e he hv, _) e he hv,
cases e with v w,
simp only [mem_edge_set] at he,
cases sym2.mem_iff.mp hv with h h; subst h,
{ exact G'.edge_vert he, },
{ exact G'.edge_vert (G'.symm he), },
end
/-- The `incidence_set` is the set of edges incident to a given vertex. -/
def incidence_set (G' : subgraph G) (v : V) : set (sym2 V) := {e ∈ G'.edge_set | v ∈ e}
lemma incidence_set_subset_incidence_set (G' : subgraph G) (v : V) :
G'.incidence_set v ⊆ G.incidence_set v :=
λ e h, ⟨G'.edge_set_subset h.1, h.2⟩
lemma incidence_set_subset (G' : subgraph G) (v : V) : G'.incidence_set v ⊆ G'.edge_set :=
λ _ h, h.1
/-- Give a vertex as an element of the subgraph's vertex type. -/
@[reducible]
def vert (G' : subgraph G) (v : V) (h : v ∈ G'.verts) : G'.verts := ⟨v, h⟩
/--
Create an equal copy of a subgraph (see `copy_eq`) with possibly different definitional equalities.
See Note [range copy pattern].
-/
def copy (G' : subgraph G)
(V'' : set V) (hV : V'' = G'.verts)
(adj' : V → V → Prop) (hadj : adj' = G'.adj) :
subgraph G :=
{ verts := V'',
adj := adj',
adj_sub := λ _ _, hadj.symm ▸ G'.adj_sub,
edge_vert := λ _ _, hV.symm ▸ hadj.symm ▸ G'.edge_vert,
symm := hadj.symm ▸ G'.symm }
lemma copy_eq (G' : subgraph G)
(V'' : set V) (hV : V'' = G'.verts)
(adj' : V → V → Prop) (hadj : adj' = G'.adj) :
G'.copy V'' hV adj' hadj = G' :=
subgraph.ext _ _ hV hadj
/-- The union of two subgraphs. -/
instance : has_sup G.subgraph :=
⟨λ G₁ G₂,
{ verts := G₁.verts ∪ G₂.verts,
adj := G₁.adj ⊔ G₂.adj,
adj_sub := λ a b hab, or.elim hab (λ h, G₁.adj_sub h) (λ h, G₂.adj_sub h),
edge_vert := λ a b, or.imp (λ h, G₁.edge_vert h) (λ h, G₂.edge_vert h),
symm := λ a b, or.imp G₁.adj_symm G₂.adj_symm }⟩
/-- The intersection of two subgraphs. -/
instance : has_inf G.subgraph :=
⟨λ G₁ G₂,
{ verts := G₁.verts ∩ G₂.verts,
adj := G₁.adj ⊓ G₂.adj,
adj_sub := λ a b hab, G₁.adj_sub hab.1,
edge_vert := λ a b, and.imp (λ h, G₁.edge_vert h) (λ h, G₂.edge_vert h),
symm := λ a b, and.imp G₁.adj_symm G₂.adj_symm }⟩
/-- The `top` subgraph is `G` as a subgraph of itself. -/
instance : has_top G.subgraph :=
⟨{ verts := set.univ,
adj := G.adj,
adj_sub := λ v w h, h,
edge_vert := λ v w h, set.mem_univ v,
symm := G.symm }⟩
/-- The `bot` subgraph is the subgraph with no vertices or edges. -/
instance : has_bot G.subgraph :=
⟨{ verts := ∅,
adj := ⊥,
adj_sub := λ v w h, false.rec _ h,
edge_vert := λ v w h, false.rec _ h,
symm := λ u v h, h }⟩
instance : has_Sup G.subgraph :=
⟨λ s, { verts := ⋃ G' ∈ s, verts G',
adj := λ a b, ∃ G' ∈ s, adj G' a b,
adj_sub := by { rintro a b ⟨G', -, hab⟩, exact G'.adj_sub hab },
edge_vert :=
by { rintro a b ⟨G', hG', hab⟩, exact set.mem_Union₂_of_mem hG' (G'.edge_vert hab) },
symm := λ a b, Exists₂.imp $ λ _ _, adj.symm }⟩
instance : has_Inf G.subgraph :=
⟨λ s, { verts := ⋂ G' ∈ s, verts G',
adj := λ a b, (∀ ⦃G'⦄, G' ∈ s → adj G' a b) ∧ G.adj a b,
adj_sub := λ a b, and.right,
edge_vert := λ a b hab, set.mem_Inter₂_of_mem $ λ G' hG', G'.edge_vert $ hab.1 hG',
symm := λ _ _, and.imp (forall₂_imp $ λ _ _, adj.symm) G.adj_symm }⟩
@[simp] lemma sup_adj : (G₁ ⊔ G₂).adj a b ↔ G₁.adj a b ∨ G₂.adj a b := iff.rfl
@[simp] lemma inf_adj : (G₁ ⊓ G₂).adj a b ↔ G₁.adj a b ∧ G₂.adj a b := iff.rfl
@[simp] lemma top_adj : (⊤ : subgraph G).adj a b ↔ G.adj a b := iff.rfl
@[simp] lemma not_bot_adj : ¬ (⊥ : subgraph G).adj a b := not_false
@[simp] lemma verts_sup (G₁ G₂ : G.subgraph) : (G₁ ⊔ G₂).verts = G₁.verts ∪ G₂.verts := rfl
@[simp] lemma verts_inf (G₁ G₂ : G.subgraph) : (G₁ ⊓ G₂).verts = G₁.verts ∩ G₂.verts := rfl
@[simp] lemma verts_top : (⊤ : G.subgraph).verts = set.univ := rfl
@[simp] lemma verts_bot : (⊥ : G.subgraph).verts = ∅ := rfl
@[simp] lemma Sup_adj {s : set G.subgraph} : (Sup s).adj a b ↔ ∃ G ∈ s, adj G a b := iff.rfl
@[simp] lemma Inf_adj {s : set G.subgraph} : (Inf s).adj a b ↔ (∀ G' ∈ s, adj G' a b) ∧ G.adj a b :=
iff.rfl
@[simp] lemma supr_adj {f : ι → G.subgraph} : (⨆ i, f i).adj a b ↔ ∃ i, (f i).adj a b :=
by simp [supr]
@[simp] lemma infi_adj {f : ι → G.subgraph} :
(⨅ i, f i).adj a b ↔ (∀ i, (f i).adj a b) ∧ G.adj a b :=
by simp [infi]
lemma Inf_adj_of_nonempty {s : set G.subgraph} (hs : s.nonempty) :
(Inf s).adj a b ↔ ∀ G' ∈ s, adj G' a b :=
Inf_adj.trans $ and_iff_left_of_imp $ by { obtain ⟨G', hG'⟩ := hs, exact λ h, G'.adj_sub (h _ hG') }
lemma infi_adj_of_nonempty [nonempty ι] {f : ι → G.subgraph} :
(⨅ i, f i).adj a b ↔ ∀ i, (f i).adj a b :=
by simp [infi, Inf_adj_of_nonempty (set.range_nonempty _)]
@[simp] lemma verts_Sup (s : set G.subgraph) : (Sup s).verts = ⋃ G' ∈ s, verts G' := rfl
@[simp] lemma verts_Inf (s : set G.subgraph) : (Inf s).verts = ⋂ G' ∈ s, verts G' := rfl
@[simp] lemma verts_supr {f : ι → G.subgraph} : (⨆ i, f i).verts = ⋃ i, (f i).verts :=
by simp [supr]
@[simp] lemma verts_infi {f : ι → G.subgraph} : (⨅ i, f i).verts = ⋂ i, (f i).verts :=
by simp [infi]
/-- For subgraphs `G₁`, `G₂`, `G₁ ≤ G₂` iff `G₁.verts ⊆ G₂.verts` and
`∀ a b, G₁.adj a b → G₂.adj a b`. -/
instance : distrib_lattice G.subgraph :=
{ le := λ x y, x.verts ⊆ y.verts ∧ ∀ ⦃v w : V⦄, x.adj v w → y.adj v w,
..show distrib_lattice G.subgraph, from function.injective.distrib_lattice
(λ G', (G'.verts, G'.spanning_coe))
(λ G₁ G₂ h, by { rw prod.ext_iff at h, exact ext _ _ h.1 (spanning_coe_inj.1 h.2) })
(λ _ _, rfl) (λ _ _, rfl) }
instance : bounded_order (subgraph G) :=
{ top := ⊤,
bot := ⊥,
le_top := λ x, ⟨set.subset_univ _, (λ v w h, x.adj_sub h)⟩,
bot_le := λ x, ⟨set.empty_subset _, (λ v w h, false.rec _ h)⟩ }
-- Note that subgraphs do not form a Boolean algebra, because of `verts`.
instance : complete_distrib_lattice G.subgraph :=
{ le := (≤),
sup := (⊔),
inf := (⊓),
top := ⊤,
bot := ⊥,
le_top := λ G', ⟨set.subset_univ _, λ a b, G'.adj_sub⟩,
bot_le := λ G', ⟨set.empty_subset _, λ a b, false.elim⟩,
Sup := Sup,
le_Sup := λ s G' hG', ⟨set.subset_Union₂ G' hG', λ a b hab, ⟨G', hG', hab⟩⟩,
Sup_le := λ s G' hG', ⟨set.Union₂_subset $ λ H hH, (hG' _ hH).1,
by { rintro a b ⟨H, hH, hab⟩, exact (hG' _ hH).2 hab }⟩,
Inf := Inf,
Inf_le := λ s G' hG', ⟨set.Inter₂_subset G' hG', λ a b hab, hab.1 hG'⟩,
le_Inf := λ s G' hG', ⟨set.subset_Inter₂ $ λ H hH, (hG' _ hH).1,
λ a b hab, ⟨λ H hH, (hG' _ hH).2 hab, G'.adj_sub hab⟩⟩,
inf_Sup_le_supr_inf := λ G' s, begin
refine ⟨_, λ a b hab, _⟩,
{ simp only [verts_inf, verts_Sup, verts_supr, set.le_eq_subset],
exact (set.inter_Union₂ _ _).subset },
{ simpa only [spanning_coe_adj, exists_prop, Sup_adj, and_imp, forall_exists_index, supr_adj,
inf_adj, ←exists_and_distrib_right, exists_and_distrib_left, and_assoc, and_self_right]
using hab }
end,
infi_sup_le_sup_Inf := λ G' s, begin
refine ⟨_, λ a b hab, _⟩,
{ simp only [set.le_eq_subset, verts_infi, verts_sup, verts_Inf],
exact (set.union_Inter₂ _ _).superset },
simp only [spanning_coe_adj, sup_adj, Inf_adj, sup_adj, Inf_adj, infi_adj] at ⊢ hab,
have : (∀ G'' ∈ s, adj G' a b ∨ adj G'' a b) ∧ G.adj a b :=
(and_congr_left $ λ h, forall_congr $ λ H, _).1 hab,
simpa [forall_or_distrib_left, or_and_distrib_right, and_iff_left_of_imp G'.adj_sub] using this,
exact and_iff_left h,
end,
..subgraph.distrib_lattice }
@[simps] instance subgraph_inhabited : inhabited (subgraph G) := ⟨⊥⟩
@[simp] lemma neighbor_set_sup {H H' : G.subgraph} (v : V) :
(H ⊔ H').neighbor_set v = H.neighbor_set v ∪ H'.neighbor_set v := rfl
@[simp] lemma neighbor_set_inf {H H' : G.subgraph} (v : V) :
(H ⊓ H').neighbor_set v = H.neighbor_set v ∩ H'.neighbor_set v := rfl
@[simp] lemma neighbor_set_top (v : V) : (⊤ : G.subgraph).neighbor_set v = G.neighbor_set v := rfl
@[simp] lemma neighbor_set_bot (v : V) : (⊥ : G.subgraph).neighbor_set v = ∅ := rfl
@[simp] lemma neighbor_set_Sup (s : set G.subgraph) (v : V) :
(Sup s).neighbor_set v = ⋃ G' ∈ s, neighbor_set G' v :=
by { ext, simp }
@[simp] lemma neighbor_set_Inf (s : set G.subgraph) (v : V) :
(Inf s).neighbor_set v = (⋂ G' ∈ s, neighbor_set G' v) ∩ G.neighbor_set v :=
by { ext, simp }
@[simp] lemma neighbor_set_supr (f : ι → G.subgraph) (v : V) :
(⨆ i, f i).neighbor_set v = ⋃ i, (f i).neighbor_set v :=
by simp [supr]
@[simp] lemma neighbor_set_infi (f : ι → G.subgraph) (v : V) :
(⨅ i, f i).neighbor_set v = (⋂ i, (f i).neighbor_set v) ∩ G.neighbor_set v :=
by simp [infi]
@[simp] lemma edge_set_top : (⊤ : subgraph G).edge_set = G.edge_set := rfl
@[simp] lemma edge_set_bot : (⊥ : subgraph G).edge_set = ∅ :=
set.ext $ sym2.ind (by simp)
@[simp] lemma edge_set_inf {H₁ H₂ : subgraph G} : (H₁ ⊓ H₂).edge_set = H₁.edge_set ∩ H₂.edge_set :=
set.ext $ sym2.ind (by simp)
@[simp] lemma edge_set_sup {H₁ H₂ : subgraph G} : (H₁ ⊔ H₂).edge_set = H₁.edge_set ∪ H₂.edge_set :=
set.ext $ sym2.ind (by simp)
@[simp] lemma edge_set_Sup (s : set G.subgraph) : (Sup s).edge_set = ⋃ G' ∈ s, edge_set G' :=
by { ext e, induction e using sym2.ind, simp }
@[simp] lemma edge_set_Inf (s : set G.subgraph) :
(Inf s).edge_set = (⋂ G' ∈ s, edge_set G') ∩ G.edge_set :=
by { ext e, induction e using sym2.ind, simp }
@[simp] lemma edge_set_supr (f : ι → G.subgraph) : (⨆ i, f i).edge_set = ⋃ i, (f i).edge_set :=
by simp [supr]
@[simp] lemma edge_set_infi (f : ι → G.subgraph) :
(⨅ i, f i).edge_set = (⋂ i, (f i).edge_set) ∩ G.edge_set :=
by simp [infi]
@[simp] lemma spanning_coe_top : (⊤ : subgraph G).spanning_coe = G :=
by { ext, refl }
@[simp] lemma spanning_coe_bot : (⊥ : subgraph G).spanning_coe = ⊥ := rfl
/-- Turn a subgraph of a `simple_graph` into a member of its subgraph type. -/
@[simps] def _root_.simple_graph.to_subgraph (H : simple_graph V) (h : H ≤ G) : G.subgraph :=
{ verts := set.univ,
adj := H.adj,
adj_sub := h,
edge_vert := λ v w h, set.mem_univ v,
symm := H.symm }
lemma support_mono {H H' : subgraph G} (h : H ≤ H') : H.support ⊆ H'.support :=
rel.dom_mono h.2
lemma _root_.simple_graph.to_subgraph.is_spanning (H : simple_graph V) (h : H ≤ G) :
(H.to_subgraph h).is_spanning := set.mem_univ
lemma spanning_coe_le_of_le {H H' : subgraph G} (h : H ≤ H') :
H.spanning_coe ≤ H'.spanning_coe := h.2
/-- The top of the `subgraph G` lattice is equivalent to the graph itself. -/
def top_equiv : (⊤ : subgraph G).coe ≃g G :=
{ to_fun := λ v, ↑v,
inv_fun := λ v, ⟨v, trivial⟩,
left_inv := λ ⟨v, _⟩, rfl,
right_inv := λ v, rfl,
map_rel_iff' := λ a b, iff.rfl }
/-- The bottom of the `subgraph G` lattice is equivalent to the empty graph on the empty
vertex type. -/
def bot_equiv : (⊥ : subgraph G).coe ≃g (⊥ : simple_graph empty) :=
{ to_fun := λ v, v.property.elim,
inv_fun := λ v, v.elim,
left_inv := λ ⟨_, h⟩, h.elim,
right_inv := λ v, v.elim,
map_rel_iff' := λ a b, iff.rfl }
lemma edge_set_mono {H₁ H₂ : subgraph G} (h : H₁ ≤ H₂) : H₁.edge_set ≤ H₂.edge_set :=
λ e, sym2.ind h.2 e
lemma _root_.disjoint.edge_set {H₁ H₂ : subgraph G}
(h : disjoint H₁ H₂) : disjoint H₁.edge_set H₂.edge_set :=
disjoint_iff_inf_le.mpr $ by simpa using edge_set_mono h.le_bot
/-- Graph homomorphisms induce a covariant function on subgraphs. -/
@[simps]
protected def map {G' : simple_graph W} (f : G →g G') (H : G.subgraph) : G'.subgraph :=
{ verts := f '' H.verts,
adj := relation.map H.adj f f,
adj_sub := by { rintro _ _ ⟨u, v, h, rfl, rfl⟩, exact f.map_rel (H.adj_sub h) },
edge_vert := by { rintro _ _ ⟨u, v, h, rfl, rfl⟩, exact set.mem_image_of_mem _ (H.edge_vert h) },
symm := by { rintro _ _ ⟨u, v, h, rfl, rfl⟩, exact ⟨v, u, H.symm h, rfl, rfl⟩ } }
lemma map_monotone {G' : simple_graph W} (f : G →g G') : monotone (subgraph.map f) :=
begin
intros H H' h,
split,
{ intro,
simp only [map_verts, set.mem_image, forall_exists_index, and_imp],
rintro v hv rfl,
exact ⟨_, h.1 hv, rfl⟩ },
{ rintros _ _ ⟨u, v, ha, rfl, rfl⟩,
exact ⟨_, _, h.2 ha, rfl, rfl⟩ }
end
lemma map_sup {G : simple_graph V} {G' : simple_graph W} (f : G →g G')
{H H' : G.subgraph} :
(H ⊔ H').map f = H.map f ⊔ H'.map f :=
begin
ext1,
{ simp only [set.image_union, map_verts, verts_sup]},
{ ext,
simp only [relation.map, map_adj, sup_adj],
split,
{ rintro ⟨a, b, h|h, rfl, rfl⟩,
{ exact or.inl ⟨_, _, h, rfl, rfl⟩ },
{ exact or.inr ⟨_, _, h, rfl, rfl⟩ } },
{ rintro (⟨a, b, h, rfl, rfl⟩|⟨a, b, h, rfl, rfl⟩),
{ exact ⟨_, _, or.inl h, rfl, rfl⟩ },
{ exact ⟨_, _, or.inr h, rfl, rfl⟩ } } },
end
/-- Graph homomorphisms induce a contravariant function on subgraphs. -/
@[simps]
protected def comap {G' : simple_graph W} (f : G →g G') (H : G'.subgraph) : G.subgraph :=
{ verts := f ⁻¹' H.verts,
adj := λ u v, G.adj u v ∧ H.adj (f u) (f v),
adj_sub := by { rintros v w ⟨ga, ha⟩, exact ga },
edge_vert := by { rintros v w ⟨ga, ha⟩, simp [H.edge_vert ha] } }
lemma comap_monotone {G' : simple_graph W} (f : G →g G') : monotone (subgraph.comap f) :=
begin
intros H H' h,
split,
{ intro,
simp only [comap_verts, set.mem_preimage],
apply h.1, },
{ intros v w,
simp only [comap_adj, and_imp, true_and] { contextual := tt },
intro,
apply h.2, }
end
lemma map_le_iff_le_comap {G' : simple_graph W} (f : G →g G') (H : G.subgraph) (H' : G'.subgraph) :
H.map f ≤ H' ↔ H ≤ H'.comap f :=
begin
refine ⟨λ h, ⟨λ v hv, _, λ v w hvw, _⟩, λ h, ⟨λ v, _, λ v w, _⟩⟩,
{ simp only [comap_verts, set.mem_preimage],
exact h.1 ⟨v, hv, rfl⟩, },
{ simp only [H.adj_sub hvw, comap_adj, true_and],
exact h.2 ⟨v, w, hvw, rfl, rfl⟩, },
{ simp only [map_verts, set.mem_image, forall_exists_index, and_imp],
rintro w hw rfl,
exact h.1 hw, },
{ simp only [relation.map, map_adj, forall_exists_index, and_imp],
rintros u u' hu rfl rfl,
have := h.2 hu,
simp only [comap_adj] at this,
exact this.2, }
end
/-- Given two subgraphs, one a subgraph of the other, there is an induced injective homomorphism of
the subgraphs as graphs. -/
@[simps]
def inclusion {x y : subgraph G} (h : x ≤ y) : x.coe →g y.coe :=
{ to_fun := λ v, ⟨↑v, and.left h v.property⟩,
map_rel' := λ v w hvw, h.2 hvw }
lemma inclusion.injective {x y : subgraph G} (h : x ≤ y) : function.injective (inclusion h) :=
λ v w h, by { simp only [inclusion, rel_hom.coe_fn_mk, subtype.mk_eq_mk] at h, exact subtype.ext h }
/-- There is an induced injective homomorphism of a subgraph of `G` into `G`. -/
@[simps]
protected def hom (x : subgraph G) : x.coe →g G :=
{ to_fun := λ v, v,
map_rel' := λ v w hvw, x.adj_sub hvw }
lemma hom.injective {x : subgraph G} : function.injective x.hom :=
λ v w h, subtype.ext h
/-- There is an induced injective homomorphism of a subgraph of `G` as
a spanning subgraph into `G`. -/
@[simps] def spanning_hom (x : subgraph G) : x.spanning_coe →g G :=
{ to_fun := id,
map_rel' := λ v w hvw, x.adj_sub hvw }
lemma spanning_hom.injective {x : subgraph G} : function.injective x.spanning_hom :=
λ v w h, h
lemma neighbor_set_subset_of_subgraph {x y : subgraph G} (h : x ≤ y) (v : V) :
x.neighbor_set v ⊆ y.neighbor_set v :=
λ w h', h.2 h'
instance neighbor_set.decidable_pred (G' : subgraph G) [h : decidable_rel G'.adj] (v : V) :
decidable_pred (∈ G'.neighbor_set v) := h v
/-- If a graph is locally finite at a vertex, then so is a subgraph of that graph. -/
instance finite_at {G' : subgraph G} (v : G'.verts) [decidable_rel G'.adj]
[fintype (G.neighbor_set v)] : fintype (G'.neighbor_set v) :=
set.fintype_subset (G.neighbor_set v) (G'.neighbor_set_subset v)
/-- If a subgraph is locally finite at a vertex, then so are subgraphs of that subgraph.
This is not an instance because `G''` cannot be inferred. -/
def finite_at_of_subgraph {G' G'' : subgraph G} [decidable_rel G'.adj]
(h : G' ≤ G'') (v : G'.verts) [hf : fintype (G''.neighbor_set v)] :
fintype (G'.neighbor_set v) :=
set.fintype_subset (G''.neighbor_set v) (neighbor_set_subset_of_subgraph h v)
instance (G' : subgraph G) [fintype G'.verts]
(v : V) [decidable_pred (∈ G'.neighbor_set v)] : fintype (G'.neighbor_set v) :=
set.fintype_subset G'.verts (neighbor_set_subset_verts G' v)
instance coe_finite_at {G' : subgraph G} (v : G'.verts) [fintype (G'.neighbor_set v)] :
fintype (G'.coe.neighbor_set v) :=
fintype.of_equiv _ (coe_neighbor_set_equiv v).symm
lemma is_spanning.card_verts [fintype V] {G' : subgraph G} [fintype G'.verts]
(h : G'.is_spanning) : G'.verts.to_finset.card = fintype.card V :=
by { rw is_spanning_iff at h, simpa [h] }
/-- The degree of a vertex in a subgraph. It's zero for vertices outside the subgraph. -/
def degree (G' : subgraph G) (v : V) [fintype (G'.neighbor_set v)] : ℕ :=
fintype.card (G'.neighbor_set v)
lemma finset_card_neighbor_set_eq_degree {G' : subgraph G} {v : V} [fintype (G'.neighbor_set v)] :
(G'.neighbor_set v).to_finset.card = G'.degree v := by rw [degree, set.to_finset_card]
lemma degree_le (G' : subgraph G) (v : V)
[fintype (G'.neighbor_set v)] [fintype (G.neighbor_set v)] :
G'.degree v ≤ G.degree v :=
begin
rw ←card_neighbor_set_eq_degree,
exact set.card_le_of_subset (G'.neighbor_set_subset v),
end
lemma degree_le' (G' G'' : subgraph G) (h : G' ≤ G'') (v : V)
[fintype (G'.neighbor_set v)] [fintype (G''.neighbor_set v)] :
G'.degree v ≤ G''.degree v :=
set.card_le_of_subset (neighbor_set_subset_of_subgraph h v)
@[simp] lemma coe_degree (G' : subgraph G) (v : G'.verts)
[fintype (G'.coe.neighbor_set v)] [fintype (G'.neighbor_set v)] :
G'.coe.degree v = G'.degree v :=
begin
rw ←card_neighbor_set_eq_degree,
exact fintype.card_congr (coe_neighbor_set_equiv v),
end
@[simp] lemma degree_spanning_coe {G' : G.subgraph} (v : V) [fintype (G'.neighbor_set v)]
[fintype (G'.spanning_coe.neighbor_set v)] :
G'.spanning_coe.degree v = G'.degree v :=
by { rw [← card_neighbor_set_eq_degree, subgraph.degree], congr }
lemma degree_eq_one_iff_unique_adj {G' : subgraph G} {v : V} [fintype (G'.neighbor_set v)] :
G'.degree v = 1 ↔ ∃! (w : V), G'.adj v w :=
begin
rw [← finset_card_neighbor_set_eq_degree, finset.card_eq_one, finset.singleton_iff_unique_mem],
simp only [set.mem_to_finset, mem_neighbor_set],
end
end subgraph
section mk_properties
/-! ### Properties of `singleton_subgraph` and `subgraph_of_adj` -/
variables {G : simple_graph V} {G' : simple_graph W}
instance nonempty_singleton_subgraph_verts (v : V) : nonempty (G.singleton_subgraph v).verts :=
⟨⟨v, set.mem_singleton v⟩⟩
@[simp] lemma singleton_subgraph_le_iff (v : V) (H : G.subgraph) :
G.singleton_subgraph v ≤ H ↔ v ∈ H.verts :=
begin
refine ⟨λ h, h.1 (set.mem_singleton v), _⟩,
intro h,
split,
{ simp [h] },
{ simp [-set.bot_eq_empty] }
end
@[simp] lemma map_singleton_subgraph (f : G →g G') {v : V} :
subgraph.map f (G.singleton_subgraph v) = G'.singleton_subgraph (f v) :=
by ext; simp only [relation.map, subgraph.map_adj, singleton_subgraph_adj, pi.bot_apply,
exists_and_distrib_left, and_iff_left_iff_imp, is_empty.forall_iff, subgraph.map_verts,
singleton_subgraph_verts, set.image_singleton]
@[simp] lemma neighbor_set_singleton_subgraph (v w : V) :
(G.singleton_subgraph v).neighbor_set w = ∅ :=
by { ext u, refl }
@[simp] lemma edge_set_singleton_subgraph (v : V) :
(G.singleton_subgraph v).edge_set = ∅ :=
sym2.from_rel_bot
lemma eq_singleton_subgraph_iff_verts_eq (H : G.subgraph) {v : V} :
H = G.singleton_subgraph v ↔ H.verts = {v} :=
begin
refine ⟨λ h, by simp [h], λ h, _⟩,
ext,
{ rw [h, singleton_subgraph_verts] },
{ simp only [Prop.bot_eq_false, singleton_subgraph_adj, pi.bot_apply, iff_false],
intro ha,
have ha1 := ha.fst_mem,
have ha2 := ha.snd_mem,
rw [h, set.mem_singleton_iff] at ha1 ha2,
subst_vars,
exact ha.ne rfl },
end
instance nonempty_subgraph_of_adj_verts {v w : V} (hvw : G.adj v w) :
nonempty (G.subgraph_of_adj hvw).verts := ⟨⟨v, by simp⟩⟩
@[simp] lemma edge_set_subgraph_of_adj {v w : V} (hvw : G.adj v w) :
(G.subgraph_of_adj hvw).edge_set = {⟦(v, w)⟧} :=
begin
ext e,
refine e.ind _,
simp only [eq_comm, set.mem_singleton_iff, subgraph.mem_edge_set, subgraph_of_adj_adj,
iff_self, forall_2_true_iff],
end
lemma subgraph_of_adj_symm {v w : V} (hvw : G.adj v w) :
G.subgraph_of_adj hvw.symm = G.subgraph_of_adj hvw :=
by ext; simp [or_comm, and_comm]
@[simp] lemma map_subgraph_of_adj (f : G →g G')
{v w : V} (hvw : G.adj v w) :
subgraph.map f (G.subgraph_of_adj hvw) = G'.subgraph_of_adj (f.map_adj hvw) :=
begin
ext,
{ simp only [subgraph.map_verts, subgraph_of_adj_verts, set.mem_image,
set.mem_insert_iff, set.mem_singleton_iff],
split,
{ rintro ⟨u, rfl|rfl, rfl⟩; simp },
{ rintro (rfl|rfl),
{ use v, simp },
{ use w, simp } } },
{ simp only [relation.map, subgraph.map_adj, subgraph_of_adj_adj, quotient.eq, sym2.rel_iff],
split,
{ rintro ⟨a, b, (⟨rfl,rfl⟩|⟨rfl,rfl⟩), rfl, rfl⟩; simp },
{ rintro (⟨rfl,rfl⟩|⟨rfl,rfl⟩),
{ use [v, w], simp },
{ use [w, v], simp } } }
end
lemma neighbor_set_subgraph_of_adj_subset {u v w : V} (hvw : G.adj v w) :
(G.subgraph_of_adj hvw).neighbor_set u ⊆ {v, w} :=
(G.subgraph_of_adj hvw).neighbor_set_subset_verts _
@[simp] lemma neighbor_set_fst_subgraph_of_adj {v w : V} (hvw : G.adj v w) :
(G.subgraph_of_adj hvw).neighbor_set v = {w} :=
begin
ext u,
suffices : w = u ↔ u = w, by simpa [hvw.ne.symm] using this,
rw eq_comm,
end
@[simp] lemma neighbor_set_snd_subgraph_of_adj {v w : V} (hvw : G.adj v w) :
(G.subgraph_of_adj hvw).neighbor_set w = {v} :=
begin
rw subgraph_of_adj_symm hvw.symm,
exact neighbor_set_fst_subgraph_of_adj hvw.symm,
end
@[simp] lemma neighbor_set_subgraph_of_adj_of_ne_of_ne {u v w : V} (hvw : G.adj v w)
(hv : u ≠ v) (hw : u ≠ w) :
(G.subgraph_of_adj hvw).neighbor_set u = ∅ :=
by { ext, simp [hv.symm, hw.symm] }
lemma neighbor_set_subgraph_of_adj [decidable_eq V] {u v w : V} (hvw : G.adj v w) :
(G.subgraph_of_adj hvw).neighbor_set u =
(if u = v then {w} else ∅) ∪ (if u = w then {v} else ∅) :=
by split_ifs; subst_vars; simp [*]
lemma singleton_subgraph_fst_le_subgraph_of_adj {u v : V} {h : G.adj u v} :
G.singleton_subgraph u ≤ G.subgraph_of_adj h :=
by split; simp [-set.bot_eq_empty]
lemma singleton_subgraph_snd_le_subgraph_of_adj {u v : V} {h : G.adj u v} :
G.singleton_subgraph v ≤ G.subgraph_of_adj h :=
by split; simp [-set.bot_eq_empty]
end mk_properties
namespace subgraph
variables {G : simple_graph V}
/-! ### Subgraphs of subgraphs -/
/-- Given a subgraph of a subgraph of `G`, construct a subgraph of `G`. -/
@[reducible]
protected def coe_subgraph {G' : G.subgraph} : G'.coe.subgraph → G.subgraph := subgraph.map G'.hom
/-- Given a subgraph of `G`, restrict it to being a subgraph of another subgraph `G'` by
taking the portion of `G` that intersects `G'`. -/
@[reducible]
protected def restrict {G' : G.subgraph} : G.subgraph → G'.coe.subgraph := subgraph.comap G'.hom
lemma restrict_coe_subgraph {G' : G.subgraph} (G'' : G'.coe.subgraph) :
G''.coe_subgraph.restrict = G'' :=
begin
ext,
{ simp },
{ simp only [relation.map, comap_adj, coe_adj, subtype.coe_prop, hom_apply, map_adj,
set_coe.exists, subtype.coe_mk, exists_and_distrib_right, exists_eq_right_right,
subtype.coe_eta, exists_true_left, exists_eq_right, and_iff_right_iff_imp],
apply G''.adj_sub, }
end
lemma coe_subgraph_injective (G' : G.subgraph) :
function.injective (subgraph.coe_subgraph : G'.coe.subgraph → G.subgraph) :=
function.left_inverse.injective restrict_coe_subgraph
/-! ### Edge deletion -/
/-- Given a subgraph `G'` and a set of vertex pairs, remove all of the corresponding edges
from its edge set, if present.
See also: `simple_graph.delete_edges`. -/
def delete_edges (G' : G.subgraph) (s : set (sym2 V)) : G.subgraph :=
{ verts := G'.verts,
adj := G'.adj \ sym2.to_rel s,
adj_sub := λ a b h', G'.adj_sub h'.1,
edge_vert := λ a b h', G'.edge_vert h'.1,
symm := λ a b, by simp [G'.adj_comm, sym2.eq_swap] }
section delete_edges
variables {G' : G.subgraph} (s : set (sym2 V))
@[simp] lemma delete_edges_verts : (G'.delete_edges s).verts = G'.verts := rfl
@[simp] lemma delete_edges_adj (v w : V) :
(G'.delete_edges s).adj v w ↔ G'.adj v w ∧ ¬ ⟦(v, w)⟧ ∈ s := iff.rfl
@[simp] lemma delete_edges_delete_edges (s s' : set (sym2 V)) :
(G'.delete_edges s).delete_edges s' = G'.delete_edges (s ∪ s') :=
by ext; simp [and_assoc, not_or_distrib]
@[simp] lemma delete_edges_empty_eq : G'.delete_edges ∅ = G' :=
by ext; simp
@[simp] lemma delete_edges_spanning_coe_eq :
G'.spanning_coe.delete_edges s = (G'.delete_edges s).spanning_coe :=
by { ext, simp }
lemma delete_edges_coe_eq (s : set (sym2 G'.verts)) :
G'.coe.delete_edges s = (G'.delete_edges (sym2.map coe '' s)).coe :=
begin
ext ⟨v, hv⟩ ⟨w, hw⟩,
simp only [simple_graph.delete_edges_adj, coe_adj, subtype.coe_mk, delete_edges_adj,
set.mem_image, not_exists, not_and, and.congr_right_iff],
intro h,
split,
{ intros hs,
refine sym2.ind _,
rintro ⟨v', hv'⟩ ⟨w', hw'⟩,
simp only [sym2.map_pair_eq, subtype.coe_mk, quotient.eq],
contrapose!,
rintro (_ | _); simpa [sym2.eq_swap], },
{ intros h' hs,
exact h' _ hs rfl, },
end
lemma coe_delete_edges_eq (s : set (sym2 V)) :
(G'.delete_edges s).coe = G'.coe.delete_edges (sym2.map coe ⁻¹' s) :=
by { ext ⟨v, hv⟩ ⟨w, hw⟩, simp }
lemma delete_edges_le : G'.delete_edges s ≤ G' :=
by split; simp { contextual := tt }
lemma delete_edges_le_of_le {s s' : set (sym2 V)} (h : s ⊆ s') :
G'.delete_edges s' ≤ G'.delete_edges s :=
begin
split;
simp only [delete_edges_verts, delete_edges_adj, true_and, and_imp] {contextual := tt},
exact λ v w hvw hs' hs, hs' (h hs),
end
@[simp] lemma delete_edges_inter_edge_set_left_eq :
G'.delete_edges (G'.edge_set ∩ s) = G'.delete_edges s :=
by ext; simp [imp_false] { contextual := tt }
@[simp] lemma delete_edges_inter_edge_set_right_eq :
G'.delete_edges (s ∩ G'.edge_set) = G'.delete_edges s :=
by ext; simp [imp_false] { contextual := tt }
lemma coe_delete_edges_le :
(G'.delete_edges s).coe ≤ (G'.coe : simple_graph G'.verts) :=
λ v w, by simp { contextual := tt }
lemma spanning_coe_delete_edges_le (G' : G.subgraph) (s : set (sym2 V)) :
(G'.delete_edges s).spanning_coe ≤ G'.spanning_coe :=
spanning_coe_le_of_le (delete_edges_le s)
end delete_edges
/-! ### Induced subgraphs -/
/- Given a subgraph, we can change its vertex set while removing any invalid edges, which
gives induced subgraphs. See also `simple_graph.induce` for the `simple_graph` version, which,
unlike for subgraphs, results in a graph with a different vertex type. -/
/-- The induced subgraph of a subgraph. The expectation is that `s ⊆ G'.verts` for the usual
notion of an induced subgraph, but, in general, `s` is taken to be the new vertex set and edges
are induced from the subgraph `G'`. -/
@[simps]
def induce (G' : G.subgraph) (s : set V) : G.subgraph :=
{ verts := s,
adj := λ u v, u ∈ s ∧ v ∈ s ∧ G'.adj u v,
adj_sub := λ u v, by { rintro ⟨-, -, ha⟩, exact G'.adj_sub ha },
edge_vert := λ u v, by { rintro ⟨h, -, -⟩, exact h } }
lemma _root_.simple_graph.induce_eq_coe_induce_top (s : set V) :
G.induce s = ((⊤ : G.subgraph).induce s).coe :=
by { ext v w, simp }
section induce
variables {G' G'' : G.subgraph} {s s' : set V}
lemma induce_mono (hg : G' ≤ G'') (hs : s ⊆ s') : G'.induce s ≤ G''.induce s' :=
begin
split,
{ simp [hs], },
{ simp only [induce_adj, true_and, and_imp] { contextual := tt },
intros v w hv hw ha,
exact ⟨hs hv, hs hw, hg.2 ha⟩, },
end
@[mono]
lemma induce_mono_left (hg : G' ≤ G'') : G'.induce s ≤ G''.induce s := induce_mono hg (by refl)
@[mono]
lemma induce_mono_right (hs : s ⊆ s') : G'.induce s ≤ G'.induce s' := induce_mono (by refl) hs
@[simp] lemma induce_empty : G'.induce ∅ = ⊥ :=
by ext; simp
@[simp] lemma induce_self_verts : G'.induce G'.verts = G' :=
begin
ext,
{ simp },
{ split;
simp only [induce_adj, implies_true_iff, and_true] {contextual := tt},
exact λ ha, ⟨G'.edge_vert ha, G'.edge_vert ha.symm⟩ }
end
lemma singleton_subgraph_eq_induce {v : V} :
G.singleton_subgraph v = (⊤ : G.subgraph).induce {v} :=
by ext; simp [-set.bot_eq_empty, Prop.bot_eq_false] { contextual := tt }
lemma subgraph_of_adj_eq_induce {v w : V} (hvw : G.adj v w) :
G.subgraph_of_adj hvw = (⊤ : G.subgraph).induce {v, w} :=
begin
ext,
{ simp },
{ split,
{ intro h,
simp only [subgraph_of_adj_adj, quotient.eq, sym2.rel_iff] at h,
obtain ⟨rfl, rfl⟩|⟨rfl, rfl⟩ := h; simp [hvw, hvw.symm], },
{ intro h,
simp only [induce_adj, set.mem_insert_iff, set.mem_singleton_iff, top_adj] at h,
obtain ⟨rfl|rfl, rfl|rfl, ha⟩ := h;
exact (ha.ne rfl).elim <|> simp } }
end
end induce
/-- Given a subgraph and a set of vertices, delete all the vertices from the subgraph,
if present. Any edges indicent to the deleted vertices are deleted as well. -/
@[reducible] def delete_verts (G' : G.subgraph) (s : set V) : G.subgraph := G'.induce (G'.verts \ s)
section delete_verts
variables {G' : G.subgraph} {s : set V}
lemma delete_verts_verts : (G'.delete_verts s).verts = G'.verts \ s := rfl
lemma delete_verts_adj {u v : V} :
(G'.delete_verts s).adj u v ↔
u ∈ G'.verts ∧ ¬ u ∈ s ∧ v ∈ G'.verts ∧ ¬ v ∈ s ∧ G'.adj u v :=
by simp [and_assoc]
@[simp] lemma delete_verts_delete_verts (s s' : set V) :
(G'.delete_verts s).delete_verts s' = G'.delete_verts (s ∪ s') :=
by ext; simp [not_or_distrib, and_assoc] { contextual := tt }
@[simp] lemma delete_verts_empty : G'.delete_verts ∅ = G' :=
by simp [delete_verts]
lemma delete_verts_le : G'.delete_verts s ≤ G' :=
by split; simp [set.diff_subset]
@[mono]
lemma delete_verts_mono {G' G'' : G.subgraph} (h : G' ≤ G'') :
G'.delete_verts s ≤ G''.delete_verts s :=
induce_mono h (set.diff_subset_diff_left h.1)
@[mono]
lemma delete_verts_anti {s s' : set V} (h : s ⊆ s') :
G'.delete_verts s' ≤ G'.delete_verts s :=
induce_mono (le_refl _) (set.diff_subset_diff_right h)
@[simp] lemma delete_verts_inter_verts_left_eq :
G'.delete_verts (G'.verts ∩ s) = G'.delete_verts s :=
by ext; simp [imp_false] { contextual := tt }
@[simp] lemma delete_verts_inter_verts_set_right_eq :
G'.delete_verts (s ∩ G'.verts) = G'.delete_verts s :=
by ext; simp [imp_false] { contextual := tt }
end delete_verts
end subgraph
end simple_graph
|
85f37f927d4fa8d68b9c43bc7e38ad8b0732ceb4 | 302c785c90d40ad3d6be43d33bc6a558354cc2cf | /src/analysis/special_functions/trigonometric.lean | fc2b6c5e8f9165d7a26e34b2adadddce534e6db5 | [
"Apache-2.0"
] | permissive | ilitzroth/mathlib | ea647e67f1fdfd19a0f7bdc5504e8acec6180011 | 5254ef14e3465f6504306132fe3ba9cec9ffff16 | refs/heads/master | 1,680,086,661,182 | 1,617,715,647,000 | 1,617,715,647,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 139,182 | 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
import analysis.calculus.times_cont_diff
/-!
# 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.T_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 strictly differentiable, with the derivative `cos x`. -/
lemma has_strict_deriv_at_sin (x : ℂ) : has_strict_deriv_at sin (cos x) x :=
begin
simp only [cos, div_eq_mul_inv],
convert ((((has_strict_deriv_at_id x).neg.mul_const I).cexp.sub
((has_strict_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
/-- 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 :=
(has_strict_deriv_at_sin x).has_deriv_at
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
@[continuity]
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 strictly differentiable, with the derivative
`-sin x`. -/
lemma has_strict_deriv_at_cos (x : ℂ) : has_strict_deriv_at cos (-sin x) x :=
begin
simp only [sin, div_eq_mul_inv, neg_mul_eq_neg_mul],
convert (((has_strict_deriv_at_id x).mul_const I).cexp.add
((has_strict_deriv_at_id x).neg.mul_const I).cexp).mul_const (2:ℂ)⁻¹,
simp only [function.comp, id],
ring
end
/-- 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 :=
(has_strict_deriv_at_cos x).has_deriv_at
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
@[continuity]
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 strictly differentiable, with the derivative
`cosh x`. -/
lemma has_strict_deriv_at_sinh (x : ℂ) : has_strict_deriv_at sinh (cosh x) x :=
begin
simp only [cosh, div_eq_mul_inv],
convert ((has_strict_deriv_at_exp x).sub (has_strict_deriv_at_id x).neg.cexp).mul_const (2:ℂ)⁻¹,
rw [id, mul_neg_one, sub_eq_add_neg, neg_neg]
end
/-- 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 :=
(has_strict_deriv_at_sinh x).has_deriv_at
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
@[continuity]
lemma continuous_sinh : continuous sinh :=
differentiable_sinh.continuous
lemma measurable_sinh : measurable sinh := continuous_sinh.measurable
/-- The complex hyperbolic cosine function is everywhere strictly differentiable, with the
derivative `sinh x`. -/
lemma has_strict_deriv_at_cosh (x : ℂ) : has_strict_deriv_at cosh (sinh x) x :=
begin
simp only [sinh, div_eq_mul_inv],
convert ((has_strict_deriv_at_exp x).add (has_strict_deriv_at_id x).neg.cexp).mul_const (2:ℂ)⁻¹,
rw [id, mul_neg_one, sub_eq_add_neg]
end
/-- 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 :=
(has_strict_deriv_at_cosh x).has_deriv_at
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
@[continuity]
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_strict_deriv_at.ccos (hf : has_strict_deriv_at f f' x) :
has_strict_deriv_at (λ x, complex.cos (f x)) (- complex.sin (f x) * f') x :=
(complex.has_strict_deriv_at_cos (f x)).comp x 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_strict_deriv_at.csin (hf : has_strict_deriv_at f f' x) :
has_strict_deriv_at (λ x, complex.sin (f x)) (complex.cos (f x) * f') x :=
(complex.has_strict_deriv_at_sin (f x)).comp x 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_strict_deriv_at.ccosh (hf : has_strict_deriv_at f f' x) :
has_strict_deriv_at (λ x, complex.cosh (f x)) (complex.sinh (f x) * f') x :=
(complex.has_strict_deriv_at_cosh (f x)).comp x 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_strict_deriv_at.csinh (hf : has_strict_deriv_at f f' x) :
has_strict_deriv_at (λ x, complex.sinh (f x)) (complex.cosh (f x) * f') x :=
(complex.has_strict_deriv_at_sinh (f x)).comp x 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_strict_fderiv_at.ccos (hf : has_strict_fderiv_at f f' x) :
has_strict_fderiv_at (λ x, complex.cos (f x)) (- complex.sin (f x) • f') x :=
(complex.has_strict_deriv_at_cos (f x)).comp_has_strict_fderiv_at x hf
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_strict_fderiv_at.csin (hf : has_strict_fderiv_at f f' x) :
has_strict_fderiv_at (λ x, complex.sin (f x)) (complex.cos (f x) • f') x :=
(complex.has_strict_deriv_at_sin (f x)).comp_has_strict_fderiv_at x hf
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_strict_fderiv_at.ccosh (hf : has_strict_fderiv_at f f' x) :
has_strict_fderiv_at (λ x, complex.cosh (f x)) (complex.sinh (f x) • f') x :=
(complex.has_strict_deriv_at_cosh (f x)).comp_has_strict_fderiv_at x hf
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_strict_fderiv_at.csinh (hf : has_strict_fderiv_at f f' x) :
has_strict_fderiv_at (λ x, complex.sinh (f x)) (complex.cosh (f x) • f') x :=
(complex.has_strict_deriv_at_sinh (f x)).comp_has_strict_fderiv_at x hf
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_strict_deriv_at_sin (x : ℝ) : has_strict_deriv_at sin (cos x) x :=
(complex.has_strict_deriv_at_sin x).real_of_complex
lemma has_deriv_at_sin (x : ℝ) : has_deriv_at sin (cos x) x :=
(has_strict_deriv_at_sin x).has_deriv_at
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
@[continuity]
lemma continuous_sin : continuous sin :=
differentiable_sin.continuous
lemma continuous_on_sin {s} : continuous_on sin s :=
continuous_sin.continuous_on
lemma measurable_sin : measurable sin := continuous_sin.measurable
lemma has_strict_deriv_at_cos (x : ℝ) : has_strict_deriv_at cos (-sin x) x :=
(complex.has_strict_deriv_at_cos x).real_of_complex
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
@[continuity]
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_strict_deriv_at_sinh (x : ℝ) : has_strict_deriv_at sinh (cosh x) x :=
(complex.has_strict_deriv_at_sinh x).real_of_complex
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
@[continuity]
lemma continuous_sinh : continuous sinh :=
differentiable_sinh.continuous
lemma measurable_sinh : measurable sinh := continuous_sinh.measurable
lemma has_strict_deriv_at_cosh (x : ℝ) : has_strict_deriv_at cosh (sinh x) x :=
(complex.has_strict_deriv_at_cosh x).real_of_complex
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
@[continuity]
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_strict_deriv_at.cos (hf : has_strict_deriv_at f f' x) :
has_strict_deriv_at (λ x, real.cos (f x)) (- real.sin (f x) * f') x :=
(real.has_strict_deriv_at_cos (f x)).comp x 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_strict_deriv_at.sin (hf : has_strict_deriv_at f f' x) :
has_strict_deriv_at (λ x, real.sin (f x)) (real.cos (f x) * f') x :=
(real.has_strict_deriv_at_sin (f x)).comp x 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_strict_deriv_at.cosh (hf : has_strict_deriv_at f f' x) :
has_strict_deriv_at (λ x, real.cosh (f x)) (real.sinh (f x) * f') x :=
(real.has_strict_deriv_at_cosh (f x)).comp x 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_strict_deriv_at.sinh (hf : has_strict_deriv_at f f' x) :
has_strict_deriv_at (λ x, real.sinh (f x)) (real.cosh (f x) * f') x :=
(real.has_strict_deriv_at_sinh (f x)).comp x 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_strict_fderiv_at.cos (hf : has_strict_fderiv_at f f' x) :
has_strict_fderiv_at (λ x, real.cos (f x)) (- real.sin (f x) • f') x :=
(real.has_strict_deriv_at_cos (f x)).comp_has_strict_fderiv_at x hf
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_strict_fderiv_at.sin (hf : has_strict_fderiv_at f f' x) :
has_strict_fderiv_at (λ x, real.sin (f x)) (real.cos (f x) • f') x :=
(real.has_strict_deriv_at_sin (f x)).comp_has_strict_fderiv_at x hf
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_strict_fderiv_at.cosh (hf : has_strict_fderiv_at f f' x) :
has_strict_fderiv_at (λ x, real.cosh (f x)) (real.sinh (f x) • f') x :=
(real.has_strict_deriv_at_cosh (f x)).comp_has_strict_fderiv_at x hf
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_strict_fderiv_at.sinh (hf : has_strict_fderiv_at f f' x) :
has_strict_fderiv_at (λ x, real.sinh (f x)) (real.cosh (f x) • f') x :=
(real.has_strict_deriv_at_sinh (f x)).comp_has_strict_fderiv_at x hf
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`. -/
protected 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 [real.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 [real.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 [real.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]
end real
namespace nnreal
open real
open_locale real nnreal
/-- `π` considered as a nonnegative real. -/
noncomputable def pi : ℝ≥0 := ⟨π, real.pi_pos.le⟩
@[simp] lemma coe_real_pi : (pi : ℝ) = π := rfl
lemma pi_pos : 0 < pi := by exact_mod_cast real.pi_pos
lemma pi_ne_zero : pi ≠ 0 := pi_pos.ne'
end nnreal
namespace real
open_locale real
@[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_sub_pi (x : ℝ) : cos (x - π) = -cos x :=
by simp [cos_sub]
lemma cos_pi_sub (x : ℝ) : cos (π - x) = -cos x :=
by simp [cos_sub]
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₃,
(sin_pos_of_pos_of_lt_pi h₃ (sub_floor_div_mul_lt _ pi_pos)).ne
(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 := le_antisymm (by linarith) (by linarith),
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 (π / 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_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 (π / 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 (π / 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 (π / 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 (π / 4) = sqrt 2 / 2 :=
by { transitivity cos (π / 2 ^ 2), congr, norm_num, simp }
@[simp] lemma sin_pi_div_four : sin (π / 4) = sqrt 2 / 2 :=
by { transitivity sin (π / 2 ^ 2), congr, norm_num, simp }
@[simp] lemma cos_pi_div_eight : cos (π / 8) = sqrt (2 + sqrt 2) / 2 :=
by { transitivity cos (π / 2 ^ 3), congr, norm_num, simp }
@[simp] lemma sin_pi_div_eight : sin (π / 8) = sqrt (2 - sqrt 2) / 2 :=
by { transitivity sin (π / 2 ^ 3), congr, norm_num, simp }
@[simp] lemma cos_pi_div_sixteen : cos (π / 16) = sqrt (2 + sqrt (2 + sqrt 2)) / 2 :=
by { transitivity cos (π / 2 ^ 4), congr, norm_num, simp }
@[simp] lemma sin_pi_div_sixteen : sin (π / 16) = sqrt (2 - sqrt (2 + sqrt 2)) / 2 :=
by { transitivity sin (π / 2 ^ 4), congr, norm_num, simp }
@[simp] lemma cos_pi_div_thirty_two : cos (π / 32) = sqrt (2 + sqrt (2 + sqrt (2 + sqrt 2))) / 2 :=
by { transitivity cos (π / 2 ^ 5), congr, norm_num, simp }
@[simp] lemma sin_pi_div_thirty_two : sin (π / 32) = sqrt (2 - sqrt (2 + sqrt (2 + sqrt 2))) / 2 :=
by { transitivity sin (π / 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, 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, 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, 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, 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, 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₂⟩
@[continuity]
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_strict_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_strict_deriv_at_const _ _).congr_of_eventually_eq this.symm,
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_strict_deriv_at_symm ⟨h₁, h₂⟩ this.ne'
(has_strict_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_strict_deriv_at_const _ _).congr_of_eventually_eq this.symm,
times_cont_diff_at_const.congr_of_eventually_eq this⟩ }
end
lemma has_strict_deriv_at_arcsin {x : ℝ} (h₁ : x ≠ -1) (h₂ : x ≠ 1) :
has_strict_deriv_at arcsin (1 / sqrt (1 - x ^ 2)) x :=
(deriv_arcsin_aux h₁ h₂).1
lemma has_deriv_at_arcsin {x : ℝ} (h₁ : x ≠ -1) (h₂ : x ≠ 1) :
has_deriv_at arcsin (1 / sqrt (1 - x ^ 2)) x :=
(has_strict_deriv_at_arcsin h₁ h₂).has_deriv_at
lemma 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₂]
@[continuity]
lemma continuous_arccos : continuous arccos := continuous_const.sub continuous_arcsin
lemma has_strict_deriv_at_arccos {x : ℝ} (h₁ : x ≠ -1) (h₂ : x ≠ 1) :
has_strict_deriv_at arccos (-(1 / sqrt (1 - x ^ 2))) x :=
(has_strict_deriv_at_arcsin h₁ h₂).const_sub (π / 2)
lemma has_deriv_at_arccos {x : ℝ} (h₁ : x ≠ -1) (h₂ : x ≠ 1) :
has_deriv_at arccos (-(1 / sqrt (1 - x ^ 2))) x :=
(has_deriv_at_arcsin h₁ h₂).const_sub (π / 2)
lemma 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 measurable_arg : measurable arg :=
have A : measurable (λ x : ℂ, real.arcsin (x.im / x.abs)),
from real.measurable_arcsin.comp (measurable_im.div measurable_norm),
have B : measurable (λ x : ℂ, real.arcsin ((-x).im / x.abs)),
from real.measurable_arcsin.comp ((measurable_im.comp measurable_neg).div measurable_norm),
measurable.ite (is_closed_le continuous_const continuous_re).measurable_set A $
measurable.ite (is_closed_le continuous_const continuous_im).measurable_set
(B.add_const _) (B.sub_const _)
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, -is_R_or_C.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, -is_R_or_C.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_eq_pi_iff {z : ℂ} : arg z = π ↔ z.re < 0 ∧ z.im = 0 :=
begin
by_cases h₀ : z = 0, { simp [h₀, lt_irrefl, real.pi_ne_zero.symm] },
have h₀' : (abs z : ℂ) ≠ 0, by simpa,
rw [← arg_neg_one, arg_eq_arg_iff h₀ (neg_ne_zero.2 one_ne_zero), abs_neg, abs_one,
of_real_one, one_div, ← div_eq_inv_mul, div_eq_iff_mul_eq h₀', neg_one_mul,
ext_iff, neg_im, of_real_im, neg_zero, @eq_comm _ z.im, and.congr_left_iff],
rcases z with ⟨x, y⟩, simp only,
rintro rfl,
simp only [← of_real_def, of_real_eq_zero] at *,
simp [← ne.le_iff_lt h₀, @neg_eq_iff_neg_eq _ _ _ x, @eq_comm _ (-x)]
end
lemma arg_of_real_of_neg {x : ℝ} (hx : x < 0) : arg x = π :=
arg_eq_pi_iff.2 ⟨hx, rfl⟩
/-- 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 measurable_log : measurable log :=
(measurable_of_real.comp $ real.measurable_log.comp measurable_norm).add $
(measurable_of_real.comp measurable_arg).mul_const 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 neg_pi_lt_log_im (x : ℂ) : -π < (log x).im := by simp only [log_im, neg_pi_lt_arg]
lemma log_im_le_pi (x : ℂ) : (log x).im ≤ π := by simp only [log_im, arg_le_pi]
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']
/-- `complex.exp` as a `local_homeomorph` with `source = {z | -π < im z < π}` and
`target = {z | 0 < re z} ∪ {z | im z ≠ 0}`. This definition is used to prove that `complex.log`
is complex differentiable at all points but the negative real semi-axis. -/
def exp_local_homeomorph : local_homeomorph ℂ ℂ :=
local_homeomorph.of_continuous_open
{ to_fun := exp,
inv_fun := log,
source := {z : ℂ | z.im ∈ Ioo (- π) π},
target := {z : ℂ | 0 < z.re} ∪ {z : ℂ | z.im ≠ 0},
map_source' :=
begin
rintro ⟨x, y⟩ ⟨h₁ : -π < y, h₂ : y < π⟩,
refine (not_or_of_imp $ λ hz, _).symm,
obtain rfl : y = 0,
{ rw exp_im at hz,
simpa [(real.exp_pos _).ne', real.sin_eq_zero_iff_of_lt_of_lt h₁ h₂] using hz },
rw [mem_set_of_eq, ← of_real_def, exp_of_real_re],
exact real.exp_pos x
end,
map_target' := λ z h,
suffices 0 ≤ z.re ∨ z.im ≠ 0,
by simpa [log_im, neg_pi_lt_arg, (arg_le_pi _).lt_iff_ne, arg_eq_pi_iff, not_and_distrib],
h.imp (λ h, le_of_lt h) id,
left_inv' := λ x hx, log_exp hx.1 (le_of_lt hx.2),
right_inv' := λ x hx, exp_log $ by { rintro rfl, simpa [lt_irrefl] using hx } }
continuous_exp.continuous_on is_open_map_exp (is_open_Ioo.preimage continuous_im)
lemma has_strict_deriv_at_log {x : ℂ} (h : 0 < x.re ∨ x.im ≠ 0) :
has_strict_deriv_at log x⁻¹ x :=
have h0 : x ≠ 0, by { rintro rfl, simpa [lt_irrefl] using h },
exp_local_homeomorph.has_strict_deriv_at_symm h h0 $
by simpa [exp_log h0] using has_strict_deriv_at_exp (log x)
lemma times_cont_diff_at_log {x : ℂ} (h : 0 < x.re ∨ x.im ≠ 0) {n : with_top ℕ} :
times_cont_diff_at ℂ n log x :=
exp_local_homeomorph.times_cont_diff_at_symm_deriv (exp_ne_zero $ log x) h
(has_deriv_at_exp _) times_cont_diff_exp.times_cont_diff_at
@[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]
lemma cos_add_two_pi (x : ℂ) : cos (x + 2 * π) = cos x :=
by simp [cos_add]
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 two_ne_zero', zero_mul,
add_eq_zero_iff_eq_neg, neg_eq_neg_one_mul, ← div_eq_iff (exp_ne_zero _), ← exp_sub],
field_simp only, congr' 3, ring },
rw [cos, h, ← exp_pi_mul_I, exp_eq_exp_iff_exists_int, mul_right_comm],
refine exists_congr (λ x, _),
refine (iff_of_eq $ congr_arg _ _).trans (mul_right_inj' $ mul_ne_zero two_ne_zero' I_ne_zero),
ring,
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 simp [tan, add_mul, sin_add, sin_int_mul_pi]
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_strict_deriv_at_tan {x : ℂ} (h : cos x ≠ 0) :
has_strict_deriv_at tan (1 / (cos x)^2) x :=
begin
convert (has_strict_deriv_at_sin x).div (has_strict_deriv_at_cos x) h,
rw ← sin_sq_add_cos_sq x,
ring,
end
lemma has_deriv_at_tan {x : ℂ} (h : cos x ≠ 0) :
has_deriv_at tan (1 / (cos x)^2) x :=
(has_strict_deriv_at_tan h).has_deriv_at
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 continuous_sin.continuous_within_at.norm.mul_at_top (norm_pos_iff.2 A)
(tendsto_norm_nhds_within_zero.comp B).inv_tendsto_zero,
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
@[continuity]
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 log_deriv
open complex
variables {α : Type*}
lemma measurable.carg [measurable_space α] {f : α → ℂ} (h : measurable f) :
measurable (λ x, arg (f x)) :=
measurable_arg.comp h
lemma measurable.clog [measurable_space α] {f : α → ℂ} (h : measurable f) :
measurable (λ x, log (f x)) :=
measurable_log.comp h
lemma filter.tendsto.clog {l : filter α} {f : α → ℂ} {x : ℂ} (h : tendsto f l (𝓝 x))
(hx : 0 < x.re ∨ x.im ≠ 0) :
tendsto (λ t, log (f t)) l (𝓝 $ log x) :=
(has_strict_deriv_at_log hx).continuous_at.tendsto.comp h
variables [topological_space α]
lemma continuous_at.clog {f : α → ℂ} {x : α} (h₁ : continuous_at f x)
(h₂ : 0 < (f x).re ∨ (f x).im ≠ 0) :
continuous_at (λ t, log (f t)) x :=
h₁.clog h₂
lemma continuous_within_at.clog {f : α → ℂ} {s : set α} {x : α} (h₁ : continuous_within_at f s x)
(h₂ : 0 < (f x).re ∨ (f x).im ≠ 0) :
continuous_within_at (λ t, log (f t)) s x :=
h₁.clog h₂
lemma continuous_on.clog {f : α → ℂ} {s : set α} (h₁ : continuous_on f s)
(h₂ : ∀ x ∈ s, 0 < (f x).re ∨ (f x).im ≠ 0) :
continuous_on (λ t, log (f t)) s :=
λ x hx, (h₁ x hx).clog (h₂ x hx)
lemma continuous.clog {f : α → ℂ} (h₁ : continuous f) (h₂ : ∀ x, 0 < (f x).re ∨ (f x).im ≠ 0) :
continuous (λ t, log (f t)) :=
continuous_iff_continuous_at.2 $ λ x, h₁.continuous_at.clog (h₂ x)
variables {E : Type*} [normed_group E] [normed_space ℂ E]
lemma has_strict_fderiv_at.clog {f : E → ℂ} {f' : E →L[ℂ] ℂ} {x : E}
(h₁ : has_strict_fderiv_at f f' x) (h₂ : 0 < (f x).re ∨ (f x).im ≠ 0) :
has_strict_fderiv_at (λ t, log (f t)) ((f x)⁻¹ • f') x :=
(has_strict_deriv_at_log h₂).comp_has_strict_fderiv_at x h₁
lemma has_strict_deriv_at.clog {f : ℂ → ℂ} {f' x : ℂ} (h₁ : has_strict_deriv_at f f' x)
(h₂ : 0 < (f x).re ∨ (f x).im ≠ 0) :
has_strict_deriv_at (λ t, log (f t)) (f' / f x) x :=
by { rw div_eq_inv_mul, exact (has_strict_deriv_at_log h₂).comp x h₁ }
lemma has_fderiv_at.clog {f : E → ℂ} {f' : E →L[ℂ] ℂ} {x : E}
(h₁ : has_fderiv_at f f' x) (h₂ : 0 < (f x).re ∨ (f x).im ≠ 0) :
has_fderiv_at (λ t, log (f t)) ((f x)⁻¹ • f') x :=
(has_strict_deriv_at_log h₂).has_deriv_at.comp_has_fderiv_at x h₁
lemma has_deriv_at.clog {f : ℂ → ℂ} {f' x : ℂ} (h₁ : has_deriv_at f f' x)
(h₂ : 0 < (f x).re ∨ (f x).im ≠ 0) :
has_deriv_at (λ t, log (f t)) (f' / f x) x :=
by { rw div_eq_inv_mul, exact (has_strict_deriv_at_log h₂).has_deriv_at.comp x h₁ }
lemma differentiable_at.clog {f : E → ℂ} {x : E} (h₁ : differentiable_at ℂ f x)
(h₂ : 0 < (f x).re ∨ (f x).im ≠ 0) :
differentiable_at ℂ (λ t, log (f t)) x :=
(h₁.has_fderiv_at.clog h₂).differentiable_at
lemma has_fderiv_within_at.clog {f : E → ℂ} {f' : E →L[ℂ] ℂ} {s : set E} {x : E}
(h₁ : has_fderiv_within_at f f' s x) (h₂ : 0 < (f x).re ∨ (f x).im ≠ 0) :
has_fderiv_within_at (λ t, log (f t)) ((f x)⁻¹ • f') s x :=
(has_strict_deriv_at_log h₂).has_deriv_at.comp_has_fderiv_within_at x h₁
lemma has_deriv_within_at.clog {f : ℂ → ℂ} {f' x : ℂ} {s : set ℂ}
(h₁ : has_deriv_within_at f f' s x) (h₂ : 0 < (f x).re ∨ (f x).im ≠ 0) :
has_deriv_within_at (λ t, log (f t)) (f' / f x) s x :=
by { rw div_eq_inv_mul,
exact (has_strict_deriv_at_log h₂).has_deriv_at.comp_has_deriv_within_at x h₁ }
lemma differentiable_within_at.clog {f : E → ℂ} {s : set E} {x : E}
(h₁ : differentiable_within_at ℂ f s x) (h₂ : 0 < (f x).re ∨ (f x).im ≠ 0) :
differentiable_within_at ℂ (λ t, log (f t)) s x :=
(h₁.has_fderiv_within_at.clog h₂).differentiable_within_at
lemma differentiable_on.clog {f : E → ℂ} {s : set E}
(h₁ : differentiable_on ℂ f s) (h₂ : ∀ x ∈ s, 0 < (f x).re ∨ (f x).im ≠ 0) :
differentiable_on ℂ (λ t, log (f t)) s :=
λ x hx, (h₁ x hx).clog (h₂ x hx)
lemma differentiable.clog {f : E → ℂ} (h₁ : differentiable ℂ f)
(h₂ : ∀ x, 0 < (f x).re ∨ (f x).im ≠ 0) :
differentiable ℂ (λ t, log (f t)) :=
λ x, (h₁ x).clog (h₂ x)
end log_deriv
namespace polynomial.chebyshev
open polynomial complex
/-- The `n`-th Chebyshev polynomial of the first kind evaluates on `cos θ` to the
value `cos (n * θ)`. -/
lemma T_complex_cos (θ : ℂ) :
∀ n, (T ℂ n).eval (cos θ) = cos (n * θ)
| 0 := by simp only [T_zero, eval_one, nat.cast_zero, zero_mul, cos_zero]
| 1 := by simp only [eval_X, one_mul, T_one, nat.cast_one]
| (n + 2) :=
begin
simp only [eval_X, eval_one, T_add_two, eval_sub, eval_bit0, nat.cast_succ, eval_mul],
rw [T_complex_cos (n + 1), T_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 of the first kind evaluated
on `cos θ`. -/
lemma cos_nat_mul (n : ℕ) (θ : ℂ) :
cos (n * θ) = (T ℂ n).eval (cos θ) :=
(T_complex_cos θ n).symm
/-- The `n`-th Chebyshev polynomial of the second kind evaluates on `cos θ` to the
value `sin ((n+1) * θ) / sin θ`. -/
lemma U_complex_cos (θ : ℂ) (n : ℕ) :
(U ℂ n).eval (cos θ) * sin θ = sin ((n+1) * θ) :=
begin
induction n with d hd,
{ simp only [U_zero, nat.cast_zero, eval_one, mul_one, zero_add, one_mul] },
{ rw U_eq_X_mul_U_add_T,
simp only [eval_add, eval_mul, eval_X, T_complex_cos, add_mul, mul_assoc, hd, one_mul],
conv_rhs { rw [sin_add, mul_comm] },
push_cast,
simp only [add_mul, one_mul] }
end
/-- `sin ((n + 1) * θ)` is equal to `sin θ` multiplied with the `n`-th Chebyshev polynomial of the
second kind evaluated on `cos θ`. -/
lemma sin_nat_succ_mul (n : ℕ) (θ : ℂ) :
sin ((n + 1) * θ) = (U ℂ n).eval (cos θ) * sin θ :=
(U_complex_cos θ n).symm
end polynomial.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_strict_deriv_at_tan {x : ℝ} (h : cos x ≠ 0) :
has_strict_deriv_at tan (1 / (cos x)^2) x :=
by exact_mod_cast (complex.has_strict_deriv_at_tan (by exact_mod_cast h)).real_of_complex
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
@[continuity]
lemma continuous_tan : continuous (λ x : {x | cos x ≠ 0}, tan x) :=
continuous_on_iff_continuous_restrict.1 continuous_on_tan
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_cos_pi_div_two.inv_tendsto_zero.at_top_mul zero_lt_one
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_cos_neg_pi_div_two.inv_tendsto_zero.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)
lemma arcsin_eq_arctan {x : ℝ} (h : x ∈ Ioo (-(1:ℝ)) 1) :
arcsin x = arctan (x / sqrt (1 - x ^ 2)) :=
begin
rw [arctan_eq_arcsin, div_pow, sqr_sqrt, one_add_div, div_div_eq_div_mul,
← sqrt_mul, mul_div_cancel', sub_add_cancel, sqrt_one, div_one];
nlinarith [h.1, h.2],
end
@[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]
@[continuity]
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_strict_deriv_at_arctan (x : ℝ) : has_strict_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_strict_deriv_at_symm trivial (by simpa) (has_strict_deriv_at_tan A)
lemma has_deriv_at_arctan (x : ℝ) : has_deriv_at arctan (1 / (1 + x^2)) x :=
(has_strict_deriv_at_arctan x).has_deriv_at
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_strict_deriv_at.arctan (hf : has_strict_deriv_at f f' x) :
has_strict_deriv_at (λ x, arctan (f x)) ((1 / (1 + (f x)^2)) * f') x :=
(real.has_strict_deriv_at_arctan (f x)).comp x hf
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_strict_fderiv_at.arctan (hf : has_strict_fderiv_at f f' x) :
has_strict_fderiv_at (λ x, arctan (f x)) ((1 / (1 + (f x)^2)) • f') x :=
(has_strict_deriv_at_arctan (f x)).comp_has_strict_fderiv_at x hf
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
|
1e759fe271f45baa7290f0a30e0bbf532b404e6a | 5ae26df177f810c5006841e9c73dc56e01b978d7 | /src/algebra/ordered_group.lean | 897021ce08367fb7c6948e70722e8cedba4a505a | [
"Apache-2.0"
] | permissive | ChrisHughes24/mathlib | 98322577c460bc6b1fe5c21f42ce33ad1c3e5558 | a2a867e827c2a6702beb9efc2b9282bd801d5f9a | refs/heads/master | 1,583,848,251,477 | 1,565,164,247,000 | 1,565,164,247,000 | 129,409,993 | 0 | 1 | Apache-2.0 | 1,565,164,817,000 | 1,523,628,059,000 | Lean | UTF-8 | Lean | false | false | 25,188 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Johannes Hölzl
Ordered monoids and groups.
-/
import algebra.group order.bounded_lattice tactic.basic
universe u
variable {α : Type u}
section old_structure_cmd
set_option old_structure_cmd true
/-- An ordered (additive) commutative monoid is a commutative monoid
with a partial order such that addition is an order embedding, i.e.
`a + b ≤ a + c ↔ b ≤ c`. These monoids are automatically cancellative. -/
class ordered_comm_monoid (α : Type*) extends add_comm_monoid α, partial_order α :=
(add_le_add_left : ∀ a b : α, a ≤ b → ∀ c : α, c + a ≤ c + b)
(lt_of_add_lt_add_left : ∀ a b c : α, a + b < a + c → b < c)
/-- A canonically ordered monoid is an ordered commutative monoid
in which the ordering coincides with the divisibility relation,
which is to say, `a ≤ b` iff there exists `c` with `b = a + c`.
This is satisfied by the natural numbers, for example, but not
the integers or other ordered groups. -/
class canonically_ordered_monoid (α : Type*) extends ordered_comm_monoid α, lattice.order_bot α :=
(le_iff_exists_add : ∀a b:α, a ≤ b ↔ ∃c, b = a + c)
end old_structure_cmd
section ordered_comm_monoid
variables [ordered_comm_monoid α] {a b c d : α}
lemma add_le_add_left' (h : a ≤ b) : c + a ≤ c + b :=
ordered_comm_monoid.add_le_add_left a b h c
lemma add_le_add_right' (h : a ≤ b) : a + c ≤ b + c :=
add_comm c a ▸ add_comm c b ▸ add_le_add_left' h
lemma lt_of_add_lt_add_left' : a + b < a + c → b < c :=
ordered_comm_monoid.lt_of_add_lt_add_left a b c
lemma add_le_add' (h₁ : a ≤ b) (h₂ : c ≤ d) : a + c ≤ b + d :=
le_trans (add_le_add_right' h₁) (add_le_add_left' h₂)
lemma le_add_of_nonneg_right' (h : b ≥ 0) : a ≤ a + b :=
have a + b ≥ a + 0, from add_le_add_left' h,
by rwa add_zero at this
lemma le_add_of_nonneg_left' (h : b ≥ 0) : a ≤ b + a :=
have 0 + a ≤ b + a, from add_le_add_right' h,
by rwa zero_add at this
lemma lt_of_add_lt_add_right' (h : a + b < c + b) : a < c :=
lt_of_add_lt_add_left'
(show b + a < b + c, begin rw [add_comm b a, add_comm b c], assumption end)
-- here we start using properties of zero.
lemma le_add_of_nonneg_of_le' (ha : 0 ≤ a) (hbc : b ≤ c) : b ≤ a + c :=
zero_add b ▸ add_le_add' ha hbc
lemma le_add_of_le_of_nonneg' (hbc : b ≤ c) (ha : 0 ≤ a) : b ≤ c + a :=
add_zero b ▸ add_le_add' hbc ha
lemma add_nonneg' (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a + b :=
le_add_of_nonneg_of_le' ha hb
lemma add_pos_of_pos_of_nonneg' (ha : 0 < a) (hb : 0 ≤ b) : 0 < a + b :=
lt_of_lt_of_le ha $ le_add_of_nonneg_right' hb
lemma add_pos' (ha : 0 < a) (hb : 0 < b) : 0 < a + b :=
add_pos_of_pos_of_nonneg' ha $ le_of_lt hb
lemma add_pos_of_nonneg_of_pos' (ha : 0 ≤ a) (hb : 0 < b) : 0 < a + b :=
lt_of_lt_of_le hb $ le_add_of_nonneg_left' ha
lemma add_nonpos' (ha : a ≤ 0) (hb : b ≤ 0) : a + b ≤ 0 :=
zero_add (0:α) ▸ (add_le_add' ha hb)
lemma add_le_of_nonpos_of_le' (ha : a ≤ 0) (hbc : b ≤ c) : a + b ≤ c :=
zero_add c ▸ add_le_add' ha hbc
lemma add_le_of_le_of_nonpos' (hbc : b ≤ c) (ha : a ≤ 0) : b + a ≤ c :=
add_zero c ▸ add_le_add' hbc ha
lemma add_neg_of_neg_of_nonpos' (ha : a < 0) (hb : b ≤ 0) : a + b < 0 :=
lt_of_le_of_lt (add_le_of_le_of_nonpos' (le_refl _) hb) ha
lemma add_neg_of_nonpos_of_neg' (ha : a ≤ 0) (hb : b < 0) : a + b < 0 :=
lt_of_le_of_lt (add_le_of_nonpos_of_le' ha (le_refl _)) hb
lemma add_neg' (ha : a < 0) (hb : b < 0) : a + b < 0 :=
add_neg_of_nonpos_of_neg' (le_of_lt ha) hb
lemma lt_add_of_nonneg_of_lt' (ha : 0 ≤ a) (hbc : b < c) : b < a + c :=
lt_of_lt_of_le hbc $ le_add_of_nonneg_left' ha
lemma lt_add_of_lt_of_nonneg' (hbc : b < c) (ha : 0 ≤ a) : b < c + a :=
lt_of_lt_of_le hbc $ le_add_of_nonneg_right' ha
lemma lt_add_of_pos_of_lt' (ha : 0 < a) (hbc : b < c) : b < a + c :=
lt_add_of_nonneg_of_lt' (le_of_lt ha) hbc
lemma lt_add_of_lt_of_pos' (hbc : b < c) (ha : 0 < a) : b < c + a :=
lt_add_of_lt_of_nonneg' hbc (le_of_lt ha)
lemma add_lt_of_nonpos_of_lt' (ha : a ≤ 0) (hbc : b < c) : a + b < c :=
lt_of_le_of_lt (add_le_of_nonpos_of_le' ha (le_refl _)) hbc
lemma add_lt_of_lt_of_nonpos' (hbc : b < c) (ha : a ≤ 0) : b + a < c :=
lt_of_le_of_lt (add_le_of_le_of_nonpos' (le_refl _) ha) hbc
lemma add_lt_of_neg_of_lt' (ha : a < 0) (hbc : b < c) : a + b < c :=
add_lt_of_nonpos_of_lt' (le_of_lt ha) hbc
lemma add_lt_of_lt_of_neg' (hbc : b < c) (ha : a < 0) : b + a < c :=
add_lt_of_lt_of_nonpos' hbc (le_of_lt ha)
lemma add_eq_zero_iff' (ha : 0 ≤ a) (hb : 0 ≤ b) : a + b = 0 ↔ a = 0 ∧ b = 0 :=
iff.intro
(assume hab : a + b = 0,
have a ≤ 0, from hab ▸ le_add_of_le_of_nonneg' (le_refl _) hb,
have a = 0, from le_antisymm this ha,
have b ≤ 0, from hab ▸ le_add_of_nonneg_of_le' ha (le_refl _),
have b = 0, from le_antisymm this hb,
and.intro ‹a = 0› ‹b = 0›)
(assume ⟨ha', hb'⟩, by rw [ha', hb', add_zero])
lemma bit0_pos {a : α} (h : 0 < a) : 0 < bit0 a :=
add_pos' h h
end ordered_comm_monoid
namespace units
instance [monoid α] [i : preorder α] : preorder (units α) :=
preorder.lift (coe : units α → α) i
@[simp] theorem coe_le_coe [monoid α] [preorder α] {a b : units α} :
(a : α) ≤ b ↔ a ≤ b := iff.rfl
@[simp] theorem coe_lt_coe [monoid α] [preorder α] {a b : units α} :
(a : α) < b ↔ a < b := iff.rfl
instance [monoid α] [i : partial_order α] : partial_order (units α) :=
partial_order.lift (coe : units α → α) (by ext) i
instance [monoid α] [i : linear_order α] : linear_order (units α) :=
linear_order.lift (coe : units α → α) (by ext) i
instance [monoid α] [i : decidable_linear_order α] : decidable_linear_order (units α) :=
decidable_linear_order.lift (coe : units α → α) (by ext) i
theorem max_coe [monoid α] [decidable_linear_order α] {a b : units α} :
(↑(max a b) : α) = max a b :=
by by_cases a ≤ b; simp [max, h]
theorem min_coe [monoid α] [decidable_linear_order α] {a b : units α} :
(↑(min a b) : α) = min a b :=
by by_cases a ≤ b; simp [min, h]
end units
namespace with_zero
open lattice
instance [preorder α] : preorder (with_zero α) := with_bot.preorder
instance [partial_order α] : partial_order (with_zero α) := with_bot.partial_order
instance [partial_order α] : order_bot (with_zero α) := with_bot.order_bot
instance [lattice α] : lattice (with_zero α) := with_bot.lattice
instance [linear_order α] : linear_order (with_zero α) := with_bot.linear_order
instance [decidable_linear_order α] :
decidable_linear_order (with_zero α) := with_bot.decidable_linear_order
def ordered_comm_monoid [ordered_comm_monoid α]
(zero_le : ∀ a : α, 0 ≤ a) : ordered_comm_monoid (with_zero α) :=
begin
suffices, refine {
add_le_add_left := this,
..with_zero.partial_order,
..with_zero.add_comm_monoid, .. },
{ intros a b c h,
have h' := lt_iff_le_not_le.1 h,
rw lt_iff_le_not_le at ⊢,
refine ⟨λ b h₂, _, λ h₂, h'.2 $ this _ _ h₂ _⟩,
cases h₂, cases c with c,
{ cases h'.2 (this _ _ bot_le a) },
{ refine ⟨_, rfl, _⟩,
cases a with a,
{ exact with_bot.some_le_some.1 h'.1 },
{ exact le_of_lt (lt_of_add_lt_add_left' $
with_bot.some_lt_some.1 h), } } },
{ intros a b h c ca h₂,
cases b with b,
{ rw le_antisymm h bot_le at h₂,
exact ⟨_, h₂, le_refl _⟩ },
cases a with a,
{ change c + 0 = some ca at h₂,
simp at h₂, simp [h₂],
exact ⟨_, rfl, by simpa using add_le_add_left' (zero_le b)⟩ },
{ simp at h,
cases c with c; change some _ = _ at h₂;
simp [-add_comm] at h₂; subst ca; refine ⟨_, rfl, _⟩,
{ exact h },
{ exact add_le_add_left' h } } }
end
end with_zero
namespace with_top
open lattice
instance [add_semigroup α] : add_semigroup (with_top α) :=
{ add := λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a + b)),
..@additive.add_semigroup _ $ @with_zero.semigroup (multiplicative α) _ }
lemma coe_add [add_semigroup α] {a b : α} : ((a + b : α) : with_top α) = a + b := rfl
instance [add_comm_semigroup α] : add_comm_semigroup (with_top α) :=
{ ..@additive.add_comm_semigroup _ $
@with_zero.comm_semigroup (multiplicative α) _ }
instance [add_monoid α] : add_monoid (with_top α) :=
{ zero := some 0,
add := (+),
..@additive.add_monoid _ $ @with_zero.monoid (multiplicative α) _ }
instance [add_comm_monoid α] : add_comm_monoid (with_top α) :=
{ zero := 0,
add := (+),
..@additive.add_comm_monoid _ $
@with_zero.comm_monoid (multiplicative α) _ }
instance [ordered_comm_monoid α] : ordered_comm_monoid (with_top α) :=
begin
suffices, refine {
add_le_add_left := this,
..with_top.partial_order,
..with_top.add_comm_monoid, ..},
{ intros a b c h,
refine ⟨λ c h₂, _, λ h₂, h.2 $ this _ _ h₂ _⟩,
cases h₂, cases a with a,
{ exact (not_le_of_lt h).elim le_top },
cases b with b,
{ exact (not_le_of_lt h).elim le_top },
{ exact ⟨_, rfl, le_of_lt (lt_of_add_lt_add_left' $
with_top.some_lt_some.1 h)⟩ } },
{ intros a b h c cb h₂,
cases c with c, {cases h₂},
cases b with b; cases h₂,
cases a with a, {cases le_antisymm h le_top},
simp at h,
exact ⟨_, rfl, add_le_add_left' h⟩, }
end
@[simp] lemma zero_lt_top [ordered_comm_monoid α] : (0 : with_top α) < ⊤ :=
coe_lt_top 0
@[simp] lemma zero_lt_coe [ordered_comm_monoid α] (a : α) : (0 : with_top α) < a ↔ 0 < a :=
coe_lt_coe
@[simp] lemma add_top [ordered_comm_monoid α] : ∀{a : with_top α}, a + ⊤ = ⊤
| none := rfl
| (some a) := rfl
@[simp] lemma top_add [ordered_comm_monoid α] {a : with_top α} : ⊤ + a = ⊤ := rfl
lemma add_eq_top [ordered_comm_monoid α] (a b : with_top α) : a + b = ⊤ ↔ a = ⊤ ∨ b = ⊤ :=
by cases a; cases b; simp [none_eq_top, some_eq_coe, coe_add.symm]
lemma add_lt_top [ordered_comm_monoid α] (a b : with_top α) : a + b < ⊤ ↔ a < ⊤ ∧ b < ⊤ :=
begin
apply not_iff_not.1,
simp [lt_top_iff_ne_top, add_eq_top],
finish,
apply classical.dec _,
apply classical.dec _,
end
instance [canonically_ordered_monoid α] : canonically_ordered_monoid (with_top α) :=
{ le_iff_exists_add := assume a b,
match a, b with
| a, none := show a ≤ ⊤ ↔ ∃c, ⊤ = a + c, by simp; refine ⟨⊤, _⟩; cases a; refl
| (some a), (some b) := show (a:with_top α) ≤ ↑b ↔ ∃c:with_top α, ↑b = ↑a + c,
begin
simp [canonically_ordered_monoid.le_iff_exists_add, -add_comm],
split,
{ rintro ⟨c, rfl⟩, refine ⟨c, _⟩, simp [coe_add] },
{ exact assume h, match b, h with _, ⟨some c, rfl⟩ := ⟨_, rfl⟩ end }
end
| none, some b := show (⊤ : with_top α) ≤ b ↔ ∃c:with_top α, ↑b = ⊤ + c, by simp
end,
.. with_top.order_bot,
.. with_top.ordered_comm_monoid }
end with_top
namespace with_bot
open lattice
instance [add_semigroup α] : add_semigroup (with_bot α) := with_top.add_semigroup
instance [add_comm_semigroup α] : add_comm_semigroup (with_bot α) := with_top.add_comm_semigroup
instance [add_monoid α] : add_monoid (with_bot α) := with_top.add_monoid
instance [add_comm_monoid α] : add_comm_monoid (with_bot α) := with_top.add_comm_monoid
instance [ordered_comm_monoid α] : ordered_comm_monoid (with_bot α) :=
begin
suffices, refine {
add_le_add_left := this,
..with_bot.partial_order,
..with_bot.add_comm_monoid, ..},
{ intros a b c h,
have h' := h,
rw lt_iff_le_not_le at h' ⊢,
refine ⟨λ b h₂, _, λ h₂, h'.2 $ this _ _ h₂ _⟩,
cases h₂, cases a with a,
{ exact (not_le_of_lt h).elim bot_le },
cases c with c,
{ exact (not_le_of_lt h).elim bot_le },
{ exact ⟨_, rfl, le_of_lt (lt_of_add_lt_add_left' $
with_bot.some_lt_some.1 h)⟩ } },
{ intros a b h c ca h₂,
cases c with c, {cases h₂},
cases a with a; cases h₂,
cases b with b, {cases le_antisymm h bot_le},
simp at h,
exact ⟨_, rfl, add_le_add_left' h⟩, }
end
@[simp] lemma coe_zero [add_monoid α] : ((0 : α) : with_bot α) = 0 := rfl
@[simp] lemma coe_add [add_semigroup α] (a b : α) : ((a + b : α) : with_bot α) = a + b := rfl
@[simp] lemma bot_add [ordered_comm_monoid α] (a : with_bot α) : ⊥ + a = ⊥ := rfl
@[simp] lemma add_bot [ordered_comm_monoid α] (a : with_bot α) : a + ⊥ = ⊥ := by cases a; refl
instance has_one [has_one α] : has_one (with_bot α) := ⟨(1 : α)⟩
@[simp] lemma coe_one [has_one α] : ((1 : α) : with_bot α) = 1 := rfl
end with_bot
section canonically_ordered_monoid
variables [canonically_ordered_monoid α] {a b c d : α}
lemma le_iff_exists_add : a ≤ b ↔ ∃c, b = a + c :=
canonically_ordered_monoid.le_iff_exists_add a b
@[simp] lemma zero_le (a : α) : 0 ≤ a := le_iff_exists_add.mpr ⟨a, by simp⟩
lemma bot_eq_zero : (⊥ : α) = 0 :=
le_antisymm lattice.bot_le (zero_le ⊥)
@[simp] lemma add_eq_zero_iff : a + b = 0 ↔ a = 0 ∧ b = 0 :=
add_eq_zero_iff' (zero_le _) (zero_le _)
@[simp] lemma le_zero_iff_eq : a ≤ 0 ↔ a = 0 :=
iff.intro
(assume h, le_antisymm h (zero_le a))
(assume h, h ▸ le_refl a)
protected lemma zero_lt_iff_ne_zero : 0 < a ↔ a ≠ 0 :=
iff.intro ne_of_gt $ assume hne, lt_of_le_of_ne (zero_le _) hne.symm
lemma le_add_left (h : a ≤ c) : a ≤ b + c :=
calc a = 0 + a : by simp
... ≤ b + c : add_le_add' (zero_le _) h
lemma le_add_right (h : a ≤ b) : a ≤ b + c :=
calc a = a + 0 : by simp
... ≤ b + c : add_le_add' h (zero_le _)
instance with_zero.canonically_ordered_monoid :
canonically_ordered_monoid (with_zero α) :=
{ le_iff_exists_add := λ a b, begin
cases a with a,
{ exact iff_of_true lattice.bot_le ⟨b, (zero_add b).symm⟩ },
cases b with b,
{ exact iff_of_false
(mt (le_antisymm lattice.bot_le) (by simp))
(λ ⟨c, h⟩, by cases c; cases h) },
{ simp [le_iff_exists_add, -add_comm],
split; intro h; rcases h with ⟨c, h⟩,
{ exact ⟨some c, congr_arg some h⟩ },
{ cases c; cases h,
{ exact ⟨_, (add_zero _).symm⟩ },
{ exact ⟨_, rfl⟩ } } }
end,
bot := 0,
bot_le := assume a a' h, option.no_confusion h,
.. with_zero.ordered_comm_monoid zero_le }
end canonically_ordered_monoid
instance ordered_cancel_comm_monoid.to_ordered_comm_monoid
[H : ordered_cancel_comm_monoid α] : ordered_comm_monoid α :=
{ lt_of_add_lt_add_left := @lt_of_add_lt_add_left _ _, ..H }
section ordered_cancel_comm_monoid
variables [ordered_cancel_comm_monoid α] {a b c : α}
@[simp] lemma add_le_add_iff_left (a : α) {b c : α} : a + b ≤ a + c ↔ b ≤ c :=
⟨le_of_add_le_add_left, λ h, add_le_add_left h _⟩
@[simp] lemma add_le_add_iff_right (c : α) : a + c ≤ b + c ↔ a ≤ b :=
add_comm c a ▸ add_comm c b ▸ add_le_add_iff_left c
@[simp] lemma add_lt_add_iff_left (a : α) {b c : α} : a + b < a + c ↔ b < c :=
⟨lt_of_add_lt_add_left, λ h, add_lt_add_left h _⟩
@[simp] lemma add_lt_add_iff_right (c : α) : a + c < b + c ↔ a < b :=
add_comm c a ▸ add_comm c b ▸ add_lt_add_iff_left c
@[simp] lemma le_add_iff_nonneg_right (a : α) {b : α} : a ≤ a + b ↔ 0 ≤ b :=
have a + 0 ≤ a + b ↔ 0 ≤ b, from add_le_add_iff_left a,
by rwa add_zero at this
@[simp] lemma le_add_iff_nonneg_left (a : α) {b : α} : a ≤ b + a ↔ 0 ≤ b :=
by rw [add_comm, le_add_iff_nonneg_right]
@[simp] lemma lt_add_iff_pos_right (a : α) {b : α} : a < a + b ↔ 0 < b :=
have a + 0 < a + b ↔ 0 < b, from add_lt_add_iff_left a,
by rwa add_zero at this
@[simp] lemma lt_add_iff_pos_left (a : α) {b : α} : a < b + a ↔ 0 < b :=
by rw [add_comm, lt_add_iff_pos_right]
lemma add_eq_zero_iff_eq_zero_of_nonneg
(ha : 0 ≤ a) (hb : 0 ≤ b) : a + b = 0 ↔ a = 0 ∧ b = 0 :=
⟨λ hab : a + b = 0,
by split; apply le_antisymm; try {assumption};
rw ← hab; simp [ha, hb],
λ ⟨ha', hb'⟩, by rw [ha', hb', add_zero]⟩
lemma with_top.add_lt_add_iff_left :
∀{a b c : with_top α}, a < ⊤ → (a + c < a + b ↔ c < b)
| none := assume b c h, (lt_irrefl ⊤ h).elim
| (some a) :=
begin
assume b c h,
cases b; cases c;
simp [with_top.none_eq_top, with_top.some_eq_coe, with_top.coe_lt_top, with_top.coe_lt_coe],
{ rw [← with_top.coe_add], exact with_top.coe_lt_top _ },
{ rw [← with_top.coe_add, ← with_top.coe_add, with_top.coe_lt_coe],
exact add_lt_add_iff_left _ }
end
lemma with_top.add_lt_add_iff_right
{a b c : with_top α} : a < ⊤ → (c + a < b + a ↔ c < b) :=
by simpa [add_comm] using @with_top.add_lt_add_iff_left _ _ a b c
end ordered_cancel_comm_monoid
section ordered_comm_group
variables [ordered_comm_group α] {a b c : α}
lemma neg_neg_iff_pos {α : Type} [_inst_1 : ordered_comm_group α] {a : α} : -a < 0 ↔ 0 < a :=
⟨ pos_of_neg_neg, neg_neg_of_pos ⟩
@[simp] lemma neg_le_neg_iff : -a ≤ -b ↔ b ≤ a :=
have a + b + -a ≤ a + b + -b ↔ -a ≤ -b, from add_le_add_iff_left _,
by simp at this; simp [this]
lemma neg_le : -a ≤ b ↔ -b ≤ a :=
have -a ≤ -(-b) ↔ -b ≤ a, from neg_le_neg_iff,
by rwa neg_neg at this
lemma le_neg : a ≤ -b ↔ b ≤ -a :=
have -(-a) ≤ -b ↔ b ≤ -a, from neg_le_neg_iff,
by rwa neg_neg at this
@[simp] lemma neg_nonpos : -a ≤ 0 ↔ 0 ≤ a :=
have -a ≤ -0 ↔ 0 ≤ a, from neg_le_neg_iff,
by rwa neg_zero at this
@[simp] lemma neg_nonneg : 0 ≤ -a ↔ a ≤ 0 :=
have -0 ≤ -a ↔ a ≤ 0, from neg_le_neg_iff,
by rwa neg_zero at this
@[simp] lemma neg_lt_neg_iff : -a < -b ↔ b < a :=
have a + b + -a < a + b + -b ↔ -a < -b, from add_lt_add_iff_left _,
by simp at this; simp [this]
lemma neg_lt_zero : -a < 0 ↔ 0 < a :=
have -a < -0 ↔ 0 < a, from neg_lt_neg_iff,
by rwa neg_zero at this
lemma neg_pos : 0 < -a ↔ a < 0 :=
have -0 < -a ↔ a < 0, from neg_lt_neg_iff,
by rwa neg_zero at this
lemma neg_lt : -a < b ↔ -b < a :=
have -a < -(-b) ↔ -b < a, from neg_lt_neg_iff,
by rwa neg_neg at this
lemma lt_neg : a < -b ↔ b < -a :=
have -(-a) < -b ↔ b < -a, from neg_lt_neg_iff,
by rwa neg_neg at this
lemma sub_le_sub_iff_left (a : α) {b c : α} : a - b ≤ a - c ↔ c ≤ b :=
(add_le_add_iff_left _).trans neg_le_neg_iff
lemma sub_le_sub_iff_right (c : α) : a - c ≤ b - c ↔ a ≤ b :=
add_le_add_iff_right _
lemma sub_lt_sub_iff_left (a : α) {b c : α} : a - b < a - c ↔ c < b :=
(add_lt_add_iff_left _).trans neg_lt_neg_iff
lemma sub_lt_sub_iff_right (c : α) : a - c < b - c ↔ a < b :=
add_lt_add_iff_right _
@[simp] lemma sub_nonneg : 0 ≤ a - b ↔ b ≤ a :=
have a - a ≤ a - b ↔ b ≤ a, from sub_le_sub_iff_left a,
by rwa sub_self at this
@[simp] lemma sub_nonpos : a - b ≤ 0 ↔ a ≤ b :=
have a - b ≤ b - b ↔ a ≤ b, from sub_le_sub_iff_right b,
by rwa sub_self at this
@[simp] lemma sub_pos : 0 < a - b ↔ b < a :=
have a - a < a - b ↔ b < a, from sub_lt_sub_iff_left a,
by rwa sub_self at this
@[simp] lemma sub_lt_zero : a - b < 0 ↔ a < b :=
have a - b < b - b ↔ a < b, from sub_lt_sub_iff_right b,
by rwa sub_self at this
lemma le_neg_add_iff_add_le : b ≤ -a + c ↔ a + b ≤ c :=
have -a + (a + b) ≤ -a + c ↔ a + b ≤ c, from add_le_add_iff_left _,
by rwa neg_add_cancel_left at this
lemma le_sub_iff_add_le' : b ≤ c - a ↔ a + b ≤ c :=
by rw [sub_eq_add_neg, add_comm, le_neg_add_iff_add_le]
lemma le_sub_iff_add_le : a ≤ c - b ↔ a + b ≤ c :=
by rw [le_sub_iff_add_le', add_comm]
@[simp] lemma neg_add_le_iff_le_add : -b + a ≤ c ↔ a ≤ b + c :=
have -b + a ≤ -b + (b + c) ↔ a ≤ b + c, from add_le_add_iff_left _,
by rwa neg_add_cancel_left at this
lemma sub_le_iff_le_add' : a - b ≤ c ↔ a ≤ b + c :=
by rw [sub_eq_add_neg, add_comm, neg_add_le_iff_le_add]
lemma sub_le_iff_le_add : a - c ≤ b ↔ a ≤ b + c :=
by rw [sub_le_iff_le_add', add_comm]
@[simp] lemma add_neg_le_iff_le_add : a + -c ≤ b ↔ a ≤ b + c :=
sub_le_iff_le_add
@[simp] lemma add_neg_le_iff_le_add' : a + -b ≤ c ↔ a ≤ b + c :=
sub_le_iff_le_add'
lemma neg_add_le_iff_le_add' : -c + a ≤ b ↔ a ≤ b + c :=
by rw [neg_add_le_iff_le_add, add_comm]
@[simp] lemma neg_le_sub_iff_le_add : -b ≤ a - c ↔ c ≤ a + b :=
le_sub_iff_add_le.trans neg_add_le_iff_le_add'
lemma neg_le_sub_iff_le_add' : -a ≤ b - c ↔ c ≤ a + b :=
by rw [neg_le_sub_iff_le_add, add_comm]
lemma sub_le : a - b ≤ c ↔ a - c ≤ b :=
sub_le_iff_le_add'.trans sub_le_iff_le_add.symm
theorem le_sub : a ≤ b - c ↔ c ≤ b - a :=
le_sub_iff_add_le'.trans le_sub_iff_add_le.symm
@[simp] lemma lt_neg_add_iff_add_lt : b < -a + c ↔ a + b < c :=
have -a + (a + b) < -a + c ↔ a + b < c, from add_lt_add_iff_left _,
by rwa neg_add_cancel_left at this
lemma lt_sub_iff_add_lt' : b < c - a ↔ a + b < c :=
by rw [sub_eq_add_neg, add_comm, lt_neg_add_iff_add_lt]
lemma lt_sub_iff_add_lt : a < c - b ↔ a + b < c :=
by rw [lt_sub_iff_add_lt', add_comm]
@[simp] lemma neg_add_lt_iff_lt_add : -b + a < c ↔ a < b + c :=
have -b + a < -b + (b + c) ↔ a < b + c, from add_lt_add_iff_left _,
by rwa neg_add_cancel_left at this
lemma sub_lt_iff_lt_add' : a - b < c ↔ a < b + c :=
by rw [sub_eq_add_neg, add_comm, neg_add_lt_iff_lt_add]
lemma sub_lt_iff_lt_add : a - c < b ↔ a < b + c :=
by rw [sub_lt_iff_lt_add', add_comm]
lemma neg_add_lt_iff_lt_add_right : -c + a < b ↔ a < b + c :=
by rw [neg_add_lt_iff_lt_add, add_comm]
@[simp] lemma neg_lt_sub_iff_lt_add : -b < a - c ↔ c < a + b :=
lt_sub_iff_add_lt.trans neg_add_lt_iff_lt_add_right
lemma neg_lt_sub_iff_lt_add' : -a < b - c ↔ c < a + b :=
by rw [neg_lt_sub_iff_lt_add, add_comm]
lemma sub_lt : a - b < c ↔ a - c < b :=
sub_lt_iff_lt_add'.trans sub_lt_iff_lt_add.symm
theorem lt_sub : a < b - c ↔ c < b - a :=
lt_sub_iff_add_lt'.trans lt_sub_iff_add_lt.symm
lemma sub_le_self_iff (a : α) {b : α} : a - b ≤ a ↔ 0 ≤ b :=
sub_le_iff_le_add'.trans (le_add_iff_nonneg_left _)
lemma sub_lt_self_iff (a : α) {b : α} : a - b < a ↔ 0 < b :=
sub_lt_iff_lt_add'.trans (lt_add_iff_pos_left _)
end ordered_comm_group
namespace decidable_linear_ordered_comm_group
variables [s : decidable_linear_ordered_comm_group α]
include s
instance : decidable_linear_ordered_cancel_comm_monoid α :=
{ le_of_add_le_add_left := λ x y z, le_of_add_le_add_left,
add_left_cancel := λ x y z, add_left_cancel,
add_right_cancel := λ x y z, add_right_cancel,
..s }
lemma eq_of_abs_sub_nonpos {a b : α} (h : abs (a - b) ≤ 0) : a = b :=
eq_of_abs_sub_eq_zero (le_antisymm _ _ h (abs_nonneg (a - b)))
end decidable_linear_ordered_comm_group
set_option old_structure_cmd true
/-- This is not so much a new structure as a construction mechanism
for ordered groups, by specifying only the "positive cone" of the group. -/
class nonneg_comm_group (α : Type*) extends add_comm_group α :=
(nonneg : α → Prop)
(pos : α → Prop := λ a, nonneg a ∧ ¬ nonneg (neg a))
(pos_iff : ∀ a, pos a ↔ nonneg a ∧ ¬ nonneg (-a) . order_laws_tac)
(zero_nonneg : nonneg 0)
(add_nonneg : ∀ {a b}, nonneg a → nonneg b → nonneg (a + b))
(nonneg_antisymm : ∀ {a}, nonneg a → nonneg (-a) → a = 0)
namespace nonneg_comm_group
variable [s : nonneg_comm_group α]
include s
@[reducible] instance to_ordered_comm_group : ordered_comm_group α :=
{ le := λ a b, nonneg (b - a),
lt := λ a b, pos (b - a),
lt_iff_le_not_le := λ a b, by simp; rw [pos_iff]; simp,
le_refl := λ a, by simp [zero_nonneg],
le_trans := λ a b c nab nbc, by simp [-sub_eq_add_neg];
rw ← sub_add_sub_cancel; exact add_nonneg nbc nab,
le_antisymm := λ a b nab nba, eq_of_sub_eq_zero $
nonneg_antisymm nba (by rw neg_sub; exact nab),
add_le_add_left := λ a b nab c, by simpa [(≤), preorder.le] using nab,
add_lt_add_left := λ a b nab c, by simpa [(<), preorder.lt] using nab, ..s }
theorem nonneg_def {a : α} : nonneg a ↔ 0 ≤ a :=
show _ ↔ nonneg _, by simp
theorem pos_def {a : α} : pos a ↔ 0 < a :=
show _ ↔ pos _, by simp
theorem not_zero_pos : ¬ pos (0 : α) :=
mt pos_def.1 (lt_irrefl _)
theorem zero_lt_iff_nonneg_nonneg {a : α} :
0 < a ↔ nonneg a ∧ ¬ nonneg (-a) :=
pos_def.symm.trans (pos_iff α _)
theorem nonneg_total_iff :
(∀ a : α, nonneg a ∨ nonneg (-a)) ↔
(∀ a b : α, a ≤ b ∨ b ≤ a) :=
⟨λ h a b, by have := h (b - a); rwa [neg_sub] at this,
λ h a, by rw [nonneg_def, nonneg_def, neg_nonneg]; apply h⟩
def to_decidable_linear_ordered_comm_group
[decidable_pred (@nonneg α _)]
(nonneg_total : ∀ a : α, nonneg a ∨ nonneg (-a))
: decidable_linear_ordered_comm_group α :=
{ le := (≤),
lt := (<),
lt_iff_le_not_le := @lt_iff_le_not_le _ _,
le_refl := @le_refl _ _,
le_trans := @le_trans _ _,
le_antisymm := @le_antisymm _ _,
le_total := nonneg_total_iff.1 nonneg_total,
decidable_le := by apply_instance,
decidable_eq := by apply_instance,
decidable_lt := by apply_instance,
..@nonneg_comm_group.to_ordered_comm_group _ s }
end nonneg_comm_group
|
8aceaf6a6c1ff64280ed5a3a34ac4d12cb4c69df | ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5 | /tests/compiler/strictAndOr.lean | 4edbbcb593df837d95c104a3f4e2f4710665b076 | [
"Apache-2.0"
] | permissive | dupuisf/lean4 | d082d13b01243e1de29ae680eefb476961221eef | 6a39c65bd28eb0e28c3870188f348c8914502718 | refs/heads/master | 1,676,948,755,391 | 1,610,665,114,000 | 1,610,665,114,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 324 | lean | #lang lean4
def main : IO Unit :=
IO.println (strictOr false false) *>
IO.println (strictOr false true) *>
IO.println (strictOr true false) *>
IO.println (strictOr true true) *>
IO.println (strictAnd false false) *>
IO.println (strictAnd false true) *>
IO.println (strictAnd true false) *>
IO.println (strictAnd true true)
|
ce23e51229138ce86c88c609e9c01031ac353450 | 22e97a5d648fc451e25a06c668dc03ac7ed7bc25 | /src/algebra/char_p.lean | 381ac9b1c5e9412342010494ec36ed628268babc | [
"Apache-2.0"
] | permissive | keeferrowan/mathlib | f2818da875dbc7780830d09bd4c526b0764a4e50 | aad2dfc40e8e6a7e258287a7c1580318e865817e | refs/heads/master | 1,661,736,426,952 | 1,590,438,032,000 | 1,590,438,032,000 | 266,892,663 | 0 | 0 | Apache-2.0 | 1,590,445,835,000 | 1,590,445,835,000 | null | UTF-8 | Lean | false | false | 10,678 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Kenny Lau, Joey van Langen, Casper Putz
Characteristic of semirings.
-/
import data.fintype.basic
import data.nat.choose
import data.int.modeq
import algebra.module
universes u v
/-- The generator of the kernel of the unique homomorphism ℕ → α for a semiring α -/
class char_p (α : Type u) [semiring α] (p : ℕ) : Prop :=
(cast_eq_zero_iff [] : ∀ x:ℕ, (x:α) = 0 ↔ p ∣ x)
theorem char_p.cast_eq_zero (α : Type u) [semiring α] (p : ℕ) [char_p α p] : (p:α) = 0 :=
(char_p.cast_eq_zero_iff α p p).2 (dvd_refl p)
lemma char_p.int_cast_eq_zero_iff (R : Type u) [ring R] (p : ℕ) [char_p R p] (a : ℤ) :
(a : R) = 0 ↔ (p:ℤ) ∣ a :=
begin
rcases lt_trichotomy a 0 with h|rfl|h,
{ rw [← neg_eq_zero, ← int.cast_neg, ← dvd_neg],
lift -a to ℕ using neg_nonneg.mpr (le_of_lt h) with b,
rw [int.cast_coe_nat, char_p.cast_eq_zero_iff R p, int.coe_nat_dvd] },
{ simp only [int.cast_zero, eq_self_iff_true, dvd_zero] },
{ lift a to ℕ using (le_of_lt h) with b,
rw [int.cast_coe_nat, char_p.cast_eq_zero_iff R p, int.coe_nat_dvd] }
end
lemma char_p.int_coe_eq_int_coe_iff (R : Type*) [ring R] (p : ℕ) [char_p R p] (a b : ℤ) :
(a : R) = (b : R) ↔ a ≡ b [ZMOD p] :=
by rw [eq_comm, ←sub_eq_zero, ←int.cast_sub,
char_p.int_cast_eq_zero_iff R p, int.modeq.modeq_iff_dvd]
theorem char_p.eq (α : Type u) [semiring α] {p q : ℕ} (c1 : char_p α p) (c2 : char_p α q) : p = q :=
nat.dvd_antisymm
((char_p.cast_eq_zero_iff α p q).1 (char_p.cast_eq_zero _ _))
((char_p.cast_eq_zero_iff α q p).1 (char_p.cast_eq_zero _ _))
instance char_p.of_char_zero (α : Type u) [semiring α] [char_zero α] : char_p α 0 :=
⟨λ x, by rw [zero_dvd_iff, ← nat.cast_zero, nat.cast_inj]⟩
theorem char_p.exists (α : Type u) [semiring α] : ∃ p, char_p α p :=
by letI := classical.dec_eq α; exact
classical.by_cases
(assume H : ∀ p:ℕ, (p:α) = 0 → p = 0, ⟨0,
⟨λ x, by rw [zero_dvd_iff]; exact ⟨H x, by rintro rfl; refl⟩⟩⟩)
(λ H, ⟨nat.find (classical.not_forall.1 H), ⟨λ x,
⟨λ H1, nat.dvd_of_mod_eq_zero (by_contradiction $ λ H2,
nat.find_min (classical.not_forall.1 H)
(nat.mod_lt x $ nat.pos_of_ne_zero $ not_of_not_imp $
nat.find_spec (classical.not_forall.1 H))
(not_imp_of_and_not ⟨by rwa [← nat.mod_add_div x (nat.find (classical.not_forall.1 H)),
nat.cast_add, nat.cast_mul, of_not_not (not_not_of_not_imp $ nat.find_spec (classical.not_forall.1 H)),
zero_mul, add_zero] at H1, H2⟩)),
λ H1, by rw [← nat.mul_div_cancel' H1, nat.cast_mul,
of_not_not (not_not_of_not_imp $ nat.find_spec (classical.not_forall.1 H)), zero_mul]⟩⟩⟩)
theorem char_p.exists_unique (α : Type u) [semiring α] : ∃! p, char_p α p :=
let ⟨c, H⟩ := char_p.exists α in ⟨c, H, λ y H2, char_p.eq α H2 H⟩
/-- Noncomuptable function that outputs the unique characteristic of a semiring. -/
noncomputable def ring_char (α : Type u) [semiring α] : ℕ :=
classical.some (char_p.exists_unique α)
theorem ring_char.spec (α : Type u) [semiring α] : ∀ x:ℕ, (x:α) = 0 ↔ ring_char α ∣ x :=
by letI := (classical.some_spec (char_p.exists_unique α)).1;
unfold ring_char; exact char_p.cast_eq_zero_iff α (ring_char α)
theorem ring_char.eq (α : Type u) [semiring α] {p : ℕ} (C : char_p α p) : p = ring_char α :=
(classical.some_spec (char_p.exists_unique α)).2 p C
theorem add_pow_char (α : Type u) [comm_ring α] {p : ℕ} (hp : nat.prime p)
[char_p α p] (x y : α) : (x + y)^p = x^p + y^p :=
begin
rw [add_pow, finset.sum_range_succ, nat.sub_self, pow_zero, nat.choose_self],
rw [nat.cast_one, mul_one, mul_one, add_right_inj],
transitivity,
{ refine finset.sum_eq_single 0 _ _,
{ intros b h1 h2,
have := nat.prime.dvd_choose_self (nat.pos_of_ne_zero h2) (finset.mem_range.1 h1) hp,
rw [← nat.div_mul_cancel this, nat.cast_mul, char_p.cast_eq_zero α p],
simp only [mul_zero] },
{ intro H, exfalso, apply H, exact finset.mem_range.2 hp.pos } },
rw [pow_zero, nat.sub_zero, one_mul, nat.choose_zero_right, nat.cast_one, mul_one]
end
lemma eq_iff_modeq_int (R : Type*) [ring R] (p : ℕ) [char_p R p] (a b : ℤ) :
(a : R) = b ↔ a ≡ b [ZMOD p] :=
by rw [eq_comm, ←sub_eq_zero, ←int.cast_sub,
char_p.int_cast_eq_zero_iff R p, int.modeq.modeq_iff_dvd]
lemma char_p.neg_one_ne_one (R : Type*) [ring R] (p : ℕ) [char_p R p] [fact (2 < p)] :
(-1 : R) ≠ (1 : R) :=
begin
suffices : (2 : R) ≠ 0,
{ symmetry, rw [ne.def, ← sub_eq_zero, sub_neg_eq_add], exact this },
assume h,
rw [show (2 : R) = (2 : ℕ), by norm_cast] at h,
have := (char_p.cast_eq_zero_iff R p 2).mp h,
have := nat.le_of_dvd dec_trivial this,
rw fact at *, linarith,
end
section frobenius
variables (R : Type u) [comm_ring R] {S : Type v} [comm_ring S] (f : R →* S) (g : R →+* S)
(p : ℕ) [fact p.prime] [char_p R p] [char_p S p] (x y : R)
/-- The frobenius map that sends x to x^p -/
def frobenius : R →+* R :=
{ to_fun := λ x, x^p,
map_one' := one_pow p,
map_mul' := λ x y, mul_pow x y p,
map_zero' := zero_pow (lt_trans zero_lt_one ‹nat.prime p›.one_lt),
map_add' := add_pow_char R ‹nat.prime p› }
variable {R}
theorem frobenius_def : frobenius R p x = x ^ p := rfl
theorem frobenius_mul : frobenius R p (x * y) = frobenius R p x * frobenius R p y :=
(frobenius R p).map_mul x y
theorem frobenius_one : frobenius R p 1 = 1 := one_pow _
variable {R}
theorem monoid_hom.map_frobenius : f (frobenius R p x) = frobenius S p (f x) :=
f.map_pow x p
theorem ring_hom.map_frobenius : g (frobenius R p x) = frobenius S p (g x) :=
g.map_pow x p
theorem monoid_hom.map_iterate_frobenius (n : ℕ) :
f (frobenius R p^[n] x) = (frobenius S p^[n] (f x)) :=
(nat.iterate₁ $ λ x, (f.map_frobenius p x).symm).symm
theorem ring_hom.map_iterate_frobenius (n : ℕ) :
g (frobenius R p^[n] x) = (frobenius S p^[n] (g x)) :=
g.to_monoid_hom.map_iterate_frobenius p x n
theorem monoid_hom.iterate_map_frobenius (f : R →* R) (p : ℕ) [fact p.prime] [char_p R p] (n : ℕ) :
f^[n] (frobenius R p x) = frobenius R p (f^[n] x) :=
f.iterate_map_pow _ _ _
theorem ring_hom.iterate_map_frobenius (f : R →+* R) (p : ℕ) [fact p.prime] [char_p R p] (n : ℕ) :
f^[n] (frobenius R p x) = frobenius R p (f^[n] x) :=
f.iterate_map_pow _ _ _
variable (R)
theorem frobenius_zero : frobenius R p 0 = 0 := (frobenius R p).map_zero
theorem frobenius_add : frobenius R p (x + y) = frobenius R p x + frobenius R p y :=
(frobenius R p).map_add x y
theorem frobenius_neg : frobenius R p (-x) = -frobenius R p x := (frobenius R p).map_neg x
theorem frobenius_sub : frobenius R p (x - y) = frobenius R p x - frobenius R p y :=
(frobenius R p).map_sub x y
theorem frobenius_nat_cast (n : ℕ) : frobenius R p n = n := (frobenius R p).map_nat_cast n
end frobenius
theorem frobenius_inj (α : Type u) [integral_domain α] (p : ℕ) [fact p.prime] [char_p α p] :
function.injective (frobenius α p) :=
λ x h H, by { rw ← sub_eq_zero at H ⊢, rw ← frobenius_sub at H, exact pow_eq_zero H }
namespace char_p
section
variables (α : Type u) [ring α]
lemma char_p_to_char_zero [char_p α 0] : char_zero α :=
add_group.char_zero_of_inj_zero $
λ n h0, eq_zero_of_zero_dvd ((cast_eq_zero_iff α 0 n).mp h0)
lemma cast_eq_mod (p : ℕ) [char_p α p] (k : ℕ) : (k : α) = (k % p : ℕ) :=
calc (k : α) = ↑(k % p + p * (k / p)) : by rw [nat.mod_add_div]
... = ↑(k % p) : by simp[cast_eq_zero]
theorem char_ne_zero_of_fintype (p : ℕ) [hc : char_p α p] [fintype α] : p ≠ 0 :=
assume h : p = 0,
have char_zero α := @char_p_to_char_zero α _ (h ▸ hc),
absurd (@nat.cast_injective α _ _ this) (not_injective_infinite_fintype coe)
end
section integral_domain
open nat
variables (α : Type u) [integral_domain α]
theorem char_ne_one (p : ℕ) [hc : char_p α p] : p ≠ 1 :=
assume hp : p = 1,
have ( 1 : α) = 0, by simpa using (cast_eq_zero_iff α p 1).mpr (hp ▸ dvd_refl p),
absurd this one_ne_zero
theorem char_is_prime_of_ge_two (p : ℕ) [hc : char_p α p] (hp : p ≥ 2) : nat.prime p :=
suffices ∀d ∣ p, d = 1 ∨ d = p, from ⟨hp, this⟩,
assume (d : ℕ) (hdvd : ∃ e, p = d * e),
let ⟨e, hmul⟩ := hdvd in
have (p : α) = 0, from (cast_eq_zero_iff α p p).mpr (dvd_refl p),
have (d : α) * e = 0, from (@cast_mul α _ d e) ▸ (hmul ▸ this),
or.elim (no_zero_divisors.eq_zero_or_eq_zero_of_mul_eq_zero (d : α) e this)
(assume hd : (d : α) = 0,
have p ∣ d, from (cast_eq_zero_iff α p d).mp hd,
show d = 1 ∨ d = p, from or.inr (dvd_antisymm ⟨e, hmul⟩ this))
(assume he : (e : α) = 0,
have p ∣ e, from (cast_eq_zero_iff α p e).mp he,
have e ∣ p, from dvd_of_mul_left_eq d (eq.symm hmul),
have e = p, from dvd_antisymm ‹e ∣ p› ‹p ∣ e›,
have h₀ : p > 0, from gt_of_ge_of_gt hp (nat.zero_lt_succ 1),
have d * p = 1 * p, by rw ‹e = p› at hmul; rw [one_mul]; exact eq.symm hmul,
show d = 1 ∨ d = p, from or.inl (eq_of_mul_eq_mul_right h₀ this))
theorem char_is_prime_or_zero (p : ℕ) [hc : char_p α p] : nat.prime p ∨ p = 0 :=
match p, hc with
| 0, _ := or.inr rfl
| 1, hc := absurd (eq.refl (1 : ℕ)) (@char_ne_one α _ (1 : ℕ) hc)
| (m+2), hc := or.inl (@char_is_prime_of_ge_two α _ (m+2) hc (nat.le_add_left 2 m))
end
lemma char_is_prime_of_pos (p : ℕ) [h : fact (0 < p)] [char_p α p] : fact p.prime :=
(char_p.char_is_prime_or_zero α _).resolve_right (nat.pos_iff_ne_zero.1 h)
theorem char_is_prime [fintype α] (p : ℕ) [char_p α p] : p.prime :=
or.resolve_right (char_is_prime_or_zero α p) (char_ne_zero_of_fintype α p)
end integral_domain
section char_one
variables {R : Type*}
section prio
set_option default_priority 100 -- see Note [default priority]
instance [semiring R] [char_p R 1] : subsingleton R :=
subsingleton.intro $
suffices ∀ (r : R), r = 0,
from assume a b, show a = b, by rw [this a, this b],
assume r,
calc r = 1 * r : by rw one_mul
... = (1 : ℕ) * r : by rw nat.cast_one
... = 0 * r : by rw char_p.cast_eq_zero
... = 0 : by rw zero_mul
end prio
lemma false_of_nonzero_of_char_one [nonzero_comm_ring R] [char_p R 1] : false :=
zero_ne_one $ show (0:R) = 1, from subsingleton.elim 0 1
lemma ring_char_ne_one [nonzero_semiring R] : ring_char R ≠ 1 :=
by { intros h, apply @zero_ne_one R, symmetry, rw [←nat.cast_one, ring_char.spec, h], }
end char_one
end char_p
|
56bd3be9695e377dccfa8e16a2b3616b5126741e | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/confuse_ind.lean | 1061bf18dcdae06f738caf7f9b68c0c126486458 | [
"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 | 222 | lean | attribute [reducible] definition mk_arrow (A : Sort*) (B : Sort*) :=
A → A → B
inductive confuse (A : Type)
| leaf1 : confuse
| leaf2 : nat → confuse
| node : mk_arrow A confuse → confuse
#check confuse.cases_on
|
512dfc2780ac69d9ca9a73e4595c1ab63759e42e | b00a388056c6a08748fb68d31375cfc972b8cb36 | /src/aristotle_SET_semantics.lean | cd061374cd8813505077d492fb3526b572039af5 | [] | no_license | hjvromen/aristotle | cfe8cedd09e7ba5da0df38db1ab18ddaa1c5c342 | fdc6c68ce2edcf6faaa638457cb593e922bfa521 | refs/heads/master | 1,677,764,431,125 | 1,676,554,695,000 | 1,676,554,695,000 | 327,547,662 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,727 | lean | /-
Copyright (c) 2023 Huub Vromen. All rights reserved.
Author: Huub Vromen
-/
import data.set.basic
/-- A set-theoretic semantics for Aristotle's assertoric syllogisms is used by
many authors. See, for instance, Smith, 1989.
Terms are interpreted as non-empty subsets of some set of individuals. -/
variable {α : Type}
variable {x : α}
variables {A B C : set α}
-- *** how can I stipulate that these sets have to be nonempty?
/-- semantics of the `a` relation -/
def universal_affirmative (A: set α) (B: set α) : Prop :=
A ∩ B = B
infixr ` a ` : 80 := universal_affirmative
/-- semantics of the `e` relation -/
def universal_negative (A: set α) (B: set α) : Prop :=
A ∩ B = ∅
infixr ` e ` : 80 := universal_negative
/-- semantics of the `i` relation -/
def particular_affirmative (A: set α) (B: set α) : Prop :=
(A ∩ B).nonempty
infixr ` i ` : 80 := particular_affirmative
/-- semantics of the `o` relation -/
def particular_negative (A: set α) (B: set α) : Prop :=
A ∩ B ≠ B
infixr ` o ` : 80 := particular_negative
/-- semantics of contradictory: contradictory is defined as negation -/
def c (p : Prop) : Prop := ¬ p
/-- first, we prove a helpful lemma -/
lemma inter_empty (h1 : A e B) : x ∈ B → x ∉ A :=
begin
rw universal_negative at h1,
intro h2,
by_contra h3,
have h4 : x ∈ A ∩ B, from set.mem_inter h3 h2,
have h5 : (A ∩ B).nonempty, from exists.intro x h4,
have h6 : A ∩ B ≠ ∅, from set.nonempty.ne_empty h5,
show false, from h6 h1
end
/-- Now, we prove the soundness of the axiom system DR -/
lemma Barbara₁ : A a B → B a C → A a C :=
begin
intros h1 h2,
rw universal_affirmative at *,
calc A ∩ C
= A ∩ (B ∩ C) : by rw h2
... = (A ∩ B) ∩ C : by tidy
... = B ∩ C : by rw h1
... = C : by rw h2
end
lemma Celarent₁ : A e B → B a C → A e C :=
begin
intros h1 h2,
rw universal_negative at *,
rw universal_affirmative at h2,
calc A ∩ C
= A ∩ (B ∩ C): by rw h2
... = (A ∩ B) ∩ C: by tidy
... = ∅ ∩ C : by rw h1
... = ∅ : by simp,
end
lemma e_conv : A e B → B e A :=
begin
intro h1,
rw universal_negative at *,
cc,
end
lemma a_conv : (A a B ∧ B.nonempty) → B i A :=
begin
intro h1,
cases h1.2 with p hp,
rw particular_affirmative,
rw universal_affirmative at h1,
cc,
end
lemma contr {p r : Prop} : (c r → c p) → p → r :=
begin
intros h1,
contrapose!,
assumption
end
/-- we can also prove the contradictories axioms -/
lemma contr_a : c (A a B) = A o B := by simp [c, particular_negative, universal_affirmative]
lemma contr_e : c (A e B) = A i B :=
begin
simp [c, particular_affirmative, universal_negative],
exact set.ne_empty_iff_nonempty
end
lemma contr_i : c (A i B) = A e B :=
begin
simp [c, particular_affirmative, universal_negative],
exact set.not_nonempty_iff_eq_empty
end
lemma contr_o : c (A o B) = A a B := by simp [c, particular_negative, universal_affirmative]
/-- it is, of course, also possible to prove the redundant axioms -/
lemma Darii₁ : A a B → B i C → A i C :=
begin
intros h1 h2,
--simp [universal_affirmation, particular_affirmation] at *,
--by_contra h3,
cases h2 with p hp,
cases hp,
rw universal_affirmative at h1,
have h4 : p ∈ A ∩ B, by cc,
exact exists.intro p (and.intro h4.left hp_right),
end
lemma Ferio₁ : A e B → B i C → A o C :=
begin
intros h1 h2,
cases h2 with p h,
rw particular_negative,
cases h with hb hc,
have h3 : p ∉ A, by exact inter_empty h1 hb,
simp,
by_contra h4,
rw ← h4 at hc,
show false, from h3 hc.1
end
lemma i_conv : A i B → B i A :=
begin
intros h1,
cases h1 with p h2,
cases h2 with q r,
exact exists.intro p (and.intro r q)
end
#lint |
f05831566caf81d36a40cda46f6d776fa1c5446f | 432d948a4d3d242fdfb44b81c9e1b1baacd58617 | /src/ring_theory/polynomial/bernstein.lean | 82583c8bf1723ac2a19f2d6ca36fcf64a2042a4f | [
"Apache-2.0"
] | permissive | JLimperg/aesop3 | 306cc6570c556568897ed2e508c8869667252e8a | a4a116f650cc7403428e72bd2e2c4cda300fe03f | refs/heads/master | 1,682,884,916,368 | 1,620,320,033,000 | 1,620,320,033,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 16,902 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import data.polynomial.derivative
import data.polynomial.algebra_map
import data.mv_polynomial.pderiv
import data.nat.choose.sum
import linear_algebra.basis
import ring_theory.polynomial.pochhammer
import tactic.omega
/-!
# Bernstein polynomials
The definition of the Bernstein polynomials
```
bernstein_polynomial (R : Type*) [comm_ring R] (n ν : ℕ) : polynomial R :=
(choose n ν) * X^ν * (1 - X)^(n - ν)
```
and the fact that for `ν : fin (n+1)` these are linearly independent over `ℚ`.
We prove the basic identities
* `(finset.range (n + 1)).sum (λ ν, bernstein_polynomial R n ν) = 1`
* `(finset.range (n + 1)).sum (λ ν, ν • bernstein_polynomial R n ν) = n • X`
* `(finset.range (n + 1)).sum (λ ν, (ν * (ν-1)) • bernstein_polynomial R n ν) = (n * (n-1)) • X^2`
## Notes
See also `analysis.special_functions.bernstein`, which defines the Bernstein approximations
of a continuous function `f : C([0,1], ℝ)`, and shows that these converge uniformly to `f`.
-/
noncomputable theory
open nat (choose)
open polynomial (X)
variables (R : Type*) [comm_ring R]
/--
`bernstein_polynomial R n ν` is `(choose n ν) * X^ν * (1 - X)^(n - ν)`.
Although the coefficients are integers, it is convenient to work over an arbitrary commutative ring.
-/
def bernstein_polynomial (n ν : ℕ) : polynomial R := choose n ν * X^ν * (1 - X)^(n - ν)
example : bernstein_polynomial ℤ 3 2 = 3 * X^2 - 3 * X^3 :=
begin
norm_num [bernstein_polynomial, choose],
ring,
end
namespace bernstein_polynomial
lemma eq_zero_of_lt {n ν : ℕ} (h : n < ν) : bernstein_polynomial R n ν = 0 :=
by simp [bernstein_polynomial, nat.choose_eq_zero_of_lt h]
section
variables {R} {S : Type*} [comm_ring S]
@[simp] lemma map (f : R →+* S) (n ν : ℕ) :
(bernstein_polynomial R n ν).map f = bernstein_polynomial S n ν :=
by simp [bernstein_polynomial]
end
lemma flip (n ν : ℕ) (h : ν ≤ n) :
(bernstein_polynomial R n ν).comp (1-X) = bernstein_polynomial R n (n-ν) :=
begin
dsimp [bernstein_polynomial],
simp [h, nat.sub_sub_assoc, mul_right_comm],
end
lemma flip' (n ν : ℕ) (h : ν ≤ n) :
bernstein_polynomial R n ν = (bernstein_polynomial R n (n-ν)).comp (1-X) :=
begin
rw [←flip _ _ _ h, polynomial.comp_assoc],
simp,
end
lemma eval_at_0 (n ν : ℕ) : (bernstein_polynomial R n ν).eval 0 = if ν = 0 then 1 else 0 :=
begin
dsimp [bernstein_polynomial],
split_ifs,
{ subst h, simp, },
{ simp [zero_pow (nat.pos_of_ne_zero h)], },
end
lemma eval_at_1 (n ν : ℕ) : (bernstein_polynomial R n ν).eval 1 = if ν = n then 1 else 0 :=
begin
dsimp [bernstein_polynomial],
split_ifs,
{ subst h, simp, },
{ by_cases w : 0 < n - ν,
{ simp [zero_pow w], },
{ simp [(show n < ν, by omega), nat.choose_eq_zero_of_lt], }, },
end.
lemma derivative_succ_aux (n ν : ℕ) :
(bernstein_polynomial R (n+1) (ν+1)).derivative =
(n+1) * (bernstein_polynomial R n ν - bernstein_polynomial R n (ν + 1)) :=
begin
dsimp [bernstein_polynomial],
suffices :
↑((n + 1).choose (ν + 1)) * ((↑ν + 1) * X ^ ν) * (1 - X) ^ (n - ν)
-(↑((n + 1).choose (ν + 1)) * X ^ (ν + 1) * (↑(n - ν) * (1 - X) ^ (n - ν - 1))) =
(↑n + 1) * (↑(n.choose ν) * X ^ ν * (1 - X) ^ (n - ν) -
↑(n.choose (ν + 1)) * X ^ (ν + 1) * (1 - X) ^ (n - (ν + 1))),
{ simpa [polynomial.derivative_pow, ←sub_eq_add_neg], },
conv_rhs { rw mul_sub, },
-- We'll prove the two terms match up separately.
refine congr (congr_arg has_sub.sub _) _,
{ simp only [←mul_assoc],
refine congr (congr_arg (*) (congr (congr_arg (*) _) rfl)) rfl,
-- Now it's just about binomial coefficients
exact_mod_cast congr_arg (λ m : ℕ, (m : polynomial R)) (nat.succ_mul_choose_eq n ν).symm, },
{ rw nat.sub_sub, rw [←mul_assoc,←mul_assoc], congr' 1,
rw mul_comm , rw [←mul_assoc,←mul_assoc], congr' 1,
norm_cast,
congr' 1,
convert (nat.choose_mul_succ_eq n (ν + 1)).symm using 1,
{ convert mul_comm _ _ using 2,
simp, },
{ apply mul_comm, }, },
end
lemma derivative_succ (n ν : ℕ) :
(bernstein_polynomial R n (ν+1)).derivative =
n * (bernstein_polynomial R (n-1) ν - bernstein_polynomial R (n-1) (ν+1)) :=
begin
cases n,
{ simp [bernstein_polynomial], },
{ apply derivative_succ_aux, }
end
lemma derivative_zero (n : ℕ) :
(bernstein_polynomial R n 0).derivative = -n * bernstein_polynomial R (n-1) 0 :=
begin
dsimp [bernstein_polynomial],
simp [polynomial.derivative_pow],
end
lemma iterate_derivative_at_0_eq_zero_of_lt (n : ℕ) {ν k : ℕ} :
k < ν → (polynomial.derivative^[k] (bernstein_polynomial R n ν)).eval 0 = 0 :=
begin
cases ν,
{ rintro ⟨⟩, },
{ intro w,
replace w := nat.lt_succ_iff.mp w,
revert w,
induction k with k ih generalizing n ν,
{ simp [eval_at_0], },
{ simp only [derivative_succ, int.coe_nat_eq_zero, int.nat_cast_eq_coe_nat, mul_eq_zero,
function.comp_app, function.iterate_succ,
polynomial.iterate_derivative_sub, polynomial.iterate_derivative_cast_nat_mul,
polynomial.eval_mul, polynomial.eval_nat_cast, polynomial.eval_sub],
intro h,
apply mul_eq_zero_of_right,
rw ih,
simp only [sub_zero],
convert @ih (n-1) (ν-1) _,
{ omega, },
{ omega, },
{ exact le_of_lt h, }, }, },
end
@[simp]
lemma iterate_derivative_succ_at_0_eq_zero (n ν : ℕ) :
(polynomial.derivative^[ν] (bernstein_polynomial R n (ν+1))).eval 0 = 0 :=
iterate_derivative_at_0_eq_zero_of_lt R n (lt_add_one ν)
open polynomial
/-- A Pochhammer identity that is useful for `bernstein_polynomial.iterate_derivative_at_0_aux₂`. -/
lemma iterate_derivative_at_0_aux₁ (n k : ℕ) :
k * polynomial.eval (k-n) (pochhammer ℕ n) = (k-n) * polynomial.eval (k-n+1) (pochhammer ℕ n) :=
begin
have p :=
congr_arg (eval (k-n)) ((pochhammer_succ_right ℕ n).symm.trans (pochhammer_succ_left ℕ n)),
simp only [nat.cast_id, eval_X, eval_one, eval_mul, eval_nat_cast, eval_add, eval_comp] at p,
rw [mul_comm] at p,
rw ←p,
by_cases h : n ≤ k,
{ rw nat.sub_add_cancel h, },
{ simp only [not_le] at h,
simp only [mul_eq_mul_right_iff],
right,
rw nat.sub_eq_zero_of_le (le_of_lt h),
simp only [pochhammer_eval_zero, ite_eq_right_iff],
rintro rfl,
cases h, },
end
lemma iterate_derivative_at_0_aux₂ (n k : ℕ) :
(↑k) * polynomial.eval ↑(k-n) (pochhammer R n) =
↑(k-n) * polynomial.eval (↑(k-n+1)) (pochhammer R n) :=
by simpa using congr_arg (algebra_map ℕ R) (iterate_derivative_at_0_aux₁ n k)
@[simp]
lemma iterate_derivative_at_0 (n ν : ℕ) :
(polynomial.derivative^[ν] (bernstein_polynomial R n ν)).eval 0 =
(pochhammer R ν).eval (n - (ν - 1) : ℕ) :=
begin
by_cases h : ν ≤ n,
{ induction ν with ν ih generalizing n h,
{ simp [eval_at_0], },
{ simp only [nat.succ_eq_add_one] at h,
have h' : ν ≤ n-1 := nat.le_sub_right_of_add_le h,
have w₁ : ((n - ν : ℕ) + 1 : R) = (n - ν + 1 : ℕ), { push_cast, },
simp only [derivative_succ, ih (n-1) h', iterate_derivative_succ_at_0_eq_zero,
nat.succ_sub_succ_eq_sub, nat.sub_zero, sub_zero,
iterate_derivative_sub, iterate_derivative_cast_nat_mul,
eval_one, eval_mul, eval_add, eval_sub, eval_X, eval_comp, eval_nat_cast,
function.comp_app, function.iterate_succ, pochhammer_succ_left],
rw [w₁],
by_cases h'' : ν = 0,
{ subst h'', simp, },
{ have w₂ : n - 1 - (ν - 1) = n - ν, { rw [nat.sub_sub], rw nat.add_sub_cancel', omega, },
simpa [w₂] using (iterate_derivative_at_0_aux₂ R ν n), }, }, },
{ simp only [not_le] at h,
have w₁ : n - (ν - 1) = 0, { omega, },
have w₂ : ν ≠ 0, { omega, },
rw [w₁, eq_zero_of_lt R h],
simp [w₂], }
end
lemma iterate_derivative_at_0_ne_zero [char_zero R] (n ν : ℕ) (h : ν ≤ n) :
(polynomial.derivative^[ν] (bernstein_polynomial R n ν)).eval 0 ≠ 0 :=
begin
simp only [int.coe_nat_eq_zero, bernstein_polynomial.iterate_derivative_at_0, ne.def,
nat.cast_eq_zero],
simp only [←pochhammer_eval_cast],
norm_cast,
apply ne_of_gt,
by_cases h : ν = 0,
{ subst h, simp, },
{ apply pochhammer_pos,
omega, },
end
/-!
Rather than redoing the work of evaluating the derivatives at 1,
we use the symmetry of the Bernstein polynomials.
-/
lemma iterate_derivative_at_1_eq_zero_of_lt (n : ℕ) {ν k : ℕ} :
k < n - ν → (polynomial.derivative^[k] (bernstein_polynomial R n ν)).eval 1 = 0 :=
begin
intro w,
rw flip' _ _ _ (show ν ≤ n, by omega),
simp [polynomial.eval_comp, iterate_derivative_at_0_eq_zero_of_lt R n w],
end
@[simp]
lemma iterate_derivative_at_1 (n ν : ℕ) (h : ν ≤ n) :
(polynomial.derivative^[n-ν] (bernstein_polynomial R n ν)).eval 1 =
(-1)^(n-ν) * (pochhammer R (n - ν)).eval (ν + 1) :=
begin
rw flip' _ _ _ h,
simp [polynomial.eval_comp, h],
by_cases h' : n = ν,
{ subst h', simp, },
{ replace h : ν < n, { omega, },
congr,
norm_cast,
congr,
omega, },
end
lemma iterate_derivative_at_1_ne_zero [char_zero R] (n ν : ℕ) (h : ν ≤ n) :
(polynomial.derivative^[n-ν] (bernstein_polynomial R n ν)).eval 1 ≠ 0 :=
begin
simp only [bernstein_polynomial.iterate_derivative_at_1 _ _ _ h, ne.def,
int.coe_nat_eq_zero, neg_one_pow_mul_eq_zero_iff, nat.cast_eq_zero],
rw ←nat.cast_succ,
simp only [←pochhammer_eval_cast],
norm_cast,
apply ne_of_gt,
apply pochhammer_pos,
exact nat.succ_pos ν,
end
open submodule
lemma linear_independent_aux (n k : ℕ) (h : k ≤ n + 1):
linear_independent ℚ (λ ν : fin k, bernstein_polynomial ℚ n ν) :=
begin
induction k with k ih,
{ apply linear_independent_empty_type,
rintro ⟨⟨n, ⟨⟩⟩⟩, },
{ apply linear_independent_fin_succ'.mpr,
fsplit,
{ exact ih (le_of_lt h), },
{ -- The actual work!
-- We show that the (n-k)-th derivative at 1 doesn't vanish,
-- but vanishes for everything in the span.
clear ih,
simp only [nat.succ_eq_add_one, add_le_add_iff_right] at h,
simp only [fin.coe_last, fin.init_def],
dsimp,
apply not_mem_span_of_apply_not_mem_span_image ((polynomial.derivative_lhom ℚ)^(n-k)),
simp only [not_exists, not_and, submodule.mem_map, submodule.span_image],
intros p m,
apply_fun (polynomial.eval (1 : ℚ)),
simp only [polynomial.derivative_lhom_coe, linear_map.pow_apply],
-- The right hand side is nonzero,
-- so it will suffice to show the left hand side is always zero.
suffices : (polynomial.derivative^[n-k] p).eval 1 = 0,
{ rw [this],
exact (iterate_derivative_at_1_ne_zero ℚ n k h).symm, },
apply span_induction m,
{ simp,
rintro ⟨a, w⟩, simp only [fin.coe_mk],
rw [iterate_derivative_at_1_eq_zero_of_lt ℚ _ (show n - k < n - a, by omega)], },
{ simp, },
{ intros x y hx hy, simp [hx, hy], },
{ intros a x h, simp [h], }, }, },
end
/--
The Bernstein polynomials are linearly independent.
We prove by induction that the collection of `bernstein_polynomial n ν` for `ν = 0, ..., k`
are linearly independent.
The inductive step relies on the observation that the `(n-k)`-th derivative, evaluated at 1,
annihilates `bernstein_polynomial n ν` for `ν < k`, but has a nonzero value at `ν = k`.
-/
lemma linear_independent (n : ℕ) :
linear_independent ℚ (λ ν : fin (n+1), bernstein_polynomial ℚ n ν) :=
linear_independent_aux n (n+1) (le_refl _)
lemma sum (n : ℕ) : (finset.range (n + 1)).sum (λ ν, bernstein_polynomial R n ν) = 1 :=
begin
-- We calculate `(x + (1-x))^n` in two different ways.
conv { congr, congr, skip, funext, dsimp [bernstein_polynomial], rw [mul_assoc, mul_comm], },
rw ←add_pow,
simp,
end
open polynomial
open mv_polynomial
lemma sum_smul (n : ℕ) :
(finset.range (n + 1)).sum (λ ν, ν • bernstein_polynomial R n ν) = n • X :=
begin
-- We calculate the `x`-derivative of `(x+y)^n`, evaluated at `y=(1-x)`,
-- either directly or by using the binomial theorem.
-- We'll work in `mv_polynomial bool R`.
let x : mv_polynomial bool R := mv_polynomial.X tt,
let y : mv_polynomial bool R := mv_polynomial.X ff,
have pderiv_tt_x : pderiv tt x = 1, { simp [x], },
have pderiv_tt_y : pderiv tt y = 0, { simp [pderiv_X, y], },
let e : bool → polynomial R := λ i, cond i X (1-X),
-- Start with `(x+y)^n = (x+y)^n`,
-- take the `x`-derivative, evaluate at `x=X, y=1-X`, and multiply by `X`:
have h : (x+y)^n = (x+y)^n := rfl,
apply_fun (pderiv tt) at h,
apply_fun (aeval e) at h,
apply_fun (λ p, p * X) at h,
-- On the left hand side we'll use the binomial theorem, then simplify.
-- We first prepare a tedious rewrite:
have w : ∀ k : ℕ,
↑k * polynomial.X ^ (k - 1) * (1 - polynomial.X) ^ (n - k) * ↑(n.choose k) * polynomial.X =
k • bernstein_polynomial R n k,
{ rintro (_|k),
{ simp, },
{ dsimp [bernstein_polynomial],
simp only [←nat_cast_mul, nat.succ_eq_add_one, nat.add_succ_sub_one, add_zero, pow_succ],
push_cast,
ring, }, },
conv at h {
to_lhs,
rw [add_pow, (pderiv tt).map_sum, (mv_polynomial.aeval e).map_sum, finset.sum_mul],
-- Step inside the sum:
apply_congr, skip,
simp [pderiv_mul, pderiv_tt_x, pderiv_tt_y, e, w], },
-- On the right hand side, we'll just simplify.
conv at h {
to_rhs,
rw [pderiv_pow, (pderiv tt).map_add, pderiv_tt_x, pderiv_tt_y],
simp [e] },
simpa using h,
end
lemma sum_mul_smul (n : ℕ) :
(finset.range (n + 1)).sum (λ ν, (ν * (ν-1)) • bernstein_polynomial R n ν) =
(n * (n-1)) • X^2 :=
begin
-- We calculate the second `x`-derivative of `(x+y)^n`, evaluated at `y=(1-x)`,
-- either directly or by using the binomial theorem.
-- We'll work in `mv_polynomial bool R`.
let x : mv_polynomial bool R := mv_polynomial.X tt,
let y : mv_polynomial bool R := mv_polynomial.X ff,
have pderiv_tt_x : pderiv tt x = 1, { simp [x], },
have pderiv_tt_y : pderiv tt y = 0, { simp [pderiv_X, y], },
let e : bool → polynomial R := λ i, cond i X (1-X),
-- Start with `(x+y)^n = (x+y)^n`,
-- take the second `x`-derivative, evaluate at `x=X, y=1-X`, and multiply by `X`:
have h : (x+y)^n = (x+y)^n := rfl,
apply_fun (pderiv tt) at h,
apply_fun (pderiv tt) at h,
apply_fun (aeval e) at h,
apply_fun (λ p, p * X^2) at h,
-- On the left hand side we'll use the binomial theorem, then simplify.
-- We first prepare a tedious rewrite:
have w : ∀ k : ℕ,
↑k * (↑(k-1) * polynomial.X ^ (k - 1 - 1)) *
(1 - polynomial.X) ^ (n - k) * ↑(n.choose k) * polynomial.X^2 =
(k * (k-1)) • bernstein_polynomial R n k,
{ rintro (_|k),
{ simp, },
{ rcases k with (_|k),
{ simp, },
{ dsimp [bernstein_polynomial],
simp only [←nat_cast_mul, nat.succ_eq_add_one, nat.add_succ_sub_one, add_zero, pow_succ],
push_cast,
ring, }, }, },
conv at h {
to_lhs,
rw [add_pow, (pderiv tt).map_sum, (pderiv tt).map_sum, (mv_polynomial.aeval e).map_sum,
finset.sum_mul],
-- Step inside the sum:
apply_congr, skip,
simp [pderiv_mul, pderiv_tt_x, pderiv_tt_y, e, w] },
-- On the right hand side, we'll just simplify.
conv at h {
to_rhs,
simp only [pderiv_one, pderiv_mul, pderiv_pow, pderiv_nat_cast, (pderiv tt).map_add,
pderiv_tt_x, pderiv_tt_y],
simp [e, smul_smul] },
simpa using h,
end
/--
A certain linear combination of the previous three identities,
which we'll want later.
-/
lemma variance (n : ℕ) :
(finset.range (n+1)).sum (λ ν, (n • polynomial.X - ν)^2 * bernstein_polynomial R n ν) =
n • polynomial.X * (1 - polynomial.X) :=
begin
have p :
(finset.range (n+1)).sum (λ ν, (ν * (ν-1)) • bernstein_polynomial R n ν) +
(1 - (2 * n) • polynomial.X) * (finset.range (n+1)).sum (λ ν, ν • bernstein_polynomial R n ν) +
(n^2 • X^2) * (finset.range (n+1)).sum (λ ν, bernstein_polynomial R n ν) = _ := rfl,
conv at p { to_lhs,
rw [finset.mul_sum, finset.mul_sum, ←finset.sum_add_distrib, ←finset.sum_add_distrib],
simp only [←nat_cast_mul],
simp only [←mul_assoc],
simp only [←add_mul], },
conv at p { to_rhs,
rw [sum, sum_smul, sum_mul_smul, ←nat_cast_mul], },
calc _ = _ : finset.sum_congr rfl (λ k m, _)
... = _ : p
... = _ : _,
{ congr' 1, simp only [←nat_cast_mul] with push_cast,
cases k; { simp, ring, }, },
{ simp only [←nat_cast_mul] with push_cast,
cases n; { simp, ring, }, },
end
end bernstein_polynomial
|
dd8b14c6cdc1593f4f2f9317a2b024e9bbe39aa6 | 5ae26df177f810c5006841e9c73dc56e01b978d7 | /src/data/matrix.lean | f7571d9726b77060fab6c76cdfbccf27bf4a58fe | [
"Apache-2.0"
] | permissive | ChrisHughes24/mathlib | 98322577c460bc6b1fe5c21f42ce33ad1c3e5558 | a2a867e827c2a6702beb9efc2b9282bd801d5f9a | refs/heads/master | 1,583,848,251,477 | 1,565,164,247,000 | 1,565,164,247,000 | 129,409,993 | 0 | 1 | Apache-2.0 | 1,565,164,817,000 | 1,523,628,059,000 | Lean | UTF-8 | Lean | false | false | 11,985 | lean | /-
Copyright (c) 2018 Ellen Arlt. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Ellen Arlt, Blair Shi, Sean Leather, Mario Carneiro, Johan Commelin
Matrices
-/
import algebra.module algebra.pi_instances
import data.fintype
universes u v
def matrix (m n : Type u) [fintype m] [fintype n] (α : Type v) : Type (max u v) :=
m → n → α
namespace matrix
variables {l m n o : Type u} [fintype l] [fintype m] [fintype n] [fintype o]
variables {α : Type v}
section ext
variables {M N : matrix m n α}
theorem ext_iff : (∀ i j, M i j = N i j) ↔ M = N :=
⟨λ h, funext $ λ i, funext $ h i, λ h, by simp [h]⟩
@[extensionality] theorem ext : (∀ i j, M i j = N i j) → M = N :=
ext_iff.mp
def transpose (M : matrix m n α) : matrix n m α
| x y := M y x
def col (w : m → α) : matrix m punit α
| x y := w x
def row (v : n → α) : matrix punit n α
| x y := v y
end ext
instance [has_add α] : has_add (matrix m n α) := pi.has_add
instance [add_semigroup α] : add_semigroup (matrix m n α) := pi.add_semigroup
instance [add_comm_semigroup α] : add_comm_semigroup (matrix m n α) := pi.add_comm_semigroup
instance [has_zero α] : has_zero (matrix m n α) := pi.has_zero
instance [add_monoid α] : add_monoid (matrix m n α) := pi.add_monoid
instance [add_comm_monoid α] : add_comm_monoid (matrix m n α) := pi.add_comm_monoid
instance [has_neg α] : has_neg (matrix m n α) := pi.has_neg
instance [add_group α] : add_group (matrix m n α) := pi.add_group
instance [add_comm_group α] : add_comm_group (matrix m n α) := pi.add_comm_group
@[simp] theorem zero_val [has_zero α] (i j) : (0 : matrix m n α) i j = 0 := rfl
@[simp] theorem neg_val [has_neg α] (M : matrix m n α) (i j) : (- M) i j = - M i j := rfl
@[simp] theorem add_val [has_add α] (M N : matrix m n α) (i j) : (M + N) i j = M i j + N i j := rfl
section diagonal
variables [decidable_eq n]
def diagonal [has_zero α] (d : n → α) : matrix n n α := λ i j, if i = j then d i else 0
@[simp] theorem diagonal_val_eq [has_zero α] {d : n → α} (i : n) : (diagonal d) i i = d i :=
by simp [diagonal]
@[simp] theorem diagonal_val_ne [has_zero α] {d : n → α} {i j : n} (h : i ≠ j) :
(diagonal d) i j = 0 := by simp [diagonal, h]
theorem diagonal_val_ne' [has_zero α] {d : n → α} {i j : n} (h : j ≠ i) :
(diagonal d) i j = 0 := diagonal_val_ne h.symm
@[simp] theorem diagonal_zero [has_zero α] : (diagonal (λ _, 0) : matrix n n α) = 0 :=
by simp [diagonal]; refl
section one
variables [has_zero α] [has_one α]
instance : has_one (matrix n n α) := ⟨diagonal (λ _, 1)⟩
@[simp] theorem diagonal_one : (diagonal (λ _, 1) : matrix n n α) = 1 := rfl
theorem one_val {i j} : (1 : matrix n n α) i j = if i = j then 1 else 0 := rfl
@[simp] theorem one_val_eq (i) : (1 : matrix n n α) i i = 1 := diagonal_val_eq i
@[simp] theorem one_val_ne {i j} : i ≠ j → (1 : matrix n n α) i j = 0 :=
diagonal_val_ne
theorem one_val_ne' {i j} : j ≠ i → (1 : matrix n n α) i j = 0 :=
diagonal_val_ne'
end one
end diagonal
@[simp] theorem diagonal_add [decidable_eq n] [add_monoid α] (d₁ d₂ : n → α) :
diagonal d₁ + diagonal d₂ = diagonal (λ i, d₁ i + d₂ i) :=
by ext i j; by_cases i = j; simp [h]
protected def mul [has_mul α] [add_comm_monoid α] (M : matrix l m α) (N : matrix m n α) :
matrix l n α :=
λ i k, finset.univ.sum (λ j, M i j * N j k)
local notation M `⬝` N := M.mul N
theorem mul_val [has_mul α] [add_comm_monoid α] {M : matrix l m α} {N : matrix m n α} {i k} :
(M ⬝ N) i k = finset.univ.sum (λ j, M i j * N j k) := rfl
local attribute [simp] mul_val
instance [has_mul α] [add_comm_monoid α] : has_mul (matrix n n α) := ⟨matrix.mul⟩
@[simp] theorem mul_eq_mul [has_mul α] [add_comm_monoid α] (M N : matrix n n α) :
M * N = M ⬝ N := rfl
theorem mul_val' [has_mul α] [add_comm_monoid α] {M N : matrix n n α} {i k} :
(M * N) i k = finset.univ.sum (λ j, M i j * N j k) := rfl
section semigroup
variables [semiring α]
protected theorem mul_assoc (L : matrix l m α) (M : matrix m n α) (N : matrix n o α) :
(L ⬝ M) ⬝ N = L ⬝ (M ⬝ N) :=
by classical; funext i k;
simp [finset.mul_sum, finset.sum_mul, mul_assoc];
rw finset.sum_comm
instance : semigroup (matrix n n α) :=
{ mul_assoc := matrix.mul_assoc, ..matrix.has_mul }
end semigroup
@[simp] theorem diagonal_neg [decidable_eq n] [add_group α] (d : n → α) :
-diagonal d = diagonal (λ i, -d i) :=
by ext i j; by_cases i = j; simp [h]
section semiring
variables [semiring α]
@[simp] protected theorem mul_zero (M : matrix m n α) : M ⬝ (0 : matrix n o α) = 0 :=
by ext i j; simp
@[simp] protected theorem zero_mul (M : matrix m n α) : (0 : matrix l m α) ⬝ M = 0 :=
by ext i j; simp
protected theorem mul_add (L : matrix m n α) (M N : matrix n o α) : L ⬝ (M + N) = L ⬝ M + L ⬝ N :=
by ext i j; simp [finset.sum_add_distrib, mul_add]
protected theorem add_mul (L M : matrix l m α) (N : matrix m n α) : (L + M) ⬝ N = L ⬝ N + M ⬝ N :=
by ext i j; simp [finset.sum_add_distrib, add_mul]
@[simp] theorem diagonal_mul [decidable_eq m]
(d : m → α) (M : matrix m n α) (i j) : (diagonal d).mul M i j = d i * M i j :=
by simp; rw finset.sum_eq_single i; simp [diagonal_val_ne'] {contextual := tt}
@[simp] theorem mul_diagonal [decidable_eq n]
(d : n → α) (M : matrix m n α) (i j) : (M ⬝ diagonal d) i j = M i j * d j :=
by simp; rw finset.sum_eq_single j; simp {contextual := tt}
@[simp] protected theorem one_mul [decidable_eq m] (M : matrix m n α) : (1 : matrix m m α) ⬝ M = M :=
by ext i j; rw [← diagonal_one, diagonal_mul, one_mul]
@[simp] protected theorem mul_one [decidable_eq n] (M : matrix m n α) : M ⬝ (1 : matrix n n α) = M :=
by ext i j; rw [← diagonal_one, mul_diagonal, mul_one]
instance [decidable_eq n] : monoid (matrix n n α) :=
{ one_mul := matrix.one_mul,
mul_one := matrix.mul_one,
..matrix.has_one, ..matrix.semigroup }
instance [decidable_eq n] : semiring (matrix n n α) :=
{ mul_zero := matrix.mul_zero,
zero_mul := matrix.zero_mul,
left_distrib := matrix.mul_add,
right_distrib := matrix.add_mul,
..matrix.add_comm_monoid,
..matrix.monoid }
@[simp] theorem diagonal_mul_diagonal' [decidable_eq n] (d₁ d₂ : n → α) :
(diagonal d₁) ⬝ (diagonal d₂) = diagonal (λ i, d₁ i * d₂ i) :=
by ext i j; by_cases i = j; simp [h]
theorem diagonal_mul_diagonal [decidable_eq n] (d₁ d₂ : n → α) :
diagonal d₁ * diagonal d₂ = diagonal (λ i, d₁ i * d₂ i) :=
diagonal_mul_diagonal' _ _
lemma is_add_monoid_hom_mul_left (M : matrix l m α) :
is_add_monoid_hom (λ x : matrix m n α, M ⬝ x) :=
{ to_is_add_hom := ⟨matrix.mul_add _⟩, map_zero := matrix.mul_zero _ }
def is_add_monoid_hom_mul_right (M : matrix m n α) :
is_add_monoid_hom (λ x : matrix l m α, x ⬝ M) :=
{ to_is_add_hom := ⟨λ _ _, matrix.add_mul _ _ _⟩, map_zero := matrix.zero_mul _ }
protected lemma sum_mul {β : Type*} (s : finset β) (f : β → matrix l m α)
(M : matrix m n α) : s.sum f ⬝ M = s.sum (λ a, f a ⬝ M) :=
(@finset.sum_hom _ _ _ s f _ _ (λ x, x ⬝ M)
/- This line does not type-check without `id` and `: _`. Lean did not recognize that two different
`add_monoid` instances were def-eq -/
(id (@is_add_monoid_hom_mul_right l _ _ _ _ _ _ _ M) : _)).symm
protected lemma mul_sum {β : Type*} (s : finset β) (f : β → matrix m n α)
(M : matrix l m α) : M ⬝ s.sum f = s.sum (λ a, M ⬝ f a) :=
(@finset.sum_hom _ _ _ s f _ _ (λ x, M ⬝ x)
/- This line does not type-check without `id` and `: _`. Lean did not recognize that two different
`add_monoid` instances were def-eq -/
(id (@is_add_monoid_hom_mul_left _ _ n _ _ _ _ _ M) : _)).symm
end semiring
section ring
variables [ring α]
@[simp] theorem neg_mul (M : matrix m n α) (N : matrix n o α) :
(-M) ⬝ N = -(M ⬝ N) := by ext; simp [matrix.mul]
@[simp] theorem mul_neg (M : matrix m n α) (N : matrix n o α) :
M ⬝ (-N) = -(M ⬝ N) := by ext; simp [matrix.mul]
end ring
instance [decidable_eq n] [ring α] : ring (matrix n n α) :=
{ ..matrix.add_comm_group, ..matrix.semiring }
instance [semiring α] : has_scalar α (matrix m n α) := pi.has_scalar
instance [ring α] : module α (matrix m n α) := pi.module _
@[simp] lemma smul_val [semiring α] (a : α) (A : matrix m n α) (i : m) (j : n) : (a • A) i j = a * A i j := rfl
section comm_ring
variables [comm_ring α]
@[simp] lemma mul_smul (M : matrix m n α) (a : α) (N : matrix n l α) : M ⬝ (a • N) = a • M ⬝ N :=
begin
ext i j,
unfold matrix.mul has_scalar.smul,
rw finset.mul_sum,
congr,
ext,
ac_refl
end
@[simp] lemma smul_mul (M : matrix m n α) (a : α) (N : matrix n l α) : (a • M) ⬝ N = a • M ⬝ N :=
begin
ext i j,
unfold matrix.mul has_scalar.smul,
rw finset.mul_sum,
congr,
ext,
ac_refl
end
end comm_ring
section semiring
variables [semiring α]
def vec_mul_vec (w : m → α) (v : n → α) : matrix m n α
| x y := w x * v y
def mul_vec (M : matrix m n α) (v : n → α) : m → α
| x := finset.univ.sum (λy:n, M x y * v y)
def vec_mul (v : m → α) (M : matrix m n α) : n → α
| y := finset.univ.sum (λx:m, v x * M x y)
instance mul_vec.is_add_monoid_hom_left (v : n → α) :
is_add_monoid_hom (λM:matrix m n α, mul_vec M v) :=
{ map_zero := by ext; simp [mul_vec]; refl,
map_add :=
begin
intros x y,
ext m,
rw pi.add_apply (mul_vec x v) (mul_vec y v) m,
simp [mul_vec, finset.sum_add_distrib, right_distrib]
end }
lemma mul_vec_diagonal [decidable_eq m] (v w : m → α) (x : m) :
mul_vec (diagonal v) w x = v x * w x :=
begin
transitivity,
refine finset.sum_eq_single x _ _,
{ assume b _ ne, simp [diagonal, ne.symm] },
{ simp },
{ rw [diagonal_val_eq] }
end
lemma vec_mul_vec_eq (w : m → α) (v : n → α) :
vec_mul_vec w v = (col w) ⬝ (row v) :=
by simp [matrix.mul]; refl
end semiring
section transpose
local postfix `ᵀ` : 1500 := transpose
lemma transpose_transpose (M : matrix m n α) :
Mᵀᵀ = M :=
by ext; refl
@[simp] lemma transpose_zero [has_zero α] : (0 : matrix m n α)ᵀ = 0 :=
by ext i j; refl
@[simp] lemma transpose_add [has_add α] (M : matrix m n α) (N : matrix m n α) :
(M + N)ᵀ = Mᵀ + Nᵀ :=
begin
ext i j,
dsimp [transpose],
refl
end
@[simp] lemma transpose_mul [comm_ring α] (M : matrix m n α) (N : matrix n l α) :
(M ⬝ N)ᵀ = Nᵀ ⬝ Mᵀ :=
begin
ext i j,
unfold matrix.mul transpose,
congr,
ext,
ac_refl
end
@[simp] lemma transpose_neg [comm_ring α] (M : matrix m n α) :
(- M)ᵀ = - Mᵀ :=
by ext i j; refl
end transpose
def minor (A : matrix m n α) (row : l → m) (col : o → n) : matrix l o α :=
λ i j, A (row i) (col j)
@[reducible]
def sub_left {m l r : nat} (A : matrix (fin m) (fin (l + r)) α) : matrix (fin m) (fin l) α :=
minor A id (fin.cast_add r)
@[reducible]
def sub_right {m l r : nat} (A : matrix (fin m) (fin (l + r)) α) : matrix (fin m) (fin r) α :=
minor A id (fin.nat_add l)
@[reducible]
def sub_up {d u n : nat} (A : matrix (fin (u + d)) (fin n) α) : matrix (fin u) (fin n) α :=
minor A (fin.cast_add d) id
@[reducible]
def sub_down {d u n : nat} (A : matrix (fin (u + d)) (fin n) α) : matrix (fin d) (fin n) α :=
minor A (fin.nat_add u) id
@[reducible]
def sub_up_right {d u l r : nat} (A: matrix (fin (u + d)) (fin (l + r)) α) :
matrix (fin u) (fin r) α :=
sub_up (sub_right A)
@[reducible]
def sub_down_right {d u l r : nat} (A : matrix (fin (u + d)) (fin (l + r)) α) :
matrix (fin d) (fin r) α :=
sub_down (sub_right A)
@[reducible]
def sub_up_left {d u l r : nat} (A : matrix (fin (u + d)) (fin (l + r)) α) :
matrix (fin u) (fin (l)) α :=
sub_up (sub_left A)
@[reducible]
def sub_down_left {d u l r : nat} (A: matrix (fin (u + d)) (fin (l + r)) α) :
matrix (fin d) (fin (l)) α :=
sub_down (sub_left A)
end matrix
|
754ac194c4ef5aa6cd7357a27fa94010bb897591 | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/data/equiv/basic.lean | 65ec1f7db147b975948777dade4d9150c51970f8 | [
"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 | 79,010 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Mario Carneiro
-/
import data.set.function
import algebra.group.basic
/-!
# Equivalence between types
In this file we define two types:
* `equiv α β` a.k.a. `α ≃ β`: a bijective map `α → β` bundled with its inverse map; we use this (and
not equality!) to express that various `Type`s or `Sort`s are equivalent.
* `equiv.perm α`: the group of permutations `α ≃ α`.
Then we define
* canonical isomorphisms between various types: e.g.,
- `equiv.refl α` is the identity map interpreted as `α ≃ α`;
- `equiv.sum_equiv_sigma_bool` is the canonical equivalence between the sum of two types `α ⊕ β`
and the sigma-type `Σ b : bool, cond b α β`;
- `equiv.prod_sum_distrib : α × (β ⊕ γ) ≃ (α × β) ⊕ (α × γ)` shows that type product and type sum
satisfy the distributive law up to a canonical equivalence;
* operations on equivalences: e.g.,
- `equiv.symm e : β ≃ α` is the inverse of `e : α ≃ β`;
- `equiv.trans e₁ e₂ : α ≃ γ` is the composition of `e₁ : α ≃ β` and `e₂ : β ≃ γ` (note the order
of the arguments!);
- `equiv.prod_congr ea eb : α₁ × β₁ ≃ α₂ × β₂`: combine two equivalences `ea : α₁ ≃ α₂` and
`eb : β₁ ≃ β₂` using `prod.map`.
* definitions that transfer some instances along an equivalence. By convention, we transfer
instances from right to left.
- `equiv.inhabited` takes `e : α ≃ β` and `[inhabited β]` and returns `inhabited α`;
- `equiv.unique` takes `e : α ≃ β` and `[unique β]` and returns `unique α`;
- `equiv.decidable_eq` takes `e : α ≃ β` and `[decidable_eq β]` and returns `decidable_eq α`.
More definitions of this kind can be found in other files. E.g., `data/equiv/transfer_instance`
does it for many algebraic type classes like `group`, `module`, etc.
* group structure on `equiv.perm α`. More lemmas about `equiv.perm` can be found in
`data/equiv/perm`.
## Tags
equivalence, congruence, bijective map
-/
open function
universes u v w z
variables {α : Sort u} {β : Sort v} {γ : Sort w}
/-- `α ≃ β` is the type of functions from `α → β` with a two-sided inverse. -/
@[nolint has_inhabited_instance]
structure equiv (α : Sort*) (β : Sort*) :=
(to_fun : α → β)
(inv_fun : β → α)
(left_inv : left_inverse inv_fun to_fun)
(right_inv : right_inverse inv_fun to_fun)
infix ` ≃ `:25 := equiv
/-- Convert an involutive function `f` to an equivalence with `to_fun = inv_fun = f`. -/
def function.involutive.to_equiv (f : α → α) (h : involutive f) : α ≃ α :=
⟨f, f, h.left_inverse, h.right_inverse⟩
namespace equiv
/-- `perm α` is the type of bijections from `α` to itself. -/
@[reducible] def perm (α : Sort*) := equiv α α
instance : has_coe_to_fun (α ≃ β) :=
⟨_, to_fun⟩
@[simp] theorem coe_fn_mk (f : α → β) (g l r) : (equiv.mk f g l r : α → β) = f :=
rfl
/-- The map `coe_fn : (r ≃ s) → (r → s)` is injective. -/
theorem injective_coe_fn : function.injective (λ (e : α ≃ β) (x : α), e x)
| ⟨f₁, g₁, l₁, r₁⟩ ⟨f₂, g₂, l₂, r₂⟩ h :=
have f₁ = f₂, from h,
have g₁ = g₂, from l₁.eq_right_inverse (this.symm ▸ r₂),
by simp *
@[simp, norm_cast] protected lemma coe_inj {e₁ e₂ : α ≃ β} : ⇑e₁ = e₂ ↔ e₁ = e₂ :=
injective_coe_fn.eq_iff
@[ext] lemma ext {f g : equiv α β} (H : ∀ x, f x = g x) : f = g :=
injective_coe_fn (funext H)
@[ext] lemma perm.ext {σ τ : equiv.perm α} (H : ∀ x, σ x = τ x) : σ = τ :=
equiv.ext H
lemma ext_iff {f g : equiv α β} : f = g ↔ ∀ x, f x = g x :=
⟨λ h x, h ▸ rfl, ext⟩
lemma perm.ext_iff {σ τ : equiv.perm α} : σ = τ ↔ ∀ x, σ x = τ x :=
ext_iff
/-- Any type is equivalent to itself. -/
@[refl] protected def refl (α : Sort*) : α ≃ α := ⟨id, id, λ x, rfl, λ x, rfl⟩
instance inhabited' : inhabited (α ≃ α) := ⟨equiv.refl α⟩
/-- Inverse of an equivalence `e : α ≃ β`. -/
@[symm] protected def symm (e : α ≃ β) : β ≃ α := ⟨e.inv_fun, e.to_fun, e.right_inv, e.left_inv⟩
/-- See Note [custom simps projection] -/
def simps.inv_fun (e : α ≃ β) : β → α := e.symm
initialize_simps_projections equiv (to_fun → apply, inv_fun → symm_apply)
/-- Composition of equivalences `e₁ : α ≃ β` and `e₂ : β ≃ γ`. -/
@[trans] protected def trans (e₁ : α ≃ β) (e₂ : β ≃ γ) : α ≃ γ :=
⟨e₂ ∘ e₁, e₁.symm ∘ e₂.symm,
e₂.left_inv.comp e₁.left_inv, e₂.right_inv.comp e₁.right_inv⟩
@[simp]
lemma to_fun_as_coe (e : α ≃ β) : e.to_fun = e := rfl
@[simp]
lemma inv_fun_as_coe (e : α ≃ β) : e.inv_fun = e.symm := rfl
protected theorem injective (e : α ≃ β) : injective e :=
e.left_inv.injective
protected theorem surjective (e : α ≃ β) : surjective e :=
e.right_inv.surjective
protected theorem bijective (f : α ≃ β) : bijective f :=
⟨f.injective, f.surjective⟩
@[simp] lemma range_eq_univ {α : Type*} {β : Type*} (e : α ≃ β) : set.range e = set.univ :=
set.eq_univ_of_forall e.surjective
protected theorem subsingleton (e : α ≃ β) [subsingleton β] : subsingleton α :=
e.injective.subsingleton
/-- Transfer `decidable_eq` across an equivalence. -/
protected def decidable_eq (e : α ≃ β) [decidable_eq β] : decidable_eq α :=
e.injective.decidable_eq
lemma nonempty_iff_nonempty (e : α ≃ β) : nonempty α ↔ nonempty β :=
nonempty.congr e e.symm
/-- If `α ≃ β` and `β` is inhabited, then so is `α`. -/
protected def inhabited [inhabited β] (e : α ≃ β) : inhabited α :=
⟨e.symm (default _)⟩
/-- If `α ≃ β` and `β` is a singleton type, then so is `α`. -/
protected def unique [unique β] (e : α ≃ β) : unique α :=
e.symm.surjective.unique
/-- Equivalence between equal types. -/
protected def cast {α β : Sort*} (h : α = β) : α ≃ β :=
⟨cast h, cast h.symm, λ x, by { cases h, refl }, λ x, by { cases h, refl }⟩
@[simp] theorem coe_fn_symm_mk (f : α → β) (g l r) : ((equiv.mk f g l r).symm : β → α) = g :=
rfl
@[simp] theorem coe_refl : ⇑(equiv.refl α) = id := rfl
theorem refl_apply (x : α) : equiv.refl α x = x := rfl
@[simp] theorem coe_trans (f : α ≃ β) (g : β ≃ γ) : ⇑(f.trans g) = g ∘ f := rfl
theorem trans_apply (f : α ≃ β) (g : β ≃ γ) (a : α) : (f.trans g) a = g (f a) := rfl
@[simp] theorem apply_symm_apply (e : α ≃ β) (x : β) : e (e.symm x) = x :=
e.right_inv x
@[simp] theorem symm_apply_apply (e : α ≃ β) (x : α) : e.symm (e x) = x :=
e.left_inv x
@[simp] theorem symm_comp_self (e : α ≃ β) : e.symm ∘ e = id := funext e.symm_apply_apply
@[simp] theorem self_comp_symm (e : α ≃ β) : e ∘ e.symm = id := funext e.apply_symm_apply
@[simp] lemma symm_trans_apply (f : α ≃ β) (g : β ≃ γ) (a : γ) :
(f.trans g).symm a = f.symm (g.symm a) := rfl
@[simp] theorem apply_eq_iff_eq (f : α ≃ β) {x y : α} : f x = f y ↔ x = y :=
f.injective.eq_iff
theorem apply_eq_iff_eq_symm_apply {α β : Sort*} (f : α ≃ β) {x : α} {y : β} :
f x = y ↔ x = f.symm y :=
begin
conv_lhs { rw ←apply_symm_apply f y, },
rw apply_eq_iff_eq,
end
@[simp] theorem cast_apply {α β} (h : α = β) (x : α) : equiv.cast h x = cast h x := rfl
lemma symm_apply_eq {α β} (e : α ≃ β) {x y} : e.symm x = y ↔ x = e y :=
⟨λ H, by simp [H.symm], λ H, by simp [H]⟩
lemma eq_symm_apply {α β} (e : α ≃ β) {x y} : y = e.symm x ↔ e y = x :=
(eq_comm.trans e.symm_apply_eq).trans eq_comm
@[simp] theorem symm_symm (e : α ≃ β) : e.symm.symm = e := by { cases e, refl }
@[simp] theorem trans_refl (e : α ≃ β) : e.trans (equiv.refl β) = e := by { cases e, refl }
@[simp] theorem refl_symm : (equiv.refl α).symm = equiv.refl α := rfl
@[simp] theorem refl_trans (e : α ≃ β) : (equiv.refl α).trans e = e := by { cases e, refl }
@[simp] theorem symm_trans (e : α ≃ β) : e.symm.trans e = equiv.refl β := ext (by simp)
@[simp] theorem trans_symm (e : α ≃ β) : e.trans e.symm = equiv.refl α := ext (by simp)
lemma trans_assoc {δ} (ab : α ≃ β) (bc : β ≃ γ) (cd : γ ≃ δ) :
(ab.trans bc).trans cd = ab.trans (bc.trans cd) :=
equiv.ext $ assume a, rfl
theorem left_inverse_symm (f : equiv α β) : left_inverse f.symm f := f.left_inv
theorem right_inverse_symm (f : equiv α β) : function.right_inverse f.symm f := f.right_inv
/-- If `α` is equivalent to `β` and `γ` is equivalent to `δ`, then the type of equivalences `α ≃ γ`
is equivalent to the type of equivalences `β ≃ δ`. -/
def equiv_congr {δ} (ab : α ≃ β) (cd : γ ≃ δ) : (α ≃ γ) ≃ (β ≃ δ) :=
⟨ λac, (ab.symm.trans ac).trans cd, λbd, ab.trans $ bd.trans $ cd.symm,
assume ac, by { ext x, simp }, assume ac, by { ext x, simp } ⟩
/-- If `α` is equivalent to `β`, then `perm α` is equivalent to `perm β`. -/
def perm_congr {α : Type*} {β : Type*} (e : α ≃ β) : perm α ≃ perm β :=
equiv_congr e e
protected lemma image_eq_preimage {α β} (e : α ≃ β) (s : set α) : e '' s = e.symm ⁻¹' s :=
set.ext $ assume x, set.mem_image_iff_of_inverse e.left_inv e.right_inv
protected lemma subset_image {α β} (e : α ≃ β) (s : set α) (t : set β) :
t ⊆ e '' s ↔ e.symm '' t ⊆ s :=
by rw [set.image_subset_iff, e.image_eq_preimage]
lemma symm_image_image {α β} (f : equiv α β) (s : set α) : f.symm '' (f '' s) = s :=
by { rw [← set.image_comp], simp }
protected lemma image_compl {α β} (f : equiv α β) (s : set α) :
f '' sᶜ = (f '' s)ᶜ :=
set.image_compl_eq f.bijective
/-!
### The group of permutations (self-equivalences) of a type `α`
-/
namespace perm
instance perm_group {α : Type u} : group (perm α) :=
begin
refine { mul := λ f g, equiv.trans g f, one := equiv.refl α, inv:= equiv.symm, ..};
intros; apply equiv.ext; try { apply trans_apply },
apply symm_apply_apply
end
theorem mul_apply {α : Type u} (f g : perm α) (x) : (f * g) x = f (g x) :=
equiv.trans_apply _ _ _
@[simp] theorem one_apply {α : Type u} (x) : (1 : perm α) x = x := rfl
@[simp] lemma inv_apply_self {α : Type u} (f : perm α) (x) :
f⁻¹ (f x) = x := equiv.symm_apply_apply _ _
@[simp] lemma apply_inv_self {α : Type u} (f : perm α) (x) :
f (f⁻¹ x) = x := equiv.apply_symm_apply _ _
lemma one_def {α : Type u} : (1 : perm α) = equiv.refl α := rfl
lemma mul_def {α : Type u} (f g : perm α) : f * g = g.trans f := rfl
lemma inv_def {α : Type u} (f : perm α) : f⁻¹ = f.symm := rfl
@[simp] lemma coe_mul {α : Type u} (f g : perm α) : ⇑(f * g) = f ∘ g := rfl
end perm
/-- If `α` is an empty type, then it is equivalent to the `empty` type. -/
def equiv_empty (h : α → false) : α ≃ empty :=
⟨λ x, (h x).elim, λ e, e.rec _, λ x, (h x).elim, λ e, e.rec _⟩
/-- `false` is equivalent to `empty`. -/
def false_equiv_empty : false ≃ empty :=
equiv_empty _root_.id
/-- If `α` is an empty type, then it is equivalent to the `pempty` type in any universe. -/
def {u' v'} equiv_pempty {α : Sort v'} (h : α → false) : α ≃ pempty.{u'} :=
⟨λ x, (h x).elim, λ e, e.rec _, λ x, (h x).elim, λ e, e.rec _⟩
/-- `false` is equivalent to `pempty`. -/
def false_equiv_pempty : false ≃ pempty :=
equiv_pempty _root_.id
/-- `empty` is equivalent to `pempty`. -/
def empty_equiv_pempty : empty ≃ pempty :=
equiv_pempty $ empty.rec _
/-- `pempty` types from any two universes are equivalent. -/
def pempty_equiv_pempty : pempty.{v} ≃ pempty.{w} :=
equiv_pempty pempty.elim
/-- If `α` is not `nonempty`, then it is equivalent to `empty`. -/
def empty_of_not_nonempty {α : Sort*} (h : ¬ nonempty α) : α ≃ empty :=
equiv_empty $ assume a, h ⟨a⟩
/-- If `α` is not `nonempty`, then it is equivalent to `pempty`. -/
def pempty_of_not_nonempty {α : Sort*} (h : ¬ nonempty α) : α ≃ pempty :=
equiv_pempty $ assume a, h ⟨a⟩
/-- The `Sort` of proofs of a true proposition is equivalent to `punit`. -/
def prop_equiv_punit {p : Prop} (h : p) : p ≃ punit :=
⟨λ x, (), λ x, h, λ _, rfl, λ ⟨⟩, rfl⟩
/-- `true` is equivalent to `punit`. -/
def true_equiv_punit : true ≃ punit := prop_equiv_punit trivial
/-- `ulift α` is equivalent to `α`. -/
@[simps apply symm_apply {fully_applied := ff}]
protected def ulift {α : Type v} : ulift.{u} α ≃ α :=
⟨ulift.down, ulift.up, ulift.up_down, λ a, rfl⟩
/-- `plift α` is equivalent to `α`. -/
@[simps apply symm_apply {fully_applied := ff}]
protected def plift : plift α ≃ α :=
⟨plift.down, plift.up, plift.up_down, plift.down_up⟩
/-- equivalence of propositions is the same as iff -/
def of_iff {P Q : Prop} (h : P ↔ Q) : P ≃ Q :=
{ to_fun := h.mp,
inv_fun := h.mpr,
left_inv := λ x, rfl,
right_inv := λ y, rfl }
/-- If `α₁` is equivalent to `α₂` and `β₁` is equivalent to `β₂`, then the type of maps `α₁ → β₁`
is equivalent to the type of maps `α₂ → β₂`. -/
@[congr, simps apply] def arrow_congr {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) :
(α₁ → β₁) ≃ (α₂ → β₂) :=
{ to_fun := λ f, e₂ ∘ f ∘ e₁.symm,
inv_fun := λ f, e₂.symm ∘ f ∘ e₁,
left_inv := λ f, funext $ λ x, by simp,
right_inv := λ f, funext $ λ x, by simp }
lemma arrow_congr_comp {α₁ β₁ γ₁ α₂ β₂ γ₂ : Sort*}
(ea : α₁ ≃ α₂) (eb : β₁ ≃ β₂) (ec : γ₁ ≃ γ₂) (f : α₁ → β₁) (g : β₁ → γ₁) :
arrow_congr ea ec (g ∘ f) = (arrow_congr eb ec g) ∘ (arrow_congr ea eb f) :=
by { ext, simp only [comp, arrow_congr_apply, eb.symm_apply_apply] }
@[simp] lemma arrow_congr_refl {α β : Sort*} :
arrow_congr (equiv.refl α) (equiv.refl β) = equiv.refl (α → β) := rfl
@[simp] lemma arrow_congr_trans {α₁ β₁ α₂ β₂ α₃ β₃ : Sort*}
(e₁ : α₁ ≃ α₂) (e₁' : β₁ ≃ β₂) (e₂ : α₂ ≃ α₃) (e₂' : β₂ ≃ β₃) :
arrow_congr (e₁.trans e₂) (e₁'.trans e₂') = (arrow_congr e₁ e₁').trans (arrow_congr e₂ e₂') :=
rfl
@[simp] lemma arrow_congr_symm {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) :
(arrow_congr e₁ e₂).symm = arrow_congr e₁.symm e₂.symm :=
rfl
/--
A version of `equiv.arrow_congr` in `Type`, rather than `Sort`.
The `equiv_rw` tactic is not able to use the default `Sort` level `equiv.arrow_congr`,
because Lean's universe rules will not unify `?l_1` with `imax (1 ?m_1)`.
-/
@[congr, simps apply {rhs_md := semireducible, simp_rhs := tt}]
def arrow_congr' {α₁ β₁ α₂ β₂ : Type*} (hα : α₁ ≃ α₂) (hβ : β₁ ≃ β₂) : (α₁ → β₁) ≃ (α₂ → β₂) :=
equiv.arrow_congr hα hβ
@[simp] lemma arrow_congr'_refl {α β : Type*} :
arrow_congr' (equiv.refl α) (equiv.refl β) = equiv.refl (α → β) := rfl
@[simp] lemma arrow_congr'_trans {α₁ β₁ α₂ β₂ α₃ β₃ : Type*}
(e₁ : α₁ ≃ α₂) (e₁' : β₁ ≃ β₂) (e₂ : α₂ ≃ α₃) (e₂' : β₂ ≃ β₃) :
arrow_congr' (e₁.trans e₂) (e₁'.trans e₂') = (arrow_congr' e₁ e₁').trans (arrow_congr' e₂ e₂') :=
rfl
@[simp] lemma arrow_congr'_symm {α₁ β₁ α₂ β₂ : Type*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) :
(arrow_congr' e₁ e₂).symm = arrow_congr' e₁.symm e₂.symm :=
rfl
/-- Conjugate a map `f : α → α` by an equivalence `α ≃ β`. -/
@[simps apply {rhs_md := semireducible, simp_rhs := tt}]
def conj (e : α ≃ β) : (α → α) ≃ (β → β) := arrow_congr e e
@[simp] lemma conj_refl : conj (equiv.refl α) = equiv.refl (α → α) := rfl
@[simp] lemma conj_symm (e : α ≃ β) : e.conj.symm = e.symm.conj := rfl
@[simp] lemma conj_trans (e₁ : α ≃ β) (e₂ : β ≃ γ) :
(e₁.trans e₂).conj = e₁.conj.trans e₂.conj :=
rfl
-- This should not be a simp lemma as long as `(∘)` is reducible:
-- when `(∘)` is reducible, Lean can unify `f₁ ∘ f₂` with any `g` using
-- `f₁ := g` and `f₂ := λ x, x`. This causes nontermination.
lemma conj_comp (e : α ≃ β) (f₁ f₂ : α → α) :
e.conj (f₁ ∘ f₂) = (e.conj f₁) ∘ (e.conj f₂) :=
by apply arrow_congr_comp
section binary_op
variables {α₁ β₁ : Type*} (e : α₁ ≃ β₁) (f : α₁ → α₁ → α₁)
lemma semiconj_conj (f : α₁ → α₁) : semiconj e f (e.conj f) := λ x, by simp
lemma semiconj₂_conj : semiconj₂ e f (e.arrow_congr e.conj f) := λ x y, by simp
instance [is_associative α₁ f] :
is_associative β₁ (e.arrow_congr (e.arrow_congr e) f) :=
(e.semiconj₂_conj f).is_associative_right e.surjective
instance [is_idempotent α₁ f] :
is_idempotent β₁ (e.arrow_congr (e.arrow_congr e) f) :=
(e.semiconj₂_conj f).is_idempotent_right e.surjective
instance [is_left_cancel α₁ f] :
is_left_cancel β₁ (e.arrow_congr (e.arrow_congr e) f) :=
⟨e.surjective.forall₃.2 $ λ x y z, by simpa using @is_left_cancel.left_cancel _ f _ x y z⟩
instance [is_right_cancel α₁ f] :
is_right_cancel β₁ (e.arrow_congr (e.arrow_congr e) f) :=
⟨e.surjective.forall₃.2 $ λ x y z, by simpa using @is_right_cancel.right_cancel _ f _ x y z⟩
end binary_op
/-- `punit` sorts in any two universes are equivalent. -/
def punit_equiv_punit : punit.{v} ≃ punit.{w} :=
⟨λ _, punit.star, λ _, punit.star, λ u, by { cases u, refl }, λ u, by { cases u, reflexivity }⟩
section
/-- The sort of maps to `punit.{v}` is equivalent to `punit.{w}`. -/
def arrow_punit_equiv_punit (α : Sort*) : (α → punit.{v}) ≃ punit.{w} :=
⟨λ f, punit.star, λ u f, punit.star,
λ f, by { funext x, cases f x, refl }, λ u, by { cases u, reflexivity }⟩
/-- The sort of maps from `punit` is equivalent to the codomain. -/
def punit_arrow_equiv (α : Sort*) : (punit.{u} → α) ≃ α :=
⟨λ f, f punit.star, λ a u, a, λ f, by { ext ⟨⟩, refl }, λ u, rfl⟩
/-- The sort of maps from `empty` is equivalent to `punit`. -/
def empty_arrow_equiv_punit (α : Sort*) : (empty → α) ≃ punit.{u} :=
⟨λ f, punit.star, λ u e, e.rec _, λ f, funext $ λ x, x.rec _, λ u, by { cases u, refl }⟩
/-- The sort of maps from `pempty` is equivalent to `punit`. -/
def pempty_arrow_equiv_punit (α : Sort*) : (pempty → α) ≃ punit.{u} :=
⟨λ f, punit.star, λ u e, e.rec _, λ f, funext $ λ x, x.rec _, λ u, by { cases u, refl }⟩
/-- The sort of maps from `false` is equivalent to `punit`. -/
def false_arrow_equiv_punit (α : Sort*) : (false → α) ≃ punit.{u} :=
calc (false → α) ≃ (empty → α) : arrow_congr false_equiv_empty (equiv.refl _)
... ≃ punit : empty_arrow_equiv_punit _
end
/-- Product of two equivalences. If `α₁ ≃ α₂` and `β₁ ≃ β₂`, then `α₁ × β₁ ≃ α₂ × β₂`. -/
@[congr, simps apply]
def prod_congr {α₁ β₁ α₂ β₂ : Type*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) : α₁ × β₁ ≃ α₂ × β₂ :=
⟨prod.map e₁ e₂, prod.map e₁.symm e₂.symm, λ ⟨a, b⟩, by simp, λ ⟨a, b⟩, by simp⟩
@[simp] theorem prod_congr_symm {α₁ β₁ α₂ β₂ : Type*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) :
(prod_congr e₁ e₂).symm = prod_congr e₁.symm e₂.symm :=
rfl
/-- Type product is commutative up to an equivalence: `α × β ≃ β × α`. -/
@[simps apply] def prod_comm (α β : Type*) : α × β ≃ β × α :=
⟨prod.swap, prod.swap, λ⟨a, b⟩, rfl, λ⟨a, b⟩, rfl⟩
@[simp] lemma prod_comm_symm (α β) : (prod_comm α β).symm = prod_comm β α := rfl
/-- Type product is associative up to an equivalence. -/
@[simps] def prod_assoc (α β γ : Sort*) : (α × β) × γ ≃ α × (β × γ) :=
⟨λ p, (p.1.1, p.1.2, p.2), λp, ((p.1, p.2.1), p.2.2), λ ⟨⟨a, b⟩, c⟩, rfl, λ ⟨a, ⟨b, c⟩⟩, rfl⟩
lemma prod_assoc_preimage {α β γ} {s : set α} {t : set β} {u : set γ} :
equiv.prod_assoc α β γ ⁻¹' s.prod (t.prod u) = (s.prod t).prod u :=
by { ext, simp [and_assoc] }
section
/-- `punit` is a right identity for type product up to an equivalence. -/
@[simps apply] def prod_punit (α : Type*) : α × punit.{u+1} ≃ α :=
⟨λ p, p.1, λ a, (a, punit.star), λ ⟨_, punit.star⟩, rfl, λ a, rfl⟩
/-- `punit` is a left identity for type product up to an equivalence. -/
@[simps apply {rhs_md := semireducible, simp_rhs := tt}]
def punit_prod (α : Type*) : punit.{u+1} × α ≃ α :=
calc punit × α ≃ α × punit : prod_comm _ _
... ≃ α : prod_punit _
/-- `empty` type is a right absorbing element for type product up to an equivalence. -/
def prod_empty (α : Type*) : α × empty ≃ empty :=
equiv_empty (λ ⟨_, e⟩, e.rec _)
/-- `empty` type is a left absorbing element for type product up to an equivalence. -/
def empty_prod (α : Type*) : empty × α ≃ empty :=
equiv_empty (λ ⟨e, _⟩, e.rec _)
/-- `pempty` type is a right absorbing element for type product up to an equivalence. -/
def prod_pempty (α : Type*) : α × pempty ≃ pempty :=
equiv_pempty (λ ⟨_, e⟩, e.rec _)
/-- `pempty` type is a left absorbing element for type product up to an equivalence. -/
def pempty_prod (α : Type*) : pempty × α ≃ pempty :=
equiv_pempty (λ ⟨e, _⟩, e.rec _)
end
section
open sum
/-- `psum` is equivalent to `sum`. -/
def psum_equiv_sum (α β : Type*) : psum α β ≃ α ⊕ β :=
⟨λ s, psum.cases_on s inl inr,
λ s, sum.cases_on s psum.inl psum.inr,
λ s, by cases s; refl,
λ s, by cases s; refl⟩
/-- If `α ≃ α'` and `β ≃ β'`, then `α ⊕ β ≃ α' ⊕ β'`. -/
@[simps apply]
def sum_congr {α₁ β₁ α₂ β₂ : Type*} (ea : α₁ ≃ α₂) (eb : β₁ ≃ β₂) : α₁ ⊕ β₁ ≃ α₂ ⊕ β₂ :=
⟨sum.map ea eb, sum.map ea.symm eb.symm, λ x, by simp, λ x, by simp⟩
@[simp] lemma sum_congr_symm {α β γ δ : Type u} (e : α ≃ β) (f : γ ≃ δ) :
(equiv.sum_congr e f).symm = (equiv.sum_congr (e.symm) (f.symm)) :=
rfl
/-- `bool` is equivalent the sum of two `punit`s. -/
def bool_equiv_punit_sum_punit : bool ≃ punit.{u+1} ⊕ punit.{v+1} :=
⟨λ b, cond b (inr punit.star) (inl punit.star),
λ s, sum.rec_on s (λ_, ff) (λ_, tt),
λ b, by cases b; refl,
λ s, by rcases s with ⟨⟨⟩⟩ | ⟨⟨⟩⟩; refl⟩
/-- `Prop` is noncomputably equivalent to `bool`. -/
noncomputable def Prop_equiv_bool : Prop ≃ bool :=
⟨λ p, @to_bool p (classical.prop_decidable _),
λ b, b, λ p, by simp, λ b, by simp⟩
/-- Sum of types is commutative up to an equivalence. -/
@[simps apply]
def sum_comm (α β : Sort*) : α ⊕ β ≃ β ⊕ α :=
⟨sum.swap, sum.swap, sum.swap_swap, sum.swap_swap⟩
@[simp] lemma sum_comm_symm (α β) : (sum_comm α β).symm = sum_comm β α := rfl
/-- Sum of types is associative up to an equivalence. -/
def sum_assoc (α β γ : Sort*) : (α ⊕ β) ⊕ γ ≃ α ⊕ (β ⊕ γ) :=
⟨sum.elim (sum.elim sum.inl (sum.inr ∘ sum.inl)) (sum.inr ∘ sum.inr),
sum.elim (sum.inl ∘ sum.inl) $ sum.elim (sum.inl ∘ sum.inr) sum.inr,
by rintros (⟨_ | _⟩ | _); refl,
by rintros (_ | ⟨_ | _⟩); refl⟩
@[simp] theorem sum_assoc_apply_in1 {α β γ} (a) : sum_assoc α β γ (inl (inl a)) = inl a := rfl
@[simp] theorem sum_assoc_apply_in2 {α β γ} (b) : sum_assoc α β γ (inl (inr b)) = inr (inl b) := rfl
@[simp] theorem sum_assoc_apply_in3 {α β γ} (c) : sum_assoc α β γ (inr c) = inr (inr c) := rfl
/-- Sum with `empty` is equivalent to the original type. -/
def sum_empty (α : Type*) : α ⊕ empty ≃ α :=
⟨sum.elim id (empty.rec _),
inl,
λ s, by { rcases s with _ | ⟨⟨⟩⟩, refl },
λ a, rfl⟩
@[simp] lemma sum_empty_apply_inl {α} (a) : sum_empty α (sum.inl a) = a := rfl
/-- The sum of `empty` with any `Sort*` is equivalent to the right summand. -/
def empty_sum (α : Sort*) : empty ⊕ α ≃ α :=
(sum_comm _ _).trans $ sum_empty _
@[simp] lemma empty_sum_apply_inr {α} (a) : empty_sum α (sum.inr a) = a := rfl
/-- Sum with `pempty` is equivalent to the original type. -/
def sum_pempty (α : Type*) : α ⊕ pempty ≃ α :=
⟨sum.elim id (pempty.rec _),
inl,
λ s, by { rcases s with _ | ⟨⟨⟩⟩, refl },
λ a, rfl⟩
@[simp] lemma sum_pempty_apply_inl {α} (a) : sum_pempty α (sum.inl a) = a := rfl
/-- The sum of `pempty` with any `Sort*` is equivalent to the right summand. -/
def pempty_sum (α : Sort*) : pempty ⊕ α ≃ α :=
(sum_comm _ _).trans $ sum_pempty _
@[simp] lemma pempty_sum_apply_inr {α} (a) : pempty_sum α (sum.inr a) = a := rfl
/-- `option α` is equivalent to `α ⊕ punit` -/
def option_equiv_sum_punit (α : Type*) : option α ≃ α ⊕ punit.{u+1} :=
⟨λ o, match o with none := inr punit.star | some a := inl a end,
λ s, match s with inr _ := none | inl a := some a end,
λ o, by cases o; refl,
λ s, by rcases s with _ | ⟨⟨⟩⟩; refl⟩
@[simp] lemma option_equiv_sum_punit_none {α} :
option_equiv_sum_punit α none = sum.inr punit.star := rfl
@[simp] lemma option_equiv_sum_punit_some {α} (a) :
option_equiv_sum_punit α (some a) = sum.inl a := rfl
@[simp] lemma option_equiv_sum_punit_coe {α} (a : α) :
option_equiv_sum_punit α a = sum.inl a := rfl
@[simp] lemma option_equiv_sum_punit_symm_inl {α} (a) :
(option_equiv_sum_punit α).symm (sum.inl a) = a :=
rfl
@[simp] lemma option_equiv_sum_punit_symm_inr {α} (a) :
(option_equiv_sum_punit α).symm (sum.inr a) = none :=
rfl
/-- The set of `x : option α` such that `is_some x` is equivalent to `α`. -/
def option_is_some_equiv (α : Type*) : {x : option α // x.is_some} ≃ α :=
{ to_fun := λ o, option.get o.2,
inv_fun := λ x, ⟨some x, dec_trivial⟩,
left_inv := λ o, subtype.eq $ option.some_get _,
right_inv := λ x, option.get_some _ _ }
/-- `α ⊕ β` is equivalent to a `sigma`-type over `bool`. -/
def sum_equiv_sigma_bool (α β : Sort*) : α ⊕ β ≃ (Σ b: bool, cond b α β) :=
⟨λ s, match s with inl a := ⟨tt, a⟩ | inr b := ⟨ff, b⟩ end,
λ s, match s with ⟨tt, a⟩ := inl a | ⟨ff, b⟩ := inr b end,
λ s, by cases s; refl,
λ s, by rcases s with ⟨_|_, _⟩; refl⟩
/-- `sigma_preimage_equiv f` for `f : α → β` is the natural equivalence between
the type of all fibres of `f` and the total space `α`. -/
@[simps]
def sigma_preimage_equiv {α β : Type*} (f : α → β) :
(Σ y : β, {x // f x = y}) ≃ α :=
⟨λ x, ↑x.2, λ x, ⟨f x, x, rfl⟩, λ ⟨y, x, rfl⟩, rfl, λ x, rfl⟩
/-- A set `s` in `α × β` is equivalent to the sigma-type `Σ x, {y | (x, y) ∈ s}`. -/
def set_prod_equiv_sigma {α β : Type*} (s : set (α × β)) :
s ≃ Σ x : α, {y | (x, y) ∈ s} :=
{ to_fun := λ x, ⟨x.1.1, x.1.2, by simp⟩,
inv_fun := λ x, ⟨(x.1, x.2.1), x.2.2⟩,
left_inv := λ ⟨⟨x, y⟩, h⟩, rfl,
right_inv := λ ⟨x, y, h⟩, rfl }
end
section sum_compl
/-- For any predicate `p` on `α`,
the sum of the two subtypes `{a // p a}` and its complement `{a // ¬ p a}`
is naturally equivalent to `α`. -/
def sum_compl {α : Type*} (p : α → Prop) [decidable_pred p] :
{a // p a} ⊕ {a // ¬ p a} ≃ α :=
{ to_fun := sum.elim coe coe,
inv_fun := λ a, if h : p a then sum.inl ⟨a, h⟩ else sum.inr ⟨a, h⟩,
left_inv := by { rintros (⟨x,hx⟩|⟨x,hx⟩); dsimp; [rw dif_pos, rw dif_neg], },
right_inv := λ a, by { dsimp, split_ifs; refl } }
@[simp] lemma sum_compl_apply_inl {α : Type*} (p : α → Prop) [decidable_pred p]
(x : {a // p a}) :
sum_compl p (sum.inl x) = x := rfl
@[simp] lemma sum_compl_apply_inr {α : Type*} (p : α → Prop) [decidable_pred p]
(x : {a // ¬ p a}) :
sum_compl p (sum.inr x) = x := rfl
@[simp] lemma sum_compl_apply_symm_of_pos {α : Type*} (p : α → Prop) [decidable_pred p]
(a : α) (h : p a) :
(sum_compl p).symm a = sum.inl ⟨a, h⟩ := dif_pos h
@[simp] lemma sum_compl_apply_symm_of_neg {α : Type*} (p : α → Prop) [decidable_pred p]
(a : α) (h : ¬ p a) :
(sum_compl p).symm a = sum.inr ⟨a, h⟩ := dif_neg h
end sum_compl
section subtype_preimage
variables (p : α → Prop) [decidable_pred p] (x₀ : {a // p a} → β)
/-- For a fixed function `x₀ : {a // p a} → β` defined on a subtype of `α`,
the subtype of functions `x : α → β` that agree with `x₀` on the subtype `{a // p a}`
is naturally equivalent to the type of functions `{a // ¬ p a} → β`. -/
@[simps]
def subtype_preimage :
{x : α → β // x ∘ coe = x₀} ≃ ({a // ¬ p a} → β) :=
{ to_fun := λ (x : {x : α → β // x ∘ coe = x₀}) a, (x : α → β) a,
inv_fun := λ x, ⟨λ a, if h : p a then x₀ ⟨a, h⟩ else x ⟨a, h⟩,
funext $ λ ⟨a, h⟩, dif_pos h⟩,
left_inv := λ ⟨x, hx⟩, subtype.val_injective $ funext $ λ a,
(by { dsimp, split_ifs; [ rw ← hx, skip ]; refl }),
right_inv := λ x, funext $ λ ⟨a, h⟩,
show dite (p a) _ _ = _, by { dsimp, rw [dif_neg h] } }
lemma subtype_preimage_symm_apply_coe_pos (x : {a // ¬ p a} → β) (a : α) (h : p a) :
((subtype_preimage p x₀).symm x : α → β) a = x₀ ⟨a, h⟩ :=
dif_pos h
lemma subtype_preimage_symm_apply_coe_neg (x : {a // ¬ p a} → β) (a : α) (h : ¬ p a) :
((subtype_preimage p x₀).symm x : α → β) a = x ⟨a, h⟩ :=
dif_neg h
end subtype_preimage
section fun_unique
variables (α β) [unique α]
/-- If `α` has a unique term, then the type of function `α → β` is equivalent to `β`. -/
@[simps] def fun_unique : (α → β) ≃ β :=
{ to_fun := λ f, f (default α),
inv_fun := λ b a, b,
left_inv := λ f, funext $ λ a, congr_arg f $ subsingleton.elim _ _,
right_inv := λ b, rfl }
end fun_unique
section
/-- A family of equivalences `Π a, β₁ a ≃ β₂ a` generates an equivalence between `Π a, β₁ a` and
`Π a, β₂ a`. -/
def Pi_congr_right {α} {β₁ β₂ : α → Sort*} (F : Π a, β₁ a ≃ β₂ a) : (Π a, β₁ a) ≃ (Π a, β₂ a) :=
⟨λ H a, F a (H a), λ H a, (F a).symm (H a),
λ H, funext $ by simp, λ H, funext $ by simp⟩
/-- Dependent `curry` equivalence: the type of dependent functions on `Σ i, β i` is equivalent
to the type of dependent functions of two arguments (i.e., functions to the space of functions). -/
def Pi_curry {α} {β : α → Sort*} (γ : Π a, β a → Sort*) :
(Π x : Σ i, β i, γ x.1 x.2) ≃ (Π a b, γ a b) :=
{ to_fun := λ f x y, f ⟨x,y⟩,
inv_fun := λ f x, f x.1 x.2,
left_inv := λ f, funext $ λ ⟨x,y⟩, rfl,
right_inv := λ f, funext $ λ x, funext $ λ y, rfl }
end
section
/-- A `psigma`-type is equivalent to the corresponding `sigma`-type. -/
@[simps apply symm_apply] def psigma_equiv_sigma {α} (β : α → Sort*) : (Σ' i, β i) ≃ Σ i, β i :=
⟨λ a, ⟨a.1, a.2⟩, λ a, ⟨a.1, a.2⟩, λ ⟨a, b⟩, rfl, λ ⟨a, b⟩, rfl⟩
/-- A family of equivalences `Π a, β₁ a ≃ β₂ a` generates an equivalence between `Σ a, β₁ a` and
`Σ a, β₂ a`. -/
@[simps apply symm_apply]
def sigma_congr_right {α} {β₁ β₂ : α → Sort*} (F : Π a, β₁ a ≃ β₂ a) : (Σ a, β₁ a) ≃ Σ a, β₂ a :=
⟨λ a, ⟨a.1, F a.1 a.2⟩, λ a, ⟨a.1, (F a.1).symm a.2⟩,
λ ⟨a, b⟩, congr_arg (sigma.mk a) $ symm_apply_apply (F a) b,
λ ⟨a, b⟩, congr_arg (sigma.mk a) $ apply_symm_apply (F a) b⟩
/-- An equivalence `f : α₁ ≃ α₂` generates an equivalence between `Σ a, β (f a)` and `Σ a, β a`. -/
@[simps apply]
def sigma_congr_left {α₁ α₂} {β : α₂ → Sort*} (e : α₁ ≃ α₂) : (Σ a:α₁, β (e a)) ≃ (Σ a:α₂, β a) :=
⟨λ a, ⟨e a.1, a.2⟩, λ a, ⟨e.symm a.1, @@eq.rec β a.2 (e.right_inv a.1).symm⟩,
λ ⟨a, b⟩, match e.symm (e a), e.left_inv a : ∀ a' (h : a' = a),
@sigma.mk _ (β ∘ e) _ (@@eq.rec β b (congr_arg e h.symm)) = ⟨a, b⟩ with
| _, rfl := rfl end,
λ ⟨a, b⟩, match e (e.symm a), _ : ∀ a' (h : a' = a),
sigma.mk a' (@@eq.rec β b h.symm) = ⟨a, b⟩ with
| _, rfl := rfl end⟩
/-- Transporting a sigma type through an equivalence of the base -/
def sigma_congr_left' {α₁ α₂} {β : α₁ → Sort*} (f : α₁ ≃ α₂) :
(Σ a:α₁, β a) ≃ (Σ a:α₂, β (f.symm a)) :=
(sigma_congr_left f.symm).symm
/-- Transporting a sigma type through an equivalence of the base and a family of equivalences
of matching fibers -/
def sigma_congr {α₁ α₂} {β₁ : α₁ → Sort*} {β₂ : α₂ → Sort*} (f : α₁ ≃ α₂)
(F : ∀ a, β₁ a ≃ β₂ (f a)) :
sigma β₁ ≃ sigma β₂ :=
(sigma_congr_right F).trans (sigma_congr_left f)
/-- `sigma` type with a constant fiber is equivalent to the product. -/
@[simps apply symm_apply] def sigma_equiv_prod (α β : Type*) : (Σ_:α, β) ≃ α × β :=
⟨λ a, ⟨a.1, a.2⟩, λ a, ⟨a.1, a.2⟩, λ ⟨a, b⟩, rfl, λ ⟨a, b⟩, rfl⟩
/-- If each fiber of a `sigma` type is equivalent to a fixed type, then the sigma type
is equivalent to the product. -/
def sigma_equiv_prod_of_equiv {α β} {β₁ : α → Sort*} (F : Π a, β₁ a ≃ β) : sigma β₁ ≃ α × β :=
(sigma_congr_right F).trans (sigma_equiv_prod α β)
end
section prod_congr
variables {α₁ β₁ β₂ : Type*} (e : α₁ → β₁ ≃ β₂)
/-- A family of equivalences `Π (a : α₁), β₁ ≃ β₂` generates an equivalence
between `β₁ × α₁` and `β₂ × α₁`. -/
def prod_congr_left : β₁ × α₁ ≃ β₂ × α₁ :=
{ to_fun := λ ab, ⟨e ab.2 ab.1, ab.2⟩,
inv_fun := λ ab, ⟨(e ab.2).symm ab.1, ab.2⟩,
left_inv := by { rintros ⟨a, b⟩, simp },
right_inv := by { rintros ⟨a, b⟩, simp } }
@[simp] lemma prod_congr_left_apply (b : β₁) (a : α₁) :
prod_congr_left e (b, a) = (e a b, a) := rfl
lemma prod_congr_refl_right (e : β₁ ≃ β₂) :
prod_congr e (equiv.refl α₁) = prod_congr_left (λ _, e) :=
by { ext ⟨a, b⟩ : 1, simp }
/-- A family of equivalences `Π (a : α₁), β₁ ≃ β₂` generates an equivalence
between `α₁ × β₁` and `α₁ × β₂`. -/
def prod_congr_right : α₁ × β₁ ≃ α₁ × β₂ :=
{ to_fun := λ ab, ⟨ab.1, e ab.1 ab.2⟩,
inv_fun := λ ab, ⟨ab.1, (e ab.1).symm ab.2⟩,
left_inv := by { rintros ⟨a, b⟩, simp },
right_inv := by { rintros ⟨a, b⟩, simp } }
@[simp] lemma prod_congr_right_apply (a : α₁) (b : β₁) :
prod_congr_right e (a, b) = (a, e a b) := rfl
lemma prod_congr_refl_left (e : β₁ ≃ β₂) :
prod_congr (equiv.refl α₁) e = prod_congr_right (λ _, e) :=
by { ext ⟨a, b⟩ : 1, simp }
@[simp] lemma prod_congr_left_trans_prod_comm :
(prod_congr_left e).trans (prod_comm _ _) = (prod_comm _ _).trans (prod_congr_right e) :=
by { ext ⟨a, b⟩ : 1, simp }
@[simp] lemma prod_congr_right_trans_prod_comm :
(prod_congr_right e).trans (prod_comm _ _) = (prod_comm _ _).trans (prod_congr_left e) :=
by { ext ⟨a, b⟩ : 1, simp }
lemma sigma_congr_right_sigma_equiv_prod :
(sigma_congr_right e).trans (sigma_equiv_prod α₁ β₂) =
(sigma_equiv_prod α₁ β₁).trans (prod_congr_right e) :=
by { ext ⟨a, b⟩ : 1, simp }
lemma sigma_equiv_prod_sigma_congr_right :
(sigma_equiv_prod α₁ β₁).symm.trans (sigma_congr_right e) =
(prod_congr_right e).trans (sigma_equiv_prod α₁ β₂).symm :=
by { ext ⟨a, b⟩ : 1, simp }
end prod_congr
namespace perm
variables {α₁ β₁ β₂ : Type*} [decidable_eq α₁] (a : α₁) (e : perm β₁)
/-- `prod_extend_right a e` extends `e : perm β` to `perm (α × β)` by sending `(a, b)` to
`(a, e b)` and keeping the other `(a', b)` fixed. -/
def prod_extend_right : perm (α₁ × β₁) :=
{ to_fun := λ ab, if ab.fst = a then (a, e ab.snd) else ab,
inv_fun := λ ab, if ab.fst = a then (a, e⁻¹ ab.snd) else ab,
left_inv := by { rintros ⟨k', x⟩, simp only, split_ifs with h; simp [h] },
right_inv := by { rintros ⟨k', x⟩, simp only, split_ifs with h; simp [h] } }
@[simp] lemma prod_extend_right_apply_eq (b : β₁) :
prod_extend_right a e (a, b) = (a, e b) := if_pos rfl
lemma prod_extend_right_apply_ne {a a' : α₁} (h : a' ≠ a) (b : β₁) :
prod_extend_right a e (a', b) = (a', b) := if_neg h
lemma eq_of_prod_extend_right_ne {e : perm β₁} {a a' : α₁} {b : β₁}
(h : prod_extend_right a e (a', b) ≠ (a', b)) : a' = a :=
by { contrapose! h, exact prod_extend_right_apply_ne _ h _ }
@[simp] lemma fst_prod_extend_right (ab : α₁ × β₁) :
(prod_extend_right a e ab).fst = ab.fst :=
begin
rw [prod_extend_right, coe_fn_mk],
split_ifs with h,
{ rw h },
{ refl }
end
end perm
section
/-- The type of functions to a product `α × β` is equivalent to the type of pairs of functions
`γ → α` and `γ → β`. -/
def arrow_prod_equiv_prod_arrow (α β γ : Type*) : (γ → α × β) ≃ (γ → α) × (γ → β) :=
⟨λ f, (λ c, (f c).1, λ c, (f c).2),
λ p c, (p.1 c, p.2 c),
λ f, funext $ λ c, prod.mk.eta,
λ p, by { cases p, refl }⟩
/-- Functions `α → β → γ` are equivalent to functions on `α × β`. -/
def arrow_arrow_equiv_prod_arrow (α β γ : Sort*) : (α → β → γ) ≃ (α × β → γ) :=
⟨uncurry, curry, curry_uncurry, uncurry_curry⟩
open sum
/-- The type of functions on a sum type `α ⊕ β` is equivalent to the type of pairs of functions
on `α` and on `β`. -/
def sum_arrow_equiv_prod_arrow (α β γ : Type*) : ((α ⊕ β) → γ) ≃ (α → γ) × (β → γ) :=
⟨λ f, (f ∘ inl, f ∘ inr),
λ p, sum.elim p.1 p.2,
λ f, by { ext ⟨⟩; refl },
λ p, by { cases p, refl }⟩
/-- Type product is right distributive with respect to type sum up to an equivalence. -/
def sum_prod_distrib (α β γ : Sort*) : (α ⊕ β) × γ ≃ (α × γ) ⊕ (β × γ) :=
⟨λ p, match p with (inl a, c) := inl (a, c) | (inr b, c) := inr (b, c) end,
λ s, match s with inl q := (inl q.1, q.2) | inr q := (inr q.1, q.2) end,
λ p, by rcases p with ⟨_ | _, _⟩; refl,
λ s, by rcases s with ⟨_, _⟩ | ⟨_, _⟩; refl⟩
@[simp] theorem sum_prod_distrib_apply_left {α β γ} (a : α) (c : γ) :
sum_prod_distrib α β γ (sum.inl a, c) = sum.inl (a, c) := rfl
@[simp] theorem sum_prod_distrib_apply_right {α β γ} (b : β) (c : γ) :
sum_prod_distrib α β γ (sum.inr b, c) = sum.inr (b, c) := rfl
/-- Type product is left distributive with respect to type sum up to an equivalence. -/
def prod_sum_distrib (α β γ : Sort*) : α × (β ⊕ γ) ≃ (α × β) ⊕ (α × γ) :=
calc α × (β ⊕ γ) ≃ (β ⊕ γ) × α : prod_comm _ _
... ≃ (β × α) ⊕ (γ × α) : sum_prod_distrib _ _ _
... ≃ (α × β) ⊕ (α × γ) : sum_congr (prod_comm _ _) (prod_comm _ _)
@[simp] theorem prod_sum_distrib_apply_left {α β γ} (a : α) (b : β) :
prod_sum_distrib α β γ (a, sum.inl b) = sum.inl (a, b) := rfl
@[simp] theorem prod_sum_distrib_apply_right {α β γ} (a : α) (c : γ) :
prod_sum_distrib α β γ (a, sum.inr c) = sum.inr (a, c) := rfl
/-- The product of an indexed sum of types (formally, a `sigma`-type `Σ i, α i`) by a type `β` is
equivalent to the sum of products `Σ i, (α i × β)`. -/
def sigma_prod_distrib {ι : Type*} (α : ι → Type*) (β : Type*) :
((Σ i, α i) × β) ≃ (Σ i, (α i × β)) :=
⟨λ p, ⟨p.1.1, (p.1.2, p.2)⟩,
λ p, (⟨p.1, p.2.1⟩, p.2.2),
λ p, by { rcases p with ⟨⟨_, _⟩, _⟩, refl },
λ p, by { rcases p with ⟨_, ⟨_, _⟩⟩, refl }⟩
/-- The product `bool × α` is equivalent to `α ⊕ α`. -/
def bool_prod_equiv_sum (α : Type u) : bool × α ≃ α ⊕ α :=
calc bool × α ≃ (unit ⊕ unit) × α : prod_congr bool_equiv_punit_sum_punit (equiv.refl _)
... ≃ (unit × α) ⊕ (unit × α) : sum_prod_distrib _ _ _
... ≃ α ⊕ α : sum_congr (punit_prod _) (punit_prod _)
/-- The function type `bool → α` is equivalent to `α × α`. -/
def bool_to_equiv_prod (α : Type u) : (bool → α) ≃ α × α :=
calc (bool → α) ≃ ((unit ⊕ unit) → α) : (arrow_congr bool_equiv_punit_sum_punit (equiv.refl α))
... ≃ (unit → α) × (unit → α) : sum_arrow_equiv_prod_arrow _ _ _
... ≃ α × α : prod_congr (punit_arrow_equiv _) (punit_arrow_equiv _)
@[simp] lemma bool_to_equiv_prod_apply {α : Type u} (f : bool → α) :
bool_to_equiv_prod α f = (f ff, f tt) := rfl
@[simp] lemma bool_to_equiv_prod_symm_apply_ff {α : Type u} (p : α × α) :
(bool_to_equiv_prod α).symm p ff = p.1 := rfl
@[simp] lemma bool_to_equiv_prod_symm_apply_tt {α : Type u} (p : α × α) :
(bool_to_equiv_prod α).symm p tt = p.2 := rfl
end
section
open sum nat
/-- The set of natural numbers is equivalent to `ℕ ⊕ punit`. -/
def nat_equiv_nat_sum_punit : ℕ ≃ ℕ ⊕ punit.{u+1} :=
⟨λ n, match n with zero := inr punit.star | succ a := inl a end,
λ s, match s with inl n := succ n | inr punit.star := zero end,
λ n, begin cases n, repeat { refl } end,
λ s, begin cases s with a u, { refl }, {cases u, { refl }} end⟩
/-- `ℕ ⊕ punit` is equivalent to `ℕ`. -/
def nat_sum_punit_equiv_nat : ℕ ⊕ punit.{u+1} ≃ ℕ :=
nat_equiv_nat_sum_punit.symm
/-- The type of integer numbers is equivalent to `ℕ ⊕ ℕ`. -/
def int_equiv_nat_sum_nat : ℤ ≃ ℕ ⊕ ℕ :=
by refine ⟨_, _, _, _⟩; intro z; {cases z; [left, right]; assumption} <|> {cases z; refl}
end
/-- An equivalence between `α` and `β` generates an equivalence between `list α` and `list β`. -/
def list_equiv_of_equiv {α β : Type*} (e : α ≃ β) : list α ≃ list β :=
{ to_fun := list.map e,
inv_fun := list.map e.symm,
left_inv := λ l, by rw [list.map_map, e.symm_comp_self, list.map_id],
right_inv := λ l, by rw [list.map_map, e.self_comp_symm, list.map_id] }
/-- `fin n` is equivalent to `{m // m < n}`. -/
def fin_equiv_subtype (n : ℕ) : fin n ≃ {m // m < n} :=
⟨λ x, ⟨x.1, x.2⟩, λ x, ⟨x.1, x.2⟩, λ ⟨a, b⟩, rfl,λ ⟨a, b⟩, rfl⟩
/-- If `α` is equivalent to `β`, then `unique α` is equivalent to `β`. -/
def unique_congr (e : α ≃ β) : unique α ≃ unique β :=
{ to_fun := λ h, @equiv.unique _ _ h e.symm,
inv_fun := λ h, @equiv.unique _ _ h e,
left_inv := λ _, subsingleton.elim _ _,
right_inv := λ _, subsingleton.elim _ _ }
section
open subtype
/-- If `α` is equivalent to `β` and the predicates `p : α → Prop` and `q : β → Prop` are equivalent
at corresponding points, then `{a // p a}` is equivalent to `{b // q b}`. -/
def subtype_congr {p : α → Prop} {q : β → Prop}
(e : α ≃ β) (h : ∀ a, p a ↔ q (e a)) : {a : α // p a} ≃ {b : β // q b} :=
⟨λ x, ⟨e x, (h _).1 x.2⟩,
λ y, ⟨e.symm y, (h _).2 (by { simp, exact y.2 })⟩,
λ ⟨x, h⟩, subtype.ext_val $ by simp,
λ ⟨y, h⟩, subtype.ext_val $ by simp⟩
@[simp] lemma subtype_congr_apply {p : α → Prop} {q : β → Prop} (e : α ≃ β)
(h : ∀ (a : α), p a ↔ q (e a)) (x : {x // p x}) :
e.subtype_congr h x = ⟨e x, (h _).1 x.2⟩ :=
rfl
@[simp] lemma subtype_congr_symm_apply {p : α → Prop} {q : β → Prop} (e : α ≃ β)
(h : ∀ (a : α), p a ↔ q (e a)) (y : {y // q y}) :
(e.subtype_congr h).symm y = ⟨e.symm y, (h _).2 $ (e.apply_symm_apply y).symm ▸ y.2⟩ :=
rfl
/-- If two predicates `p` and `q` are pointwise equivalent, then `{x // p x}` is equivalent to
`{x // q x}`. -/
@[simps {rhs_md := semireducible, simp_rhs := tt}]
def subtype_congr_right {p q : α → Prop} (e : ∀x, p x ↔ q x) : {x // p x} ≃ {x // q x} :=
subtype_congr (equiv.refl _) e
/-- If `α ≃ β`, then for any predicate `p : β → Prop` the subtype `{a // p (e a)}` is equivalent
to the subtype `{b // p b}`. -/
def subtype_equiv_of_subtype {p : β → Prop} (e : α ≃ β) :
{a : α // p (e a)} ≃ {b : β // p b} :=
subtype_congr e $ by simp
/-- If `α ≃ β`, then for any predicate `p : α → Prop` the subtype `{a // p a}` is equivalent
to the subtype `{b // p (e.symm b)}`. This version is used by `equiv_rw`. -/
def subtype_equiv_of_subtype' {p : α → Prop} (e : α ≃ β) :
{a : α // p a} ≃ {b : β // p (e.symm b)} :=
e.symm.subtype_equiv_of_subtype.symm
/-- If two predicates are equal, then the corresponding subtypes are equivalent. -/
def subtype_congr_prop {α : Type*} {p q : α → Prop} (h : p = q) : subtype p ≃ subtype q :=
subtype_congr (equiv.refl α) (assume a, h ▸ iff.rfl)
/-- The subtypes corresponding to equal sets are equivalent. -/
@[simps apply {rhs_md := semireducible, simp_rhs := tt}]
def set_congr {α : Type*} {s t : set α} (h : s = t) : s ≃ t :=
subtype_congr_prop h
/-- A subtype of a subtype is equivalent to the subtype of elements satisfying both predicates. This
version allows the “inner” predicate to depend on `h : p a`. -/
def subtype_subtype_equiv_subtype_exists {α : Type u} (p : α → Prop) (q : subtype p → Prop) :
subtype q ≃ {a : α // ∃h:p a, q ⟨a, h⟩ } :=
⟨λ⟨⟨a, ha⟩, ha'⟩, ⟨a, ha, ha'⟩,
λ⟨a, ha⟩, ⟨⟨a, ha.cases_on $ assume h _, h⟩, by { cases ha, exact ha_h }⟩,
assume ⟨⟨a, ha⟩, h⟩, rfl, assume ⟨a, h₁, h₂⟩, rfl⟩
/-- A subtype of a subtype is equivalent to the subtype of elements satisfying both predicates. -/
def subtype_subtype_equiv_subtype_inter {α : Type u} (p q : α → Prop) :
{x : subtype p // q x.1} ≃ subtype (λ x, p x ∧ q x) :=
(subtype_subtype_equiv_subtype_exists p _).trans $
subtype_congr_right $ λ x, exists_prop
/-- If the outer subtype has more restrictive predicate than the inner one,
then we can drop the latter. -/
def subtype_subtype_equiv_subtype {α : Type u} {p q : α → Prop} (h : ∀ {x}, q x → p x) :
{x : subtype p // q x.1} ≃ subtype q :=
(subtype_subtype_equiv_subtype_inter p _).trans $
subtype_congr_right $
assume x,
⟨and.right, λ h₁, ⟨h h₁, h₁⟩⟩
/-- If a proposition holds for all elements, then the subtype is
equivalent to the original type. -/
def subtype_univ_equiv {α : Type u} {p : α → Prop} (h : ∀ x, p x) :
subtype p ≃ α :=
⟨λ x, x, λ x, ⟨x, h x⟩, λ x, subtype.eq rfl, λ x, rfl⟩
/-- A subtype of a sigma-type is a sigma-type over a subtype. -/
def subtype_sigma_equiv {α : Type u} (p : α → Type v) (q : α → Prop) :
{ y : sigma p // q y.1 } ≃ Σ(x : subtype q), p x.1 :=
⟨λ x, ⟨⟨x.1.1, x.2⟩, x.1.2⟩,
λ x, ⟨⟨x.1.1, x.2⟩, x.1.2⟩,
λ ⟨⟨x, h⟩, y⟩, rfl,
λ ⟨⟨x, y⟩, h⟩, rfl⟩
/-- A sigma type over a subtype is equivalent to the sigma set over the original type,
if the fiber is empty outside of the subset -/
def sigma_subtype_equiv_of_subset {α : Type u} (p : α → Type v) (q : α → Prop)
(h : ∀ x, p x → q x) :
(Σ x : subtype q, p x) ≃ Σ x : α, p x :=
(subtype_sigma_equiv p q).symm.trans $ subtype_univ_equiv $ λ x, h x.1 x.2
/-- If a predicate `p : β → Prop` is true on the range of a map `f : α → β`, then
`Σ y : {y // p y}, {x // f x = y}` is equivalent to `α`. -/
def sigma_subtype_preimage_equiv {α : Type u} {β : Type v} (f : α → β) (p : β → Prop)
(h : ∀ x, p (f x)) :
(Σ y : subtype p, {x : α // f x = y}) ≃ α :=
calc _ ≃ Σ y : β, {x : α // f x = y} : sigma_subtype_equiv_of_subset _ p (λ y ⟨x, h'⟩, h' ▸ h x)
... ≃ α : sigma_preimage_equiv f
/-- If for each `x` we have `p x ↔ q (f x)`, then `Σ y : {y // q y}, f ⁻¹' {y}` is equivalent
to `{x // p x}`. -/
def sigma_subtype_preimage_equiv_subtype {α : Type u} {β : Type v} (f : α → β)
{p : α → Prop} {q : β → Prop} (h : ∀ x, p x ↔ q (f x)) :
(Σ y : subtype q, {x : α // f x = y}) ≃ subtype p :=
calc (Σ y : subtype q, {x : α // f x = y}) ≃
Σ y : subtype q, {x : subtype p // subtype.mk (f x) ((h x).1 x.2) = y} :
begin
apply sigma_congr_right,
assume y,
symmetry,
refine (subtype_subtype_equiv_subtype_exists _ _).trans (subtype_congr_right _),
assume x,
exact ⟨λ ⟨hp, h'⟩, congr_arg subtype.val h', λ h', ⟨(h x).2 (h'.symm ▸ y.2), subtype.eq h'⟩⟩
end
... ≃ subtype p : sigma_preimage_equiv (λ x : subtype p, (⟨f x, (h x).1 x.property⟩ : subtype q))
/-- The `pi`-type `Π i, π i` is equivalent to the type of sections `f : ι → Σ i, π i` of the
`sigma` type such that for all `i` we have `(f i).fst = i`. -/
def pi_equiv_subtype_sigma (ι : Type*) (π : ι → Type*) :
(Πi, π i) ≃ {f : ι → Σi, π i | ∀i, (f i).1 = i } :=
⟨ λf, ⟨λi, ⟨i, f i⟩, assume i, rfl⟩, λf i, begin rw ← f.2 i, exact (f.1 i).2 end,
assume f, funext $ assume i, rfl,
assume ⟨f, hf⟩, subtype.eq $ funext $ assume i, sigma.eq (hf i).symm $
eq_of_heq $ rec_heq_of_heq _ $ rec_heq_of_heq _ $ heq.refl _⟩
/-- The set of functions `f : Π a, β a` such that for all `a` we have `p a (f a)` is equivalent
to the set of functions `Π a, {b : β a // p a b}`. -/
def subtype_pi_equiv_pi {α : Sort u} {β : α → Sort v} {p : Πa, β a → Prop} :
{f : Πa, β a // ∀a, p a (f a) } ≃ Πa, { b : β a // p a b } :=
⟨λf a, ⟨f.1 a, f.2 a⟩, λf, ⟨λa, (f a).1, λa, (f a).2⟩,
by { rintro ⟨f, h⟩, refl },
by { rintro f, funext a, exact subtype.ext_val rfl }⟩
/-- A subtype of a product defined by componentwise conditions
is equivalent to a product of subtypes. -/
def subtype_prod_equiv_prod {α : Type u} {β : Type v} {p : α → Prop} {q : β → Prop} :
{c : α × β // p c.1 ∧ q c.2} ≃ ({a // p a} × {b // q b}) :=
⟨λ x, ⟨⟨x.1.1, x.2.1⟩, ⟨x.1.2, x.2.2⟩⟩,
λ x, ⟨⟨x.1.1, x.2.1⟩, ⟨x.1.2, x.2.2⟩⟩,
λ ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl,
λ ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl⟩
end
section subtype_equiv_codomain
variables {X : Type*} {Y : Type*} [decidable_eq X] {x : X}
/-- The type of all functions `X → Y` with prescribed values for all `x' ≠ x`
is equivalent to the codomain `Y`. -/
def subtype_equiv_codomain (f : {x' // x' ≠ x} → Y) : {g : X → Y // g ∘ coe = f} ≃ Y :=
(subtype_preimage _ f).trans $
@fun_unique {x' // ¬ x' ≠ x} _ $
show unique {x' // ¬ x' ≠ x}, from @equiv.unique _ _
(show unique {x' // x' = x}, from
{ default := ⟨x, rfl⟩, uniq := λ ⟨x', h⟩, subtype.val_injective h })
(subtype_congr_right $ λ a, not_not)
@[simp] lemma coe_subtype_equiv_codomain (f : {x' // x' ≠ x} → Y) :
(subtype_equiv_codomain f : {g : X → Y // g ∘ coe = f} → Y) = λ g, (g : X → Y) x := rfl
@[simp] lemma subtype_equiv_codomain_apply (f : {x' // x' ≠ x} → Y)
(g : {g : X → Y // g ∘ coe = f}) :
subtype_equiv_codomain f g = (g : X → Y) x := rfl
lemma coe_subtype_equiv_codomain_symm (f : {x' // x' ≠ x} → Y) :
((subtype_equiv_codomain f).symm : Y → {g : X → Y // g ∘ coe = f}) =
λ y, ⟨λ x', if h : x' ≠ x then f ⟨x', h⟩ else y,
by { funext x', dsimp, erw [dif_pos x'.2, subtype.coe_eta] }⟩ := rfl
@[simp] lemma subtype_equiv_codomain_symm_apply (f : {x' // x' ≠ x} → Y) (y : Y) (x' : X) :
((subtype_equiv_codomain f).symm y : X → Y) x' = if h : x' ≠ x then f ⟨x', h⟩ else y :=
rfl
@[simp] lemma subtype_equiv_codomain_symm_apply_eq (f : {x' // x' ≠ x} → Y) (y : Y) :
((subtype_equiv_codomain f).symm y : X → Y) x = y :=
dif_neg (not_not.mpr rfl)
lemma subtype_equiv_codomain_symm_apply_ne (f : {x' // x' ≠ x} → Y) (y : Y) (x' : X) (h : x' ≠ x) :
((subtype_equiv_codomain f).symm y : X → Y) x' = f ⟨x', h⟩ :=
dif_pos h
end subtype_equiv_codomain
namespace set
open set
/-- `univ α` is equivalent to `α`. -/
@[simps apply symm_apply]
protected def univ (α) : @univ α ≃ α :=
⟨coe, λ a, ⟨a, trivial⟩, λ ⟨a, _⟩, rfl, λ a, rfl⟩
/-- An empty set is equivalent to the `empty` type. -/
protected def empty (α) : (∅ : set α) ≃ empty :=
equiv_empty $ λ ⟨x, h⟩, not_mem_empty x h
/-- An empty set is equivalent to a `pempty` type. -/
protected def pempty (α) : (∅ : set α) ≃ pempty :=
equiv_pempty $ λ ⟨x, h⟩, not_mem_empty x h
/-- If sets `s` and `t` are separated by a decidable predicate, then `s ∪ t` is equivalent to
`s ⊕ t`. -/
protected def union' {α} {s t : set α}
(p : α → Prop) [decidable_pred p]
(hs : ∀ x ∈ s, p x)
(ht : ∀ x ∈ t, ¬ p x) : (s ∪ t : set α) ≃ s ⊕ t :=
{ to_fun := λ x, if hp : p x
then sum.inl ⟨_, x.2.resolve_right (λ xt, ht _ xt hp)⟩
else sum.inr ⟨_, x.2.resolve_left (λ xs, hp (hs _ xs))⟩,
inv_fun := λ o, match o with
| (sum.inl x) := ⟨x, or.inl x.2⟩
| (sum.inr x) := ⟨x, or.inr x.2⟩
end,
left_inv := λ ⟨x, h'⟩, by by_cases p x; simp [union'._match_1, h]; congr,
right_inv := λ o, begin
rcases o with ⟨x, h⟩ | ⟨x, h⟩;
dsimp [union'._match_1];
[simp [hs _ h], simp [ht _ h]]
end }
/-- If sets `s` and `t` are disjoint, then `s ∪ t` is equivalent to `s ⊕ t`. -/
protected def union {α} {s t : set α} [decidable_pred (λ x, x ∈ s)] (H : s ∩ t ⊆ ∅) :
(s ∪ t : set α) ≃ s ⊕ t :=
set.union' (λ x, x ∈ s) (λ _, id) (λ x xt xs, H ⟨xs, xt⟩)
lemma union_apply_left {α} {s t : set α} [decidable_pred (λ x, x ∈ s)] (H : s ∩ t ⊆ ∅)
{a : (s ∪ t : set α)} (ha : ↑a ∈ s) : equiv.set.union H a = sum.inl ⟨a, ha⟩ :=
dif_pos ha
lemma union_apply_right {α} {s t : set α} [decidable_pred (λ x, x ∈ s)] (H : s ∩ t ⊆ ∅)
{a : (s ∪ t : set α)} (ha : ↑a ∈ t) : equiv.set.union H a = sum.inr ⟨a, ha⟩ :=
dif_neg $ λ h, H ⟨h, ha⟩
@[simp] lemma union_symm_apply_left {α} {s t : set α} [decidable_pred (λ x, x ∈ s)] (H : s ∩ t ⊆ ∅)
(a : s) : (equiv.set.union H).symm (sum.inl a) = ⟨a, subset_union_left _ _ a.2⟩ :=
rfl
@[simp] lemma union_symm_apply_right {α} {s t : set α} [decidable_pred (λ x, x ∈ s)] (H : s ∩ t ⊆ ∅)
(a : t) : (equiv.set.union H).symm (sum.inr a) = ⟨a, subset_union_right _ _ a.2⟩ :=
rfl
-- TODO: Any reason to use the same universe?
/-- A singleton set is equivalent to a `punit` type. -/
protected def singleton {α} (a : α) : ({a} : set α) ≃ punit.{u} :=
⟨λ _, punit.star, λ _, ⟨a, mem_singleton _⟩,
λ ⟨x, h⟩, by { simp at h, subst x },
λ ⟨⟩, rfl⟩
/-- Equal sets are equivalent. -/
@[simps apply symm_apply]
protected def of_eq {α : Type u} {s t : set α} (h : s = t) : s ≃ t :=
{ to_fun := λ x, ⟨x, h ▸ x.2⟩,
inv_fun := λ x, ⟨x, h.symm ▸ x.2⟩,
left_inv := λ _, subtype.eq rfl,
right_inv := λ _, subtype.eq rfl }
/-- If `a ∉ s`, then `insert a s` is equivalent to `s ⊕ punit`. -/
protected def insert {α} {s : set.{u} α} [decidable_pred s] {a : α} (H : a ∉ s) :
(insert a s : set α) ≃ s ⊕ punit.{u+1} :=
calc (insert a s : set α) ≃ ↥(s ∪ {a}) : equiv.set.of_eq (by simp)
... ≃ s ⊕ ({a} : set α) : equiv.set.union (by finish [set.subset_def])
... ≃ s ⊕ punit.{u+1} : sum_congr (equiv.refl _) (equiv.set.singleton _)
@[simp] lemma insert_symm_apply_inl {α} {s : set.{u} α} [decidable_pred s] {a : α} (H : a ∉ s)
(b : s) : (equiv.set.insert H).symm (sum.inl b) = ⟨b, or.inr b.2⟩ :=
rfl
@[simp] lemma insert_symm_apply_inr {α} {s : set.{u} α} [decidable_pred s] {a : α} (H : a ∉ s)
(b : punit.{u+1}) : (equiv.set.insert H).symm (sum.inr b) = ⟨a, or.inl rfl⟩ :=
rfl
@[simp] lemma insert_apply_left {α} {s : set.{u} α} [decidable_pred s] {a : α} (H : a ∉ s) :
equiv.set.insert H ⟨a, or.inl rfl⟩ = sum.inr punit.star :=
(equiv.set.insert H).apply_eq_iff_eq_symm_apply.2 rfl
@[simp] lemma insert_apply_right {α} {s : set.{u} α} [decidable_pred s] {a : α} (H : a ∉ s)
(b : s) : equiv.set.insert H ⟨b, or.inr b.2⟩ = sum.inl b :=
(equiv.set.insert H).apply_eq_iff_eq_symm_apply.2 rfl
/-- If `s : set α` is a set with decidable membership, then `s ⊕ sᶜ` is equivalent to `α`. -/
protected def sum_compl {α} (s : set α) [decidable_pred s] : s ⊕ (sᶜ : set α) ≃ α :=
calc s ⊕ (sᶜ : set α) ≃ ↥(s ∪ sᶜ) : (equiv.set.union (by simp [set.ext_iff])).symm
... ≃ @univ α : equiv.set.of_eq (by simp)
... ≃ α : equiv.set.univ _
@[simp] lemma sum_compl_apply_inl {α : Type u} (s : set α) [decidable_pred s] (x : s) :
equiv.set.sum_compl s (sum.inl x) = x := rfl
@[simp] lemma sum_compl_apply_inr {α : Type u} (s : set α) [decidable_pred s] (x : sᶜ) :
equiv.set.sum_compl s (sum.inr x) = x := rfl
lemma sum_compl_symm_apply_of_mem {α : Type u} {s : set α} [decidable_pred s] {x : α}
(hx : x ∈ s) : (equiv.set.sum_compl s).symm x = sum.inl ⟨x, hx⟩ :=
have ↑(⟨x, or.inl hx⟩ : (s ∪ sᶜ : set α)) ∈ s, from hx,
by { rw [equiv.set.sum_compl], simpa using set.union_apply_left _ this }
lemma sum_compl_symm_apply_of_not_mem {α : Type u} {s : set α} [decidable_pred s] {x : α}
(hx : x ∉ s) : (equiv.set.sum_compl s).symm x = sum.inr ⟨x, hx⟩ :=
have ↑(⟨x, or.inr hx⟩ : (s ∪ sᶜ : set α)) ∈ sᶜ, from hx,
by { rw [equiv.set.sum_compl], simpa using set.union_apply_right _ this }
@[simp] lemma sum_compl_symm_apply {α : Type*} {s : set α} [decidable_pred s] {x : s} :
(equiv.set.sum_compl s).symm x = sum.inl x :=
by cases x with x hx; exact set.sum_compl_symm_apply_of_mem hx
@[simp] lemma sum_compl_symm_apply_compl {α : Type*} {s : set α}
[decidable_pred s] {x : sᶜ} : (equiv.set.sum_compl s).symm x = sum.inr x :=
by cases x with x hx; exact set.sum_compl_symm_apply_of_not_mem hx
/-- `sum_diff_subset s t` is the natural equivalence between
`s ⊕ (t \ s)` and `t`, where `s` and `t` are two sets. -/
protected def sum_diff_subset {α} {s t : set α} (h : s ⊆ t) [decidable_pred s] :
s ⊕ (t \ s : set α) ≃ t :=
calc s ⊕ (t \ s : set α) ≃ (s ∪ (t \ s) : set α) :
(equiv.set.union (by simp [inter_diff_self])).symm
... ≃ t : equiv.set.of_eq (by { simp [union_diff_self, union_eq_self_of_subset_left h] })
@[simp] lemma sum_diff_subset_apply_inl
{α} {s t : set α} (h : s ⊆ t) [decidable_pred s] (x : s) :
equiv.set.sum_diff_subset h (sum.inl x) = inclusion h x := rfl
@[simp] lemma sum_diff_subset_apply_inr
{α} {s t : set α} (h : s ⊆ t) [decidable_pred s] (x : t \ s) :
equiv.set.sum_diff_subset h (sum.inr x) = inclusion (diff_subset t s) x := rfl
lemma sum_diff_subset_symm_apply_of_mem
{α} {s t : set α} (h : s ⊆ t) [decidable_pred s] {x : t} (hx : x.1 ∈ s) :
(equiv.set.sum_diff_subset h).symm x = sum.inl ⟨x, hx⟩ :=
begin
apply (equiv.set.sum_diff_subset h).injective,
simp only [apply_symm_apply, sum_diff_subset_apply_inl],
exact subtype.eq rfl,
end
lemma sum_diff_subset_symm_apply_of_not_mem
{α} {s t : set α} (h : s ⊆ t) [decidable_pred s] {x : t} (hx : x.1 ∉ s) :
(equiv.set.sum_diff_subset h).symm x = sum.inr ⟨x, ⟨x.2, hx⟩⟩ :=
begin
apply (equiv.set.sum_diff_subset h).injective,
simp only [apply_symm_apply, sum_diff_subset_apply_inr],
exact subtype.eq rfl,
end
/-- If `s` is a set with decidable membership, then the sum of `s ∪ t` and `s ∩ t` is equivalent
to `s ⊕ t`. -/
protected def union_sum_inter {α : Type u} (s t : set α) [decidable_pred s] :
(s ∪ t : set α) ⊕ (s ∩ t : set α) ≃ s ⊕ t :=
calc (s ∪ t : set α) ⊕ (s ∩ t : set α)
≃ (s ∪ t \ s : set α) ⊕ (s ∩ t : set α) : by rw [union_diff_self]
... ≃ (s ⊕ (t \ s : set α)) ⊕ (s ∩ t : set α) :
sum_congr (set.union $ subset_empty_iff.2 (inter_diff_self _ _)) (equiv.refl _)
... ≃ s ⊕ (t \ s : set α) ⊕ (s ∩ t : set α) : sum_assoc _ _ _
... ≃ s ⊕ (t \ s ∪ s ∩ t : set α) : sum_congr (equiv.refl _) begin
refine (set.union' (∉ s) _ _).symm,
exacts [λ x hx, hx.2, λ x hx, not_not_intro hx.1]
end
... ≃ s ⊕ t : by { rw (_ : t \ s ∪ s ∩ t = t), rw [union_comm, inter_comm, inter_union_diff] }
/-- Given an equivalence `e₀` between sets `s : set α` and `t : set β`, the set of equivalences
`e : α ≃ β` such that `e ↑x = ↑(e₀ x)` for each `x : s` is equivalent to the set of equivalences
between `sᶜ` and `tᶜ`. -/
protected def compl {α : Type u} {β : Type v} {s : set α} {t : set β} [decidable_pred s]
[decidable_pred t] (e₀ : s ≃ t) :
{e : α ≃ β // ∀ x : s, e x = e₀ x} ≃ ((sᶜ : set α) ≃ (tᶜ : set β)) :=
{ to_fun := λ e, subtype_congr e
(λ a, not_congr $ iff.symm $ maps_to.mem_iff
(maps_to_iff_exists_map_subtype.2 ⟨e₀, e.2⟩)
(surj_on.maps_to_compl (surj_on_iff_exists_map_subtype.2
⟨t, e₀, subset.refl t, e₀.surjective, e.2⟩) e.1.injective)),
inv_fun := λ e₁,
subtype.mk
(calc α ≃ s ⊕ (sᶜ : set α) : (set.sum_compl s).symm
... ≃ t ⊕ (tᶜ : set β) : e₀.sum_congr e₁
... ≃ β : set.sum_compl t)
(λ x, by simp only [sum.map_inl, trans_apply, sum_congr_apply,
set.sum_compl_apply_inl, set.sum_compl_symm_apply]),
left_inv := λ e,
begin
ext x,
by_cases hx : x ∈ s,
{ simp only [set.sum_compl_symm_apply_of_mem hx, ←e.prop ⟨x, hx⟩,
sum.map_inl, sum_congr_apply, trans_apply,
subtype.coe_mk, set.sum_compl_apply_inl] },
{ simp only [set.sum_compl_symm_apply_of_not_mem hx, sum.map_inr,
subtype_congr_apply, set.sum_compl_apply_inr, trans_apply,
sum_congr_apply, subtype.coe_mk] },
end,
right_inv := λ e, equiv.ext $ λ x, by simp only [sum.map_inr, subtype_congr_apply,
set.sum_compl_apply_inr, function.comp_app, sum_congr_apply, equiv.coe_trans,
subtype.coe_eta, subtype.coe_mk, set.sum_compl_symm_apply_compl] }
/-- The set product of two sets is equivalent to the type product of their coercions to types. -/
protected def prod {α β} (s : set α) (t : set β) :
s.prod t ≃ s × t :=
@subtype_prod_equiv_prod α β s t
/-- If a function `f` is injective on a set `s`, then `s` is equivalent to `f '' s`. -/
protected noncomputable def image_of_inj_on {α β} (f : α → β) (s : set α) (H : inj_on f s) :
s ≃ (f '' s) :=
⟨λ p, ⟨f p, mem_image_of_mem f p.2⟩,
λ p, ⟨classical.some p.2, (classical.some_spec p.2).1⟩,
λ ⟨x, h⟩, subtype.eq (H (classical.some_spec (mem_image_of_mem f h)).1 h
(classical.some_spec (mem_image_of_mem f h)).2),
λ ⟨y, h⟩, subtype.eq (classical.some_spec h).2⟩
/-- If `f` is an injective function, then `s` is equivalent to `f '' s`. -/
@[simps apply {rhs_md := semireducible}]
protected noncomputable def image {α β} (f : α → β) (s : set α) (H : injective f) : s ≃ (f '' s) :=
equiv.set.image_of_inj_on f s (H.inj_on s)
lemma image_symm_preimage {α β} {f : α → β} (hf : injective f) (u s : set α) :
(λ x, (set.image f s hf).symm x : f '' s → α) ⁻¹' u = coe ⁻¹' (f '' u) :=
begin
ext ⟨b, a, has, rfl⟩,
have : ∀(h : ∃a', a' ∈ s ∧ a' = a), classical.some h = a := λ h, (classical.some_spec h).2,
simp [equiv.set.image, equiv.set.image_of_inj_on, hf, this],
end
/-- If `f : α → β` is an injective function, then `α` is equivalent to the range of `f`. -/
@[simps apply]
protected noncomputable def range {α β} (f : α → β) (H : injective f) :
α ≃ range f :=
{ to_fun := λ x, ⟨f x, mem_range_self _⟩,
inv_fun := λ x, classical.some x.2,
left_inv := λ x, H (classical.some_spec (show f x ∈ range f, from mem_range_self _)),
right_inv := λ x, subtype.eq $ classical.some_spec x.2 }
theorem apply_range_symm {α β} (f : α → β) (H : injective f) (b : range f) :
f ((set.range f H).symm b) = b :=
begin
conv_rhs { rw ←((set.range f H).right_inv b), },
simp,
end
/-- If `α` is equivalent to `β`, then `set α` is equivalent to `set β`. -/
protected def congr {α β : Type*} (e : α ≃ β) : set α ≃ set β :=
⟨λ s, e '' s, λ t, e.symm '' t, symm_image_image e, symm_image_image e.symm⟩
/-- The set `{x ∈ s | t x}` is equivalent to the set of `x : s` such that `t x`. -/
protected def sep {α : Type u} (s : set α) (t : α → Prop) :
({ x ∈ s | t x } : set α) ≃ { x : s | t x } :=
(equiv.subtype_subtype_equiv_subtype_inter s t).symm
/-- The set `𝒫 S := {x | x ⊆ S}` is equivalent to the type `set S`. -/
protected def powerset {α} (S : set α) : 𝒫 S ≃ set S :=
{ to_fun := λ x : 𝒫 S, coe ⁻¹' (x : set α),
inv_fun := λ x : set S, ⟨coe '' x, by rintro _ ⟨a : S, _, rfl⟩; exact a.2⟩,
left_inv := λ x, by ext y; exact ⟨λ ⟨⟨_, _⟩, h, rfl⟩, h, λ h, ⟨⟨_, x.2 h⟩, h, rfl⟩⟩,
right_inv := λ x, by ext; simp }
end set
/-- If `f` is a bijective function, then its domain is equivalent to its codomain. -/
@[simps apply {rhs_md := semireducible, simp_rhs := tt}]
noncomputable def of_bijective {α β} (f : α → β) (hf : bijective f) : α ≃ β :=
(equiv.set.range f hf.1).trans $ (set_congr hf.2.range_eq).trans $ equiv.set.univ β
/-- If `f` is an injective function, then its domain is equivalent to its range. -/
@[simps apply {rhs_md := semireducible, simp_rhs := tt}]
noncomputable def of_injective {α β} (f : α → β) (hf : injective f) : α ≃ _root_.set.range f :=
of_bijective (λ x, ⟨f x, set.mem_range_self x⟩)
⟨λ x y hxy, hf $ by injections, λ ⟨_, x, rfl⟩, ⟨x, rfl⟩⟩
/-- Subtype of the quotient is equivalent to the quotient of the subtype. Let `α` be a setoid with
equivalence relation `~`. Let `p₂` be a predicate on the quotient type `α/~`, and `p₁` be the lift
of this predicate to `α`: `p₁ a ↔ p₂ ⟦a⟧`. Let `~₂` be the restriction of `~` to `{x // p₁ x}`.
Then `{x // p₂ x}` is equivalent to the quotient of `{x // p₁ x}` by `~₂`. -/
def subtype_quotient_equiv_quotient_subtype (p₁ : α → Prop) [s₁ : setoid α]
[s₂ : setoid (subtype p₁)] (p₂ : quotient s₁ → Prop) (hp₂ : ∀ a, p₁ a ↔ p₂ ⟦a⟧)
(h : ∀ x y : subtype p₁, @setoid.r _ s₂ x y ↔ (x : α) ≈ y) :
{x // p₂ x} ≃ quotient s₂ :=
{ to_fun := λ a, quotient.hrec_on a.1 (λ a h, ⟦⟨a, (hp₂ _).2 h⟩⟧)
(λ a b hab, hfunext (by rw quotient.sound hab)
(λ h₁ h₂ _, heq_of_eq (quotient.sound ((h _ _).2 hab)))) a.2,
inv_fun := λ a, quotient.lift_on a (λ a, (⟨⟦a.1⟧, (hp₂ _).1 a.2⟩ : {x // p₂ x}))
(λ a b hab, subtype.ext_val (quotient.sound ((h _ _).1 hab))),
left_inv := λ ⟨a, ha⟩, quotient.induction_on a (λ a ha, rfl) ha,
right_inv := λ a, quotient.induction_on a (λ ⟨a, ha⟩, rfl) }
section swap
variable [decidable_eq α]
/-- A helper function for `equiv.swap`. -/
def swap_core (a b r : α) : α :=
if r = a then b
else if r = b then a
else r
theorem swap_core_self (r a : α) : swap_core a a r = r :=
by { unfold swap_core, split_ifs; cc }
theorem swap_core_swap_core (r a b : α) : swap_core a b (swap_core a b r) = r :=
by { unfold swap_core, split_ifs; cc }
theorem swap_core_comm (r a b : α) : swap_core a b r = swap_core b a r :=
by { unfold swap_core, split_ifs; cc }
/-- `swap a b` is the permutation that swaps `a` and `b` and
leaves other values as is. -/
def swap (a b : α) : perm α :=
⟨swap_core a b, swap_core a b, λr, swap_core_swap_core r a b, λr, swap_core_swap_core r a b⟩
theorem swap_self (a : α) : swap a a = equiv.refl _ :=
ext $ λ r, swap_core_self r a
theorem swap_comm (a b : α) : swap a b = swap b a :=
ext $ λ r, swap_core_comm r _ _
theorem swap_apply_def (a b x : α) : swap a b x = if x = a then b else if x = b then a else x :=
rfl
@[simp] theorem swap_apply_left (a b : α) : swap a b a = b :=
if_pos rfl
@[simp] theorem swap_apply_right (a b : α) : swap a b b = a :=
by { by_cases h : b = a; simp [swap_apply_def, h], }
theorem swap_apply_of_ne_of_ne {a b x : α} : x ≠ a → x ≠ b → swap a b x = x :=
by simp [swap_apply_def] {contextual := tt}
@[simp] theorem swap_swap (a b : α) : (swap a b).trans (swap a b) = equiv.refl _ :=
ext $ λ x, swap_core_swap_core _ _ _
theorem swap_comp_apply {a b x : α} (π : perm α) :
π.trans (swap a b) x = if π x = a then b else if π x = b then a else π x :=
by { cases π, refl }
@[simp] lemma swap_inv {α : Type*} [decidable_eq α] (x y : α) :
(swap x y)⁻¹ = swap x y := rfl
@[simp] lemma symm_trans_swap_trans [decidable_eq β] (a b : α)
(e : α ≃ β) : (e.symm.trans (swap a b)).trans e = swap (e a) (e b) :=
equiv.ext (λ x, begin
have : ∀ a, e.symm x = a ↔ x = e a :=
λ a, by { rw @eq_comm _ (e.symm x), split; intros; simp * at * },
simp [swap_apply_def, this],
split_ifs; simp
end)
@[simp] lemma swap_mul_self {α : Type*} [decidable_eq α] (i j : α) : swap i j * swap i j = 1 :=
equiv.swap_swap i j
@[simp] lemma swap_apply_self {α : Type*} [decidable_eq α] (i j a : α) :
swap i j (swap i j a) = a :=
by rw [← perm.mul_apply, swap_mul_self, perm.one_apply]
/-- Augment an equivalence with a prescribed mapping `f a = b` -/
def set_value (f : α ≃ β) (a : α) (b : β) : α ≃ β :=
(swap a (f.symm b)).trans f
@[simp] theorem set_value_eq (f : α ≃ β) (a : α) (b : β) : set_value f a b a = b :=
by { dsimp [set_value], simp [swap_apply_left] }
end swap
protected lemma forall_congr {p : α → Prop} {q : β → Prop} (f : α ≃ β)
(h : ∀{x}, p x ↔ q (f x)) : (∀x, p x) ↔ (∀y, q y) :=
begin
split; intros h₂ x,
{ rw [←f.right_inv x], apply h.mp, apply h₂ },
apply h.mpr, apply h₂
end
protected lemma forall_congr' {p : α → Prop} {q : β → Prop} (f : α ≃ β)
(h : ∀{x}, p (f.symm x) ↔ q x) : (∀x, p x) ↔ (∀y, q y) :=
(equiv.forall_congr f.symm (λ x, h.symm)).symm
-- We next build some higher arity versions of `equiv.forall_congr`.
-- Although they appear to just be repeated applications of `equiv.forall_congr`,
-- unification of metavariables works better with these versions.
-- In particular, they are necessary in `equiv_rw`.
-- (Stopping at ternary functions seems reasonable: at least in 1-categorical mathematics,
-- it's rare to have axioms involving more than 3 elements at once.)
universes ua1 ua2 ub1 ub2 ug1 ug2
variables {α₁ : Sort ua1} {α₂ : Sort ua2}
{β₁ : Sort ub1} {β₂ : Sort ub2}
{γ₁ : Sort ug1} {γ₂ : Sort ug2}
protected lemma forall₂_congr {p : α₁ → β₁ → Prop} {q : α₂ → β₂ → Prop} (eα : α₁ ≃ α₂)
(eβ : β₁ ≃ β₂) (h : ∀{x y}, p x y ↔ q (eα x) (eβ y)) :
(∀x y, p x y) ↔ (∀x y, q x y) :=
begin
apply equiv.forall_congr,
intros,
apply equiv.forall_congr,
intros,
apply h,
end
protected lemma forall₂_congr' {p : α₁ → β₁ → Prop} {q : α₂ → β₂ → Prop} (eα : α₁ ≃ α₂)
(eβ : β₁ ≃ β₂) (h : ∀{x y}, p (eα.symm x) (eβ.symm y) ↔ q x y) :
(∀x y, p x y) ↔ (∀x y, q x y) :=
(equiv.forall₂_congr eα.symm eβ.symm (λ x y, h.symm)).symm
protected lemma forall₃_congr {p : α₁ → β₁ → γ₁ → Prop} {q : α₂ → β₂ → γ₂ → Prop}
(eα : α₁ ≃ α₂) (eβ : β₁ ≃ β₂) (eγ : γ₁ ≃ γ₂)
(h : ∀{x y z}, p x y z ↔ q (eα x) (eβ y) (eγ z)) : (∀x y z, p x y z) ↔ (∀x y z, q x y z) :=
begin
apply equiv.forall₂_congr,
intros,
apply equiv.forall_congr,
intros,
apply h,
end
protected lemma forall₃_congr' {p : α₁ → β₁ → γ₁ → Prop} {q : α₂ → β₂ → γ₂ → Prop}
(eα : α₁ ≃ α₂) (eβ : β₁ ≃ β₂) (eγ : γ₁ ≃ γ₂)
(h : ∀{x y z}, p (eα.symm x) (eβ.symm y) (eγ.symm z) ↔ q x y z) :
(∀x y z, p x y z) ↔ (∀x y z, q x y z) :=
(equiv.forall₃_congr eα.symm eβ.symm eγ.symm (λ x y z, h.symm)).symm
protected lemma forall_congr_left' {p : α → Prop} (f : α ≃ β) :
(∀x, p x) ↔ (∀y, p (f.symm y)) :=
equiv.forall_congr f (λx, by simp)
protected lemma forall_congr_left {p : β → Prop} (f : α ≃ β) :
(∀x, p (f x)) ↔ (∀y, p y) :=
(equiv.forall_congr_left' f.symm).symm
section
variables (P : α → Sort w) (e : α ≃ β)
/--
Transport dependent functions through an equivalence of the base space.
-/
@[simps] def Pi_congr_left' : (Π a, P a) ≃ (Π b, P (e.symm b)) :=
{ to_fun := λ f x, f (e.symm x),
inv_fun := λ f x, begin rw [← e.symm_apply_apply x], exact f (e x) end,
left_inv := λ f, funext $ λ x, eq_of_heq ((eq_rec_heq _ _).trans
(by { dsimp, rw e.symm_apply_apply })),
right_inv := λ f, funext $ λ x, eq_of_heq ((eq_rec_heq _ _).trans
(by { rw e.apply_symm_apply })) }
end
section
variables (P : β → Sort w) (e : α ≃ β)
/--
Transporting dependent functions through an equivalence of the base,
expressed as a "simplification".
-/
def Pi_congr_left : (Π a, P (e a)) ≃ (Π b, P b) :=
(Pi_congr_left' P e.symm).symm
end
section
variables
{W : α → Sort w} {Z : β → Sort z} (h₁ : α ≃ β) (h₂ : Π a : α, (W a ≃ Z (h₁ a)))
/--
Transport dependent functions through
an equivalence of the base spaces and a family
of equivalences of the matching fibers.
-/
def Pi_congr : (Π a, W a) ≃ (Π b, Z b) :=
(equiv.Pi_congr_right h₂).trans (equiv.Pi_congr_left _ h₁)
end
section
variables
{W : α → Sort w} {Z : β → Sort z} (h₁ : α ≃ β) (h₂ : Π b : β, (W (h₁.symm b) ≃ Z b))
/--
Transport dependent functions through
an equivalence of the base spaces and a family
of equivalences of the matching fibres.
-/
def Pi_congr' : (Π a, W a) ≃ (Π b, Z b) :=
(Pi_congr h₁.symm (λ b, (h₂ b).symm)).symm
end
end equiv
instance {α} [subsingleton α] : subsingleton (ulift α) := equiv.ulift.subsingleton
instance {α} [subsingleton α] : subsingleton (plift α) := equiv.plift.subsingleton
instance {α} [decidable_eq α] : decidable_eq (ulift α) := equiv.ulift.decidable_eq
instance {α} [decidable_eq α] : decidable_eq (plift α) := equiv.plift.decidable_eq
/-- If both `α` and `β` are singletons, then `α ≃ β`. -/
def equiv_of_unique_of_unique [unique α] [unique β] : α ≃ β :=
{ to_fun := λ _, default β,
inv_fun := λ _, default α,
left_inv := λ _, subsingleton.elim _ _,
right_inv := λ _, subsingleton.elim _ _ }
/-- If `α` is a singleton, then it is equivalent to any `punit`. -/
def equiv_punit_of_unique [unique α] : α ≃ punit.{v} :=
equiv_of_unique_of_unique
/-- If `α` is a subsingleton, then it is equivalent to `α × α`. -/
def subsingleton_prod_self_equiv {α : Type*} [subsingleton α] : α × α ≃ α :=
{ to_fun := λ p, p.1,
inv_fun := λ a, (a, a),
left_inv := λ p, subsingleton.elim _ _,
right_inv := λ p, subsingleton.elim _ _, }
/-- To give an equivalence between two subsingleton types, it is sufficient to give any two
functions between them. -/
def equiv_of_subsingleton_of_subsingleton [subsingleton α] [subsingleton β]
(f : α → β) (g : β → α) : α ≃ β :=
{ to_fun := f,
inv_fun := g,
left_inv := λ _, subsingleton.elim _ _,
right_inv := λ _, subsingleton.elim _ _ }
/-- `unique (unique α)` is equivalent to `unique α`. -/
def unique_unique_equiv : unique (unique α) ≃ unique α :=
equiv_of_subsingleton_of_subsingleton (λ h, h.default)
(λ h, { default := h, uniq := λ _, subsingleton.elim _ _ })
namespace quot
/-- An equivalence `e : α ≃ β` generates an equivalence between quotient spaces,
if `ra a₁ a₂ ↔ rb (e a₁) (e a₂). -/
protected def congr {ra : α → α → Prop} {rb : β → β → Prop} (e : α ≃ β)
(eq : ∀a₁ a₂, ra a₁ a₂ ↔ rb (e a₁) (e a₂)) :
quot ra ≃ quot rb :=
{ to_fun := quot.map e (assume a₁ a₂, (eq a₁ a₂).1),
inv_fun := quot.map e.symm
(assume b₁ b₂ h,
(eq (e.symm b₁) (e.symm b₂)).2
((e.apply_symm_apply b₁).symm ▸ (e.apply_symm_apply b₂).symm ▸ h)),
left_inv := by { rintros ⟨a⟩, dunfold quot.map, simp only [equiv.symm_apply_apply] },
right_inv := by { rintros ⟨a⟩, dunfold quot.map, simp only [equiv.apply_symm_apply] } }
/-- Quotients are congruent on equivalences under equality of their relation.
An alternative is just to use rewriting with `eq`, but then computational proofs get stuck. -/
protected def congr_right {r r' : α → α → Prop} (eq : ∀a₁ a₂, r a₁ a₂ ↔ r' a₁ a₂) :
quot r ≃ quot r' :=
quot.congr (equiv.refl α) eq
/-- An equivalence `e : α ≃ β` generates an equivalence between the quotient space of `α`
by a relation `ra` and the quotient space of `β` by the image of this relation under `e`. -/
protected def congr_left {r : α → α → Prop} (e : α ≃ β) :
quot r ≃ quot (λ b b', r (e.symm b) (e.symm b')) :=
@quot.congr α β r (λ b b', r (e.symm b) (e.symm b')) e (λ a₁ a₂, by simp only [e.symm_apply_apply])
end quot
namespace quotient
/-- An equivalence `e : α ≃ β` generates an equivalence between quotient spaces,
if `ra a₁ a₂ ↔ rb (e a₁) (e a₂). -/
protected def congr {ra : setoid α} {rb : setoid β} (e : α ≃ β)
(eq : ∀a₁ a₂, @setoid.r α ra a₁ a₂ ↔ @setoid.r β rb (e a₁) (e a₂)) :
quotient ra ≃ quotient rb :=
quot.congr e eq
/-- Quotients are congruent on equivalences under equality of their relation.
An alternative is just to use rewriting with `eq`, but then computational proofs get stuck. -/
protected def congr_right {r r' : setoid α}
(eq : ∀a₁ a₂, @setoid.r α r a₁ a₂ ↔ @setoid.r α r' a₁ a₂) : quotient r ≃ quotient r' :=
quot.congr_right eq
end quotient
/-- If a function is a bijection between `univ` and a set `s` in the target type, it induces an
equivalence between the original type and the type `↑s`. -/
noncomputable def set.bij_on.equiv {α : Type*} {β : Type*} {s : set β} (f : α → β)
(h : set.bij_on f set.univ s) : α ≃ s :=
begin
have : function.bijective (λ (x : α), (⟨f x, begin exact h.maps_to (set.mem_univ x) end⟩ : s)),
{ split,
{ assume x y hxy,
apply h.inj_on (set.mem_univ x) (set.mem_univ y) (subtype.mk.inj hxy) },
{ assume x,
rcases h.surj_on x.2 with ⟨y, hy⟩,
exact ⟨y, subtype.eq hy.2⟩ } },
exact equiv.of_bijective _ this
end
/-- The composition of an updated function with an equiv on a subset can be expressed as an
updated function. -/
lemma dite_comp_equiv_update {α : Type*} {β : Type*} {γ : Type*} {s : set α} (e : β ≃ s)
(v : β → γ) (w : α → γ) (j : β) (x : γ) [decidable_eq β] [decidable_eq α]
[∀ j, decidable (j ∈ s)] :
(λ (i : α), if h : i ∈ s then (function.update v j x) (e.symm ⟨i, h⟩) else w i) =
function.update (λ (i : α), if h : i ∈ s then v (e.symm ⟨i, h⟩) else w i) (e j) x :=
begin
ext i,
by_cases h : i ∈ s,
{ simp only [h, dif_pos],
have A : e.symm ⟨i, h⟩ = j ↔ i = e j,
by { rw equiv.symm_apply_eq, exact subtype.ext_iff_val },
by_cases h' : i = e j,
{ rw [A.2 h', h'], simp },
{ have : ¬ e.symm ⟨i, h⟩ = j, by simpa [← A] using h',
simp [h, h', this] } },
{ have : i ≠ e j,
by { contrapose! h, have : (e j : α) ∈ s := (e j).2, rwa ← h at this },
simp [h, this] }
end
|
39e9c541ad08767f3e39f0bb46134172ba25f4e4 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/group_theory/group_action/fixing_subgroup.lean | 3f60d952629eeed7a8eacacf0d905bae49ff1030 | [
"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 | 5,593 | lean | /-
Copyright (c) 2022 Antoine Chambert-Loir. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Antoine Chambert-Loir
-/
import group_theory.subgroup.actions
import group_theory.group_action.basic
/-!
# Fixing submonoid, fixing subgroup of an action
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
In the presence of of an action of a monoid or a group,
this file defines the fixing submonoid or the fixing subgroup,
and relates it to the set of fixed points via a Galois connection.
## Main definitions
* `fixing_submonoid M s` : in the presence of `mul_action M α` (with `monoid M`)
it is the `submonoid M` consisting of elements which fix `s : set α` pointwise.
* `fixing_submonoid_fixed_points_gc M α` is the `galois_connection`
that relates `fixing_submonoid` with `fixed_points`.
* `fixing_subgroup M s` : in the presence of `mul_action M α` (with `group M`)
it is the `subgroup M` consisting of elements which fix `s : set α` pointwise.
* `fixing_subgroup_fixed_points_gc M α` is the `galois_connection`
that relates `fixing_subgroup` with `fixed_points`.
TODO :
* Maybe other lemmas are useful
* Treat semigroups ?
-/
section monoid
open mul_action
variables (M : Type*) {α : Type*} [monoid M] [mul_action M α]
/-- The submonoid fixing a set under a `mul_action`. -/
@[to_additive /-" The additive submonoid fixing a set under an `add_action`. "-/]
def fixing_submonoid (s : set α) : submonoid M :=
{ carrier := { ϕ : M | ∀ x : s, ϕ • (x : α) = x },
one_mem' := λ _, one_smul _ _,
mul_mem' := λ x y hx hy z, by rw [mul_smul, hy z, hx z], }
lemma mem_fixing_submonoid_iff {s : set α} {m : M} :
m ∈ fixing_submonoid M s ↔ ∀ y ∈ s, m • y = y :=
⟨λ hg y hy, hg ⟨y, hy⟩, λ h ⟨y, hy⟩, h y hy⟩
variable (α)
/-- The Galois connection between fixing submonoids and fixed points of a monoid action -/
theorem fixing_submonoid_fixed_points_gc : galois_connection
(order_dual.to_dual ∘ (fixing_submonoid M))
((λ P : submonoid M, (fixed_points P α)) ∘ order_dual.of_dual) :=
λ s P, ⟨λ h s hs p, h p.2 ⟨s, hs⟩, λ h p hp s, h s.2 ⟨p, hp⟩⟩
lemma fixing_submonoid_antitone : antitone (λ (s : set α), fixing_submonoid M s) :=
(fixing_submonoid_fixed_points_gc M α).monotone_l
lemma fixed_points_antitone :
antitone (λ (P : submonoid M), fixed_points P α) :=
(fixing_submonoid_fixed_points_gc M α).monotone_u.dual_left
/-- Fixing submonoid of union is intersection -/
lemma fixing_submonoid_union {s t : set α} :
fixing_submonoid M (s ∪ t) = fixing_submonoid M s ⊓ fixing_submonoid M t :=
(fixing_submonoid_fixed_points_gc M α).l_sup
/-- Fixing submonoid of Union is intersection -/
lemma fixing_submonoid_Union {ι : Sort*} {s : ι → set α} :
fixing_submonoid M (⋃ i, s i) = ⨅ i, fixing_submonoid M (s i) :=
(fixing_submonoid_fixed_points_gc M α).l_supr
/-- Fixed points of sup of submonoids is intersection -/
lemma fixed_points_submonoid_sup {P Q : submonoid M} :
fixed_points ↥(P ⊔ Q) α = fixed_points P α ∩ fixed_points Q α :=
(fixing_submonoid_fixed_points_gc M α).u_inf
/-- Fixed points of supr of submonoids is intersection -/
lemma fixed_points_submonoid_supr {ι : Sort*} {P : ι → submonoid M} :
fixed_points ↥(supr P) α = ⋂ i, fixed_points (P i) α :=
(fixing_submonoid_fixed_points_gc M α).u_infi
end monoid
section group
open mul_action
variables (M : Type*) {α : Type*} [group M] [mul_action M α]
/-- The subgroup fixing a set under a `mul_action`. -/
@[to_additive /-" The additive subgroup fixing a set under an `add_action`. "-/]
def fixing_subgroup (s : set α) : subgroup M :=
{ inv_mem' := λ _ hx z, by rw [inv_smul_eq_iff, hx z],
..fixing_submonoid M s, }
lemma mem_fixing_subgroup_iff {s : set α} {m : M} :
m ∈ fixing_subgroup M s ↔ ∀ y ∈ s, m • y = y :=
⟨λ hg y hy, hg ⟨y, hy⟩, λ h ⟨y, hy⟩, h y hy⟩
variable (α)
/-- The Galois connection between fixing subgroups and fixed points of a group action -/
lemma fixing_subgroup_fixed_points_gc : galois_connection
(order_dual.to_dual ∘ fixing_subgroup M)
((λ P : subgroup M, fixed_points P α) ∘ order_dual.of_dual) :=
λ s P, ⟨λ h s hs p, h p.2 ⟨s, hs⟩, λ h p hp s, h s.2 ⟨p, hp⟩⟩
lemma fixing_subgroup_antitone : antitone (fixing_subgroup M : set α → subgroup M) :=
(fixing_subgroup_fixed_points_gc M α).monotone_l
lemma fixed_points_subgroup_antitone :
antitone (λ (P : subgroup M), fixed_points P α) :=
(fixing_subgroup_fixed_points_gc M α).monotone_u.dual_left
/-- Fixing subgroup of union is intersection -/
lemma fixing_subgroup_union {s t : set α} :
fixing_subgroup M (s ∪ t) = fixing_subgroup M s ⊓ fixing_subgroup M t :=
(fixing_subgroup_fixed_points_gc M α).l_sup
/-- Fixing subgroup of Union is intersection -/
lemma fixing_subgroup_Union {ι : Sort*} {s : ι → set α} :
fixing_subgroup M (⋃ i, s i) = ⨅ i, fixing_subgroup M (s i) :=
(fixing_subgroup_fixed_points_gc M α).l_supr
/-- Fixed points of sup of subgroups is intersection -/
lemma fixed_points_subgroup_sup {P Q : subgroup M} :
fixed_points ↥(P ⊔ Q) α = fixed_points P α ∩ fixed_points Q α :=
(fixing_subgroup_fixed_points_gc M α).u_inf
/-- Fixed points of supr of subgroups is intersection -/
lemma fixed_points_subgroup_supr {ι : Sort*} {P : ι → subgroup M} :
fixed_points ↥(supr P) α = ⋂ i, fixed_points (P i) α :=
(fixing_subgroup_fixed_points_gc M α).u_infi
end group
|
dc1c826220871007ac76073e527c846353d211dc | e00ea76a720126cf9f6d732ad6216b5b824d20a7 | /src/data/finset.lean | 172b3b99a6f98560ce34ac29ccbc46d9bcec851d | [
"Apache-2.0"
] | permissive | vaibhavkarve/mathlib | a574aaf68c0a431a47fa82ce0637f0f769826bfe | 17f8340912468f49bdc30acdb9a9fa02eeb0473a | refs/heads/master | 1,621,263,802,637 | 1,585,399,588,000 | 1,585,399,588,000 | 250,833,447 | 0 | 0 | Apache-2.0 | 1,585,410,341,000 | 1,585,410,341,000 | null | UTF-8 | Lean | false | false | 112,156 | 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 algebra.order_functions
data.multiset data.sigma.basic data.set.lattice
tactic.monotonicity tactic.apply
open multiset subtype nat
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
instance decidable_mem' [decidable_eq α] (a : α) (s : finset α) :
decidable (a ∈ (↑s : set α)) := s.decidable_mem _
/-! ### extensionality -/
theorem ext {s₁ s₂ : finset α} : s₁ = s₂ ↔ ∀ a, a ∈ s₁ ↔ a ∈ s₂ :=
val_inj.symm.trans $ nodup_ext s₁.2 s₂.2
@[ext]
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
lemma to_set_injective {α} : function.injective (finset.to_set : finset α → set α) :=
λ s t, coe_inj.1
/-! ### 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 superset.trans {s₁ s₂ s₃ : finset α} : s₁ ⊇ s₂ → s₂ ⊇ s₃ → s₁ ⊇ s₃ :=
λ h' h, subset.trans h h'
-- TODO: these should be global attributes, but this will require fixing other files
local attribute [trans] subset.trans superset.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_def, 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
/-! ### Nonempty -/
/-- The property `s.nonempty` expresses the fact that the finset `s` is not empty. It should be used
in theorem assumptions instead of `∃ x, x ∈ s` or `s ≠ ∅` as it gives access to a nice API thanks
to the dot notation. -/
protected def nonempty (s : finset α) : Prop := ∃ x:α, x ∈ s
@[elim_cast] lemma coe_nonempty {s : finset α} : (↑s:set α).nonempty ↔ s.nonempty := iff.rfl
lemma nonempty.bex {s : finset α} (h : s.nonempty) : ∃ x:α, x ∈ s := h
lemma nonempty.mono {s t : finset α} (hst : s ⊆ t) (hs : s.nonempty) : t.nonempty :=
set.nonempty.mono hst hs
/-! ### empty -/
/-- The empty finset -/
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 nonempty_of_ne_empty {s : finset α} (h : s ≠ ∅) : s.nonempty :=
exists_mem_of_ne_zero (mt val_eq_zero.1 h)
theorem nonempty_iff_ne_empty {s : finset α} : s.nonempty ↔ s ≠ ∅ :=
⟨λ ⟨a, ha⟩, ne_empty_of_mem ha, nonempty_of_ne_empty⟩
theorem eq_empty_or_nonempty (s : finset α) : s = ∅ ∨ s.nonempty :=
classical.by_cases or.inl (λ h, or.inr (nonempty_of_ne_empty h))
@[simp] lemma coe_empty : ↑(∅ : finset α) = (∅ : set α) := rfl
/--
`finset.singleton a` is the set `{a}` containing `a` and nothing else.
This differs from `singleton a` in that it does not require a `decidable_eq` instance for `α`.
-/
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
lemma eq_singleton_iff_unique_mem {s : finset α} {a : α} :
s = finset.singleton a ↔ a ∈ s ∧ ∀ x ∈ s, x = a :=
begin
split; intro t,
rw t,
refine ⟨finset.mem_singleton_self _, λ _, finset.mem_singleton.1⟩,
ext, rw finset.mem_singleton,
refine ⟨t.right _, λ r, r.symm ▸ t.left⟩
end
lemma singleton_iff_unique_mem (s : finset α) : (∃ a, s = finset.singleton a) ↔ ∃! a, a ∈ s :=
by simp only [eq_singleton_iff_unique_mem, exists_unique]
@[simp] lemma singleton_subset_iff {s : finset α} {a : α} :
singleton a ⊆ s ↔ a ∈ s :=
set.singleton_subset_iff
/-! ### 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⟩⟩
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)
lemma ne_insert_of_not_mem (s t : finset α) {a : α} (h : a ∉ s) :
s ≠ insert a t :=
by { contrapose! h, simp [h] }
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 (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
/--
To prove a proposition about an arbitrary `finset α`,
it suffices to prove it for the empty `finset`,
and to show that if it holds for some `finset α`,
then it holds for the `finset` obtained by inserting a new element.
-/
@[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 : α) : {a} = ι a := rfl
theorem insert_empty_eq_singleton (a : α) : {a} = ι a := rfl
theorem insert_singleton_self_eq (a : α) : ({a, a} : finset α) = ι a :=
insert_eq_of_mem $ mem_singleton_self _
@[simp] theorem insert_singleton_self_eq' {a : α} : insert a (ι a) = ι a :=
insert_singleton_self_eq _
/-! ### 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 _
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₂)]
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]
@[simp] lemma union_eq_left_iff_subset {s t : finset α} :
s ∪ t = s ↔ t ⊆ s :=
begin
split,
{ assume h,
have : t ⊆ s ∪ t := subset_union_right _ _,
rwa h at this },
{ assume h,
exact subset.antisymm (union_subset (subset.refl _) h) (subset_union_left _ _) }
end
@[simp] lemma left_eq_union_iff_subset {s t : finset α} :
s = s ∪ t ↔ t ⊆ s :=
by rw [← union_eq_left_iff_subset, eq_comm]
@[simp] lemma union_eq_right_iff_subset {s t : finset α} :
t ∪ s = s ↔ t ⊆ s :=
by rw [union_comm, union_eq_left_iff_subset]
@[simp] lemma right_eq_union_iff_subset {s t : finset α} :
s = t ∪ s ↔ t ⊆ s :=
by rw [← union_eq_right_iff_subset, eq_comm]
/-! ### 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 union_inter_cancel_left {s t : finset α} : (s ∪ t) ∩ s = s :=
by rw [← coe_inj, coe_inter, coe_union, set.union_inter_cancel_left]
@[simp] theorem union_inter_cancel_right {s t : finset α} : (s ∪ t) ∩ t = t :=
by rw [← coe_inj, coe_inter, coe_union, set.union_inter_cancel_right]
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]
theorem inter_left_comm (s₁ s₂ s₃ : finset α) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) :=
ext.2 $ λ _, by simp only [mem_inter, and.left_comm]
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]
@[mono]
lemma inter_subset_inter {x y s t : finset α} (h : x ⊆ y) (h' : s ⊆ t) : x ∩ s ⊆ y ∩ t :=
begin
intros a a_in,
rw finset.mem_inter at a_in ⊢,
exact ⟨h a_in.1, h' a_in.2⟩
end
lemma inter_subset_inter_right {x y s : finset α} (h : x ⊆ y) : x ∩ s ⊆ y ∩ s :=
finset.inter_subset_inter h (finset.subset.refl _)
lemma inter_subset_inter_left {x y s : finset α} (h : x ⊆ y) : s ∩ x ⊆ s ∩ y :=
finset.inter_subset_inter (finset.subset.refl _) 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 }
instance {α : Type*} [decidable_eq α] : semilattice_sup_bot (finset α) :=
{ ..finset.semilattice_inf_bot, ..finset.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 }
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
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)
theorem union_sdiff_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁ ∪ (s₂ \ s₁) = s₂ :=
(union_comm _ _).trans (sdiff_union_of_subset h)
theorem inter_sdiff (s t u : finset α) : s ∩ (t \ u) = s ∩ t \ u :=
by { ext x, simp [and_assoc] }
@[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 _ _)
@[simp] theorem sdiff_self (s₁ : finset α) : s₁ \ s₁ = ∅ :=
by ext; simp
theorem sdiff_inter_distrib_right (s₁ s₂ s₃ : finset α) : s₁ \ (s₂ ∩ s₃) = (s₁ \ s₂) ∪ (s₁ \ s₃) :=
by ext; simp only [and_or_distrib_left, mem_union, classical.not_and_distrib, mem_sdiff, mem_inter]
@[simp] theorem sdiff_inter_self_left (s₁ s₂ : finset α) : s₁ \ (s₁ ∩ s₂) = s₁ \ s₂ :=
by simp only [sdiff_inter_distrib_right, sdiff_self, empty_union]
@[simp] theorem sdiff_inter_self_right (s₁ s₂ : finset α) : s₁ \ (s₂ ∩ s₁) = s₁ \ s₂ :=
by simp only [sdiff_inter_distrib_right, sdiff_self, union_empty]
@[simp] theorem sdiff_empty {s₁ : finset α} : s₁ \ ∅ = s₁ :=
ext.2 (by simp)
@[mono]
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₂)
theorem sdiff_subset_self {s₁ s₂ : finset α} : s₁ \ s₂ ⊆ s₁ :=
suffices s₁ \ s₂ ⊆ s₁ \ ∅, by simpa [sdiff_empty] using this,
sdiff_subset_sdiff (subset.refl _) (empty_subset _)
@[simp] lemma coe_sdiff (s₁ s₂ : finset α) : ↑(s₁ \ s₂) = (↑s₁ \ ↑s₂ : set α) :=
set.ext $ λ _, mem_sdiff
@[simp] lemma to_set_sdiff (s t : finset α) : (s \ t).to_set = s.to_set \ t.to_set :=
by apply finset.coe_sdiff
@[simp] theorem union_sdiff_self_eq_union {s t : finset α} : s ∪ (t \ s) = s ∪ t :=
ext.2 $ λ a, by simp only [mem_union, mem_sdiff, or_iff_not_imp_left,
imp_and_distrib, and_iff_left id]
@[simp] theorem sdiff_union_self_eq_union {s t : finset α} : (s \ t) ∪ t = s ∪ t :=
by rw [union_comm, union_sdiff_self_eq_union, union_comm]
lemma union_sdiff_symm {s t : finset α} : s ∪ (t \ s) = t ∪ (s \ t) :=
by rw [union_sdiff_self_eq_union, union_sdiff_self_eq_union, union_comm]
lemma sdiff_eq_empty_iff_subset {s t : finset α} : s \ t = ∅ ↔ s ⊆ t :=
by rw [subset_iff, ext]; simp
@[simp] lemma empty_sdiff (s : finset α) : ∅ \ s = ∅ :=
by { rw sdiff_eq_empty_iff_subset, exact empty_subset _ }
lemma insert_sdiff_of_not_mem (s : finset α) {t : finset α} {x : α} (h : x ∉ t) :
(insert x s) \ t = insert x (s \ t) :=
begin
rw [← coe_inj, coe_insert, coe_sdiff, coe_sdiff, coe_insert],
exact set.insert_diff_of_not_mem ↑s h
end
lemma insert_sdiff_of_mem (s : finset α) {t : finset α} {x : α} (h : x ∈ t) :
(insert x s) \ t = s \ t :=
begin
rw [← coe_inj, coe_sdiff, coe_sdiff, coe_insert],
exact set.insert_diff_of_mem ↑s h
end
@[simp] lemma sdiff_subset (s t : finset α) : s \ t ⊆ s :=
by simp [subset_iff, mem_sdiff] {contextual := tt}
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
/-! ### piecewise -/
section piecewise
/-- `s.piecewise f g` is the function equal to `f` on the finset `s`, and to `g` on its complement. -/
def piecewise {α : Type*} {δ : α → Sort*} (s : finset α) (f g : Πi, δ i) [∀j, decidable (j ∈ s)] :
Πi, δ i :=
λi, if i ∈ s then f i else g i
variables {δ : α → Sort*} (s : finset α) (f g : Πi, δ i)
@[simp] lemma piecewise_insert_self [decidable_eq α] {j : α} [∀i, decidable (i ∈ insert j s)] :
(insert j s).piecewise f g j = f j :=
by simp [piecewise]
@[simp] lemma piecewise_empty [∀i : α, decidable (i ∈ (∅ : finset α))] : piecewise ∅ f g = g :=
by { ext i, simp [piecewise] }
variable [∀j, decidable (j ∈ s)]
@[elim_cast] lemma piecewise_coe [∀j, decidable (j ∈ (↑s : set α))] :
(↑s : set α).piecewise f g = s.piecewise f g :=
by { ext, congr }
@[simp, priority 980]
lemma piecewise_eq_of_mem {i : α} (hi : i ∈ s) : s.piecewise f g i = f i :=
by simp [piecewise, hi]
@[simp, priority 980]
lemma piecewise_eq_of_not_mem {i : α} (hi : i ∉ s) : s.piecewise f g i = g i :=
by simp [piecewise, hi]
@[simp, priority 990]
lemma piecewise_insert_of_ne [decidable_eq α] {i j : α} [∀i, decidable (i ∈ insert j s)]
(h : i ≠ j) : (insert j s).piecewise f g i = s.piecewise f g i :=
by { simp [piecewise, h], congr }
lemma piecewise_insert [decidable_eq α] (j : α) [∀i, decidable (i ∈ insert j s)] :
(insert j s).piecewise f g = function.update (s.piecewise f g) j (f j) :=
begin
classical,
rw [← piecewise_coe, ← piecewise_coe, ← set.piecewise_insert, ← coe_insert j s],
congr
end
lemma update_eq_piecewise {β : Type*} [decidable_eq α] (f : α → β) (i : α) (v : β) :
function.update f i v = piecewise (singleton i) (λj, v) f :=
begin
ext j,
by_cases h : j = i,
{ rw [h], simp },
{ simp [h] }
end
end piecewise
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
lemma filter_empty : filter p ∅ = ∅ :=
subset_empty.1 $ filter_subset _
lemma filter_subset_filter {s t : finset α} (h : s ⊆ t) : s.filter p ⊆ t.filter p :=
assume a ha, mem_filter.2 ⟨h (mem_filter.1 ha).1, (mem_filter.1 ha).2⟩
@[simp] lemma coe_filter (s : finset α) : ↑(s.filter p) = ({x ∈ ↑s | p x} : set α) :=
set.ext $ λ _, mem_filter
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_union_right (p q : α → Prop) [decidable_pred p] [decidable_pred q] (s : finset α) :
s.filter p ∪ s.filter q = s.filter (λx, p x ∨ q x) :=
ext.2 $ λ x, by simp only [mem_filter, mem_union, and_or_distrib_left.symm]
lemma filter_mem_eq_inter {s t : finset α} : s.filter (λ i, i ∈ t) = s ∩ t :=
ext' $ λ i, by rw [mem_filter, mem_inter]
theorem filter_inter {s t : finset α} : filter p s ∩ t = filter p (s ∩ t) :=
by { ext, simp only [mem_inter, mem_filter, and.right_comm] }
theorem inter_filter {s t : finset α} : s ∩ filter p t = filter p (s ∩ t) :=
by rw [inter_comm, filter_inter, inter_comm]
theorem filter_insert (a : α) (s : finset α) :
filter p (insert a s) = if p a then insert a (filter p s) else (filter p s) :=
by { ext x, simp, split_ifs with h; by_cases h' : x = a; simp [h, h'] }
theorem filter_singleton (a : α) : filter p (singleton a) = if p a then singleton a else ∅ :=
by { ext x, simp, split_ifs with h; by_cases h' : x = a; simp [h, h'] }
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 sdiff_eq_self (s₁ s₂ : finset α) :
s₁ \ s₂ = s₁ ↔ s₁ ∩ s₂ ⊆ ∅ :=
by { simp [subset.antisymm_iff,sdiff_subset_self],
split; intro h,
{ transitivity' ((s₁ \ s₂) ∩ s₂), mono, simp },
{ calc s₁ \ s₂
⊇ s₁ \ (s₁ ∩ s₂) : by simp [(⊇)]
... ⊇ s₁ \ ∅ : by mono using [(⊇)]
... ⊇ s₁ : by simp [(⊇)] } }
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]
lemma subset_union_elim {s : finset α} {t₁ t₂ : set α} [decidable_pred (∈ t₁)] (h : ↑s ⊆ t₁ ∪ t₂) :
∃s₁ s₂ : finset α, s₁ ∪ s₂ = s ∧ ↑s₁ ⊆ t₁ ∧ ↑s₂ ⊆ t₂ \ t₁ :=
begin
refine ⟨s.filter (∈ t₁), s.filter (∉ t₁), _, _ , _⟩,
{ simp [filter_union_right, classical.or_not] },
{ intro x, simp },
{ intro x, simp, intros hx hx₂, refine ⟨or.resolve_left (h hx) hx₂, hx₂⟩ }
end
/- We can simplify an application of filter where the decidability is inferred in "the wrong way" -/
@[simp] lemma filter_congr_decidable {α} (s : finset α) (p : α → Prop) (h : decidable_pred p)
[decidable_pred p] : @filter α p h s = s.filter p :=
by congr
section classical
open_locale classical
/-- The following instance allows us to write `{ x ∈ s | p x }` for `finset.filter s p`.
Since the former notation requires us to define this for all propositions `p`, and `finset.filter`
only works for decidable propositions, the notation `{ x ∈ s | p x }` is only compatible with
classical logic because it uses `classical.prop_decidable`.
We don't want to redo all lemmas of `finset.filter` for `has_sep.sep`, so we make sure that `simp`
unfolds the notation `{ x ∈ s | p x }` to `finset.filter s p`. If `p` happens to be decidable, the
simp-lemma `filter_congr_decidable` will make sure that `finset.filter` uses the right instance
for decidability.
-/
noncomputable instance {α : Type*} : has_sep α (finset α) := ⟨λ p x, x.filter p⟩
@[simp] lemma sep_def {α : Type*} (s : finset α) (p : α → Prop) : {x ∈ s | p x} = s.filter p := rfl
end classical
/--
After filtering out everything that does not equal a given value, at most that value remains.
This is equivalent to `filter_eq'` with the equality the other way.
-/
-- This is not a good simp lemma, as it would prevent `finset.mem_filter` from firing
-- on, e.g. `x ∈ s.filter(eq b)`.
lemma filter_eq [decidable_eq β] (s : finset β) (b : β) :
s.filter(eq b) = ite (b ∈ s) {b} ∅ :=
begin
split_ifs,
{ ext,
simp only [mem_filter, insert_empty_eq_singleton, mem_singleton],
exact ⟨λ h, h.2.symm, by { rintro ⟨h⟩, exact ⟨h, rfl⟩, }⟩ },
{ ext,
simp only [mem_filter, not_and, iff_false, not_mem_empty],
rintros m ⟨e⟩, exact h m, }
end
/--
After filtering out everything that does not equal a given value, at most that value remains.
This is equivalent to `filter_eq` with the equality the other way.
-/
lemma filter_eq' [decidable_eq β] (s : finset β) (b : β) :
s.filter (λ a, a = b) = ite (b ∈ s) {b} ∅ :=
trans (filter_congr (λ _ _, ⟨eq.symm, eq.symm⟩)) (filter_eq s b)
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
theorem range_add_one : range (n + 1) = insert n (range n) :=
range_succ
@[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 range_mono : monotone range := λ _ _, range_subset.2
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
@[simp] lemma to_finset_smul (s : multiset α) :
∀(n : ℕ) (hn : n ≠ 0), (add_monoid.smul n s).to_finset = s.to_finset
| 0 h := by contradiction
| (n+1) h :=
begin
by_cases n = 0,
{ rw [h, zero_add, add_monoid.one_smul] },
{ rw [add_monoid.add_smul, to_finset_add, add_monoid.one_smul, to_finset_smul n h,
finset.union_idempotent] }
end
@[simp] lemma to_finset_inter (s t : multiset α) :
to_finset (s ∩ t) = to_finset s ∩ to_finset t :=
finset.ext' $ by simp
theorem to_finset_eq_empty {m : multiset α} : m.to_finset = ∅ ↔ m = 0 :=
finset.val_inj.symm.trans multiset.erase_dup_eq_zero
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
/-! ### map -/
section map
open function
/-- When `f` is an embedding of `α` in `β` and `s` is a finset in `α`, then `s.map f` is the image
finset in `β`. The embedding condition guarantees that there are no duplicates in the image. -/
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 : α ↪ β) : (∅ : 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
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]
/-- Associate to an embedding `f` from `α` to `β` the embedding that maps a finset to its image
under `f`. -/
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
lemma range_add_one' (n : ℕ) :
range (n + 1) = insert 0 ((range n).map ⟨λi, i + 1, assume i j, nat.succ_inj⟩) :=
by ext (⟨⟩ | ⟨n⟩); simp [nat.succ_eq_add_one, nat.zero_lt_succ n]
/-! ### image -/
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]
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
lemma nonempty.image (h : s.nonempty) (f : α → β) : (s.image f).nonempty :=
let ⟨a, ha⟩ := h in ⟨f a, mem_image_of_mem f ha⟩
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]
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_mono (f : α → β) : monotone (finset.image f) := λ _ _, image_subset_image
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 (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 {s : finset α} (h : s.nonempty) (b : β) : s.image (λa, b) = singleton b :=
ext.2 $ assume b', by simp only [mem_image, exists_prop, exists_and_distrib_right,
h.bex, true_and, mem_singleton, eq_comm]
/-- Given a finset `s` and a predicate `p`, `s.subtype p` is the finset of `subtype p` whose
elements belong to `s`. -/
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]
lemma subset_image_iff [decidable_eq α] {f : α → β}
{s : finset β} {t : set α} : ↑s ⊆ f '' t ↔ ∃s' : finset α, ↑s' ⊆ t ∧ s'.image f = s :=
begin
split, swap,
{ rintro ⟨s, hs, rfl⟩, rw [coe_image], exact set.image_subset f hs },
intro h, induction s using finset.induction with a s has ih h,
{ exact ⟨∅, set.empty_subset _, finset.image_empty _⟩ },
rw [finset.coe_insert, set.insert_subset] at h,
rcases ih h.2 with ⟨s', hst, hsi⟩,
rcases h.1 with ⟨x, hxt, rfl⟩,
refine ⟨insert x s', _, _⟩,
{ rw [finset.coe_insert, set.insert_subset], exact ⟨hxt, hst⟩ },
rw [finset.image_insert, hsi]
end
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.nonempty :=
pos_iff_ne_zero.trans $ (not_congr card_eq_zero).trans nonempty_iff_ne_empty.symm
theorem card_ne_zero_of_mem {s : finset α} {a : α} (h : a ∈ s) : card s ≠ 0 :=
(not_congr card_eq_zero).2 (ne_empty_of_mem h)
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
theorem card_erase_lt_of_mem [decidable_eq α] {a : α} {s : finset α} : a ∈ s → card (erase s a) < card s := card_erase_lt_of_mem
theorem card_erase_le [decidable_eq α] {a : α} {s : finset α} : card (erase s a) ≤ card s := card_erase_le
@[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
@[simp] lemma card_map {α β} [decidable_eq β] (f : α ↪ β) {s : finset α} : (s.map f).card = s.card :=
by rw [map_eq_image, card_image_of_injective]; exact f.2
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 α} {n : ℕ} :
s.card = n + 1 ↔ (∃a t, a ∉ t ∧ insert a t = s ∧ card t = n) :=
iff.intro
(assume eq,
have 0 < card s, from eq.symm ▸ nat.zero_lt_succ _,
let ⟨a, has⟩ := 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 {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 β] {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₂)
/-- Suppose that, given objects defined on all strict subsets of any finset `s`, one knows how to
define an object on `s`. Then one can inductively define an object on all finsets, starting from
the empty set and iterating. This can be used either to define data, or to prove properties. -/
@[elab_as_eliminator] def 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 r har, by by_cases a ∈ s; simp *; cc
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
open function
lemma inj_on_of_surj_on_of_card_le {s : finset α} {t : finset β}
(f : Π a ∈ s, β) (hf : ∀ a ha, f a ha ∈ t)
(hsurj : ∀ b ∈ t, ∃ a ha, b = f a ha)
(hst : card s ≤ card t)
⦃a₁ a₂⦄ (ha₁ : a₁ ∈ s) (ha₂ : a₂ ∈ s)
(ha₁a₂: f a₁ ha₁ = f a₂ ha₂) : a₁ = a₂ :=
by haveI : inhabited {x // x ∈ s} := ⟨⟨a₁, ha₁⟩⟩; exact
let f' : {x // x ∈ s} → {x // x ∈ t} := λ x, ⟨f x.1 x.2, hf x.1 x.2⟩ in
let g : {x // x ∈ t} → {x // x ∈ s} :=
@surj_inv _ _ f'
(λ x, let ⟨y, hy₁, hy₂⟩ := hsurj x.1 x.2 in ⟨⟨y, hy₁⟩, subtype.eq hy₂.symm⟩) in
have hg : injective g, from function.injective_surj_inv _,
have hsg : surjective g, from λ x,
let ⟨y, hy⟩ := surj_on_of_inj_on_of_card_le (λ (x : {x // x ∈ t}) (hx : x ∈ t.attach), g x)
(λ x _, show (g x) ∈ s.attach, from mem_attach _ _)
(λ x y _ _ hxy, hg hxy) (by simpa) x (mem_attach _ _) in
⟨y, hy.snd.symm⟩,
have hif : injective f',
from injective_of_has_left_inverse
⟨g, left_inverse_of_surjective_of_right_inverse hsg
(right_inverse_surj_inv _)⟩,
subtype.ext.1 (@hif ⟨a₁, ha₁⟩ ⟨a₂, ha₂⟩ (subtype.eq ha₁a₂))
end card
/-! ### bind -/
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 bind_inter (s : finset α) (f : α → finset β) (t : finset β) :
s.bind f ∩ t = s.bind (λ x, f x ∩ t) :=
begin
ext x,
simp only [mem_bind, mem_inter],
tauto
end
theorem inter_bind (t : finset β) (s : finset α) (f : α → finset β) :
t ∩ s.bind f = s.bind (λ x, t ∩ f x) :=
by rw [inter_comm, bind_inter]; simp [inter_comm]
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
/-! ### prod-/
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
/-! ### sigma -/
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
/-! ### pi -/
section pi
variables {δ : α → Type*} [decidable_eq α]
/-- Given a finset `s` of `α` and for all `a : α` a finset `t a` of `δ a`, then one can define the
finset `s.pi t` of all functions defined on elements of `s` taking values in `t a` for `a ∈ s`.
Note that the elements of `s.pi t` are only partially defined, on `s`. -/
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 _ _ _
/-- The empty dependent product function, defined on the emptyset. The assumption `a ∈ ∅` is never
satisfied. -/
def pi.empty (β : α → Sort*) (a : α) (h : a ∈ (∅ : finset α)) : β a :=
multiset.pi.empty β a h
/-- Given a function `f` defined on a finset `s`, define a new function on the finset `s ∪ {a}`,
equal to `f` on `s` and sending `a` to a given value `b`. This function is denoted
`s.pi.cons a b f`. If `a` already belongs to `s`, the new function takes the value `b` at `a`
anyway. -/
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
lemma pi_subset {s : finset α} (t₁ t₂ : Πa, finset (δ a)) (h : ∀ a ∈ s, t₁ a ⊆ t₂ a) :
s.pi t₁ ⊆ s.pi t₂ :=
λ g hg, mem_pi.2 $ λ a ha, h a ha (mem_pi.mp hg a ha)
end pi
/-! ### powerset -/
section powerset
/-- When `s` is a finset, `s.powerset` is the finset of all subsets of `s` (seen as finsets). -/
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] lemma powerset_empty [decidable_eq α] : finset.powerset (∅ : finset α) = {∅} := rfl
@[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)
lemma not_mem_of_mem_powerset_of_not_mem {s t : finset α} {a : α}
(ht : t ∈ s.powerset) (h : a ∉ s) : a ∉ t :=
by { apply mt _ h, apply mem_powerset.1 ht }
lemma powerset_insert [decidable_eq α] (s : finset α) (a : α) :
powerset (insert a s) = s.powerset ∪ s.powerset.image (insert a) :=
begin
ext t,
simp only [exists_prop, mem_powerset, mem_image, mem_union, subset_insert_iff],
by_cases h : a ∈ t,
{ split,
{ exact λH, or.inr ⟨_, H, insert_erase h⟩ },
{ intros H,
cases H,
{ exact subset.trans (erase_subset a t) H },
{ rcases H with ⟨u, hu⟩,
rw ← hu.2,
exact subset.trans (erase_insert_subset a u) hu.1 } } },
{ have : ¬ ∃ (u : finset α), u ⊆ s ∧ insert a u = t,
by simp [ne.symm (ne_insert_of_not_mem _ _ h)],
simp [finset.erase_eq_of_not_mem h, this] }
end
end powerset
section powerset_len
/-- Given an integer `n` and a finset `s`, then `powerset_len n s` is the finset of subsets of `s`
of cardinality `n`.-/
def powerset_len (n : ℕ) (s : finset α) : finset (finset α) :=
⟨(s.1.powerset_len n).pmap finset.mk
(λ t h, nodup_of_le (mem_powerset_len.1 h).1 s.2),
nodup_pmap (λ a ha b hb, congr_arg finset.val)
(nodup_powerset_len s.2)⟩
theorem mem_powerset_len {n} {s t : finset α} :
s ∈ powerset_len n t ↔ s ⊆ t ∧ card s = n :=
by cases s; simp [powerset_len, val_le_iff.symm]; refl
@[simp] theorem powerset_len_mono {n} {s t : finset α} (h : s ⊆ t) :
powerset_len n s ⊆ powerset_len n t :=
λ u h', mem_powerset_len.2 $
and.imp (λ h₂, subset.trans h₂ h) id (mem_powerset_len.1 h')
@[simp] theorem card_powerset_len (n : ℕ) (s : finset α) :
card (powerset_len n s) = nat.choose (card s) n :=
(card_pmap _ _ _).trans (card_powerset_len n s.1)
end powerset_len
/-! ### fold -/
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_map {g : γ ↪ α} {s : finset γ} :
(s.map g).fold op b f = s.fold op b (f ∘ g) :=
by simp only [fold, map, multiset.map_map]
@[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]
lemma fold_op_rel_iff_and [decidable_eq α]
{r : β → β → Prop} (hr : ∀ {x y z}, r x (op y z) ↔ (r x y ∧ r x z)) {c : β} :
r c (s.fold op b f) ↔ (r c b ∧ ∀ x∈s, r c (f x)) :=
begin
apply finset.induction_on s, { simp },
clear s, intros a s ha IH,
rw [finset.fold_insert ha, hr, IH, ← and_assoc, and_comm (r c (f a)), and_assoc],
apply and_congr iff.rfl,
split,
{ rintro ⟨h₁, h₂⟩, intros b hb, rw finset.mem_insert at hb,
rcases hb with rfl|hb; solve_by_elim },
{ intro h, split,
{ exact h a (finset.mem_insert_self _ _), },
{ intros b hb, apply h b, rw finset.mem_insert, right, exact hb } }
end
lemma fold_op_rel_iff_or [decidable_eq α]
{r : β → β → Prop} (hr : ∀ {x y z}, r x (op y z) ↔ (r x y ∨ r x z)) {c : β} :
r c (s.fold op b f) ↔ (r c b ∨ ∃ x∈s, r c (f x)) :=
begin
apply finset.induction_on s, { simp },
clear s, intros a s ha IH,
rw [finset.fold_insert ha, hr, IH, ← or_assoc, or_comm (r c (f a)), or_assoc],
apply or_congr iff.rfl,
split,
{ rintro (h₁|⟨x, hx, h₂⟩),
{ use a, simp [h₁] },
{ refine ⟨x, by simp [hx], h₂⟩ } },
{ rintro ⟨x, hx, h⟩,
rw mem_insert at hx, cases hx,
{ left, rwa hx at h },
{ right, exact ⟨x, hx, h⟩ } }
end
omit hc ha
section order
variables [decidable_eq α] [decidable_linear_order β] (c : β)
lemma le_fold_min : c ≤ s.fold min b f ↔ (c ≤ b ∧ ∀ x∈s, c ≤ f x) :=
fold_op_rel_iff_and $ λ x y z, le_min_iff
lemma fold_min_le : s.fold min b f ≤ c ↔ (b ≤ c ∨ ∃ x∈s, f x ≤ c) :=
begin
show _ ≥ _ ↔ _,
apply fold_op_rel_iff_or,
intros x y z,
show _ ≤ _ ↔ _,
exact min_le_iff
end
lemma lt_fold_min : c < s.fold min b f ↔ (c < b ∧ ∀ x∈s, c < f x) :=
fold_op_rel_iff_and $ λ x y z, lt_min_iff
lemma fold_min_lt : s.fold min b f < c ↔ (b < c ∨ ∃ x∈s, f x < c) :=
begin
show _ > _ ↔ _,
apply fold_op_rel_iff_or,
intros x y z,
show _ < _ ↔ _,
exact min_lt_iff
end
lemma fold_max_le : s.fold max b f ≤ c ↔ (b ≤ c ∧ ∀ x∈s, f x ≤ c) :=
begin
show _ ≥ _ ↔ _,
apply fold_op_rel_iff_and,
intros x y z,
show _ ≤ _ ↔ _,
exact max_le_iff
end
lemma le_fold_max : c ≤ s.fold max b f ↔ (c ≤ b ∨ ∃ x∈s, c ≤ f x) :=
fold_op_rel_iff_or $ λ x y z, le_max_iff
lemma fold_max_lt : s.fold max b f < c ↔ (b < c ∧ ∀ x∈s, f x < c) :=
begin
show _ > _ ↔ _,
apply fold_op_rel_iff_and,
intros x y z,
show _ < _ ↔ _,
exact max_lt_iff
end
lemma lt_fold_max : c < s.fold max b f ↔ (c < b ∨ ∃ x∈s, c < f x) :=
fold_op_rel_iff_or $ λ x y z, lt_max_iff
end order
end fold
/-! ### sup -/
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' {b : β} : (singleton b).sup f = f b :=
sup_singleton
lemma sup_singleton [decidable_eq β] {b : β} : ({b} : finset β).sup f = f b :=
sup_singleton
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]
theorem sup_congr {f g : β → α} (hs : s₁ = s₂) (hfg : ∀a∈s₂, f a = g a) : s₁.sup f = s₂.sup g :=
by subst hs; exact finset.fold_congr hfg
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))
@[simp] 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)
@[simp] lemma sup_lt_iff [is_total α (≤)] {a : α} (ha : ⊥ < a) :
s.sup f < a ↔ (∀b ∈ s, f b < a) :=
by letI := classical.dec_eq β; from
⟨ λh b hb, lt_of_le_of_lt (le_sup hb) h,
finset.induction_on s (by simp [ha]) (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})
theorem subset_range_sup_succ (s : finset ℕ) : s ⊆ range (s.sup id).succ :=
λ n hn, mem_range.2 $ nat.lt_succ_of_le $ le_sup hn
theorem exists_nat_subset_range (s : finset ℕ) : ∃n : ℕ, s ⊆ range n :=
⟨_, s.subset_range_sup_succ⟩
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)
/-! ### inf -/
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' {b : β} : (singleton b).inf f = f b :=
inf_singleton
lemma inf_singleton [decidable_eq β] {b : β} : ({b} : finset β).inf f = f b :=
inf_singleton'
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]
theorem inf_congr {f g : β → α} (hs : s₁ = s₂) (hfg : ∀a∈s₂, f a = g a) : s₁.inf f = s₂.inf g :=
by subst hs; exact finset.fold_congr hfg
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 α]
/-- Let `s` be a finset in a linear order. Then `s.max` is the maximum of `s` if `s` is not empty,
and `none` otherwise. It belongs to `option α`. If you want to get an element of `α`, see
`s.max'`. -/
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
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_nonempty {s : finset α} (h : s.nonempty) : ∃ a, a ∈ s.max :=
let ⟨a, ha⟩ := h in max_of_mem ha
theorem max_eq_none {s : finset α} : s.max = none ↔ s = ∅ :=
⟨λ h, s.eq_empty_or_nonempty.elim id
(λ H, let ⟨a, ha⟩ := max_of_nonempty H 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
/-- Let `s` be a finset in a linear order. Then `s.min` is the minimum of `s` if `s` is not empty,
and `none` otherwise. It belongs to `option α`. If you want to get an element of `α`, see
`s.min'`. -/
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
theorem min_singleton {a : α} : finset.min {a} = some a := min_insert
@[simp] theorem min_singleton' {a : α} : finset.min (singleton a) = some a := min_singleton
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_nonempty {s : finset α} (h : s.nonempty) : ∃ a, a ∈ s.min :=
let ⟨a, ha⟩ := h in min_of_mem ha
theorem min_eq_none {s : finset α} : s.min = none ↔ s = ∅ :=
⟨λ h, s.eq_empty_or_nonempty.elim id
(λ H, let ⟨a, ha⟩ := min_of_nonempty H 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 min_le_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
lemma exists_min (s : finset β) (f : β → α) (h : s.nonempty) : ∃ x ∈ s, ∀ x' ∈ s, f x ≤ f x' :=
begin
cases min_of_nonempty (h.image f) with y hy,
rcases mem_image.mp (mem_of_min hy) with ⟨x, hx, rfl⟩,
exact ⟨x, hx, λ x' hx', min_le_of_mem (mem_image_of_mem f hx') hy⟩
end
/-- Given a nonempty finset `s` in a linear order `α `, then `s.min' h` is its minimum, as an
element of `α`, where `h` is a proof of nonemptiness. Without this assumption, use instead `s.min`,
taking values in `option α`. -/
def min' (s : finset α) (H : s.nonempty) : α :=
@option.get _ s.min $
let ⟨k, hk⟩ := H in
let ⟨b, hb⟩ := min_of_mem hk in by simp at hb; simp [hb]
/-- Given a nonempty finset `s` in a linear order `α `, then `s.max' h` is its maximum, as an
element of `α`, where `h` is a proof of nonemptiness. Without this assumption, use instead `s.max`,
taking values in `option α`. -/
def max' (s : finset α) (H : s.nonempty) : α :=
@option.get _ s.max $
let ⟨k, hk⟩ := H in
let ⟨b, hb⟩ := max_of_mem hk in by simp at hb; simp [hb]
variables (s : finset α) (H : s.nonempty)
theorem min'_mem : s.min' H ∈ s := mem_of_min $ by simp [min']
theorem min'_le (x) (H2 : x ∈ s) : s.min' H ≤ x := min_le_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 max_min
/-! ### sort -/
section sort
variables (r : α → α → Prop) [decidable_rel r]
[is_trans α r] [is_antisymm α r] [is_total α r]
/-- `sort s` constructs a sorted list from the unordered set `s`.
(Uses merge sort algorithm.) -/
def sort (s : finset α) : list α := sort r s.1
@[simp] theorem sort_sorted (s : finset α) : list.sorted r (sort r s) :=
sort_sorted _ _
@[simp] theorem sort_eq (s : finset α) : ↑(sort r s) = s.1 :=
sort_eq _ _
@[simp] theorem sort_nodup (s : finset α) : (sort r s).nodup :=
(by rw sort_eq; exact s.2 : @multiset.nodup α (sort r s))
@[simp] theorem sort_to_finset [decidable_eq α] (s : finset α) : (sort r s).to_finset = s :=
list.to_finset_eq (sort_nodup r s) ▸ eq_of_veq (sort_eq r s)
@[simp] theorem mem_sort {s : finset α} {a : α} : a ∈ sort r s ↔ a ∈ s :=
multiset.mem_sort _
@[simp] theorem length_sort {s : finset α} : (sort r s).length = s.card :=
multiset.length_sort _
end sort
section sort_linear_order
variables [decidable_linear_order α]
theorem sort_sorted_lt (s : finset α) :
list.sorted (<) (sort (≤) s) :=
(sort_sorted _ _).imp₂ (@lt_of_le_of_ne _ _) (sort_nodup _ _)
lemma sorted_zero_eq_min' (s : finset α) (h : 0 < (s.sort (≤)).length) (H : s.nonempty) :
(s.sort (≤)).nth_le 0 h = s.min' H :=
begin
let l := s.sort (≤),
apply le_antisymm,
{ have : s.min' H ∈ l := (finset.mem_sort (≤)).mpr (s.min'_mem H),
obtain ⟨i, i_lt, hi⟩ : ∃ i (hi : i < l.length), l.nth_le i hi = s.min' H :=
list.mem_iff_nth_le.1 this,
rw ← hi,
exact list.nth_le_of_sorted_of_le (s.sort_sorted (≤)) (nat.zero_le i) },
{ have : l.nth_le 0 h ∈ s := (finset.mem_sort (≤)).1 (list.nth_le_mem l 0 h),
exact s.min'_le H _ this }
end
lemma sorted_last_eq_max' (s : finset α) (h : (s.sort (≤)).length - 1 < (s.sort (≤)).length)
(H : s.nonempty) : (s.sort (≤)).nth_le ((s.sort (≤)).length - 1) h = s.max' H :=
begin
let l := s.sort (≤),
apply le_antisymm,
{ have : l.nth_le ((s.sort (≤)).length - 1) h ∈ s :=
(finset.mem_sort (≤)).1 (list.nth_le_mem l _ h),
exact s.le_max' H _ this },
{ have : s.max' H ∈ l := (finset.mem_sort (≤)).mpr (s.max'_mem H),
obtain ⟨i, i_lt, hi⟩ : ∃ i (hi : i < l.length), l.nth_le i hi = s.max' H :=
list.mem_iff_nth_le.1 this,
rw ← hi,
have : i ≤ l.length - 1 := nat.le_pred_of_lt i_lt,
exact list.nth_le_of_sorted_of_le (s.sort_sorted (≤)) (nat.le_pred_of_lt i_lt) },
end
/-- Given a finset `s` of cardinal `k` in a linear order `α`, the map `mono_of_fin s h`
is the increasing bijection between `fin k` and `s` as an `α`-valued map. Here, `h` is a proof that
the cardinality of `s` is `k`. We use this instead of a map `fin s.card → α` to avoid
casting issues in further uses of this function. -/
def mono_of_fin (s : finset α) {k : ℕ} (h : s.card = k) (i : fin k) : α :=
have A : (i : ℕ) < (s.sort (≤)).length, by simpa [h] using i.2,
(s.sort (≤)).nth_le i A
lemma bij_on_mono_of_fin (s : finset α) {k : ℕ} (h : s.card = k) :
set.bij_on (s.mono_of_fin h) set.univ ↑s :=
begin
have A : ∀ j, j ∈ s ↔ j ∈ (s.sort (≤)) := λ j, by simp,
apply set.bij_on.mk,
{ assume i hi,
simp only [mono_of_fin, set.mem_preimage, mem_coe, list.nth_le, A],
exact list.nth_le_mem _ _ _ },
{ refine (strict_mono.injective (λ i j hij, _)).inj_on _,
exact list.pairwise_iff_nth_le.1 s.sort_sorted_lt _ _ _ hij },
{ assume x hx,
simp only [mem_coe, A] at hx,
obtain ⟨i, il, hi⟩ : ∃ (i : ℕ) (h : i < (s.sort (≤)).length), (s.sort (≤)).nth_le i h = x :=
list.nth_le_of_mem hx,
simp [h] at il,
exact ⟨⟨i, il⟩, set.mem_univ _, hi⟩ }
end
/-- Given a finset `s` of cardinal `k` in a linear order `α`, the equiv `mono_equiv_of_fin s h`
is the increasing bijection between `fin k` and `s` as an `s`-valued map. Here, `h` is a proof that
the cardinality of `s` is `k`. We use this instead of a map `fin s.card → α` to avoid
casting issues in further uses of this function. -/
noncomputable def mono_equiv_of_fin (s : finset α) {k : ℕ} (h : s.card = k) :
fin k ≃ {x // x ∈ s} :=
(s.bij_on_mono_of_fin h).equiv _
end sort_linear_order
/-! ### disjoint -/
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]
lemma sdiff_disjoint {s t : finset α} : disjoint (t \ s) s :=
disjoint_left.2 $ assume a ha, (mem_sdiff.1 ha).2
lemma disjoint_sdiff {s t : finset α} : disjoint s (t \ s) :=
sdiff_disjoint.symm
lemma disjoint_bind_left {ι : Type*} [decidable_eq ι]
(s : finset ι) (f : ι → finset α) (t : finset α) :
disjoint (s.bind f) t ↔ (∀i∈s, disjoint (f i) t) :=
begin
refine s.induction _ _,
{ simp only [forall_mem_empty_iff, bind_empty, disjoint_empty_left] },
{ assume i s his ih,
simp only [disjoint_union_left, bind_insert, his, forall_mem_insert, ih] }
end
lemma disjoint_bind_right {ι : Type*} [decidable_eq ι]
(s : finset α) (t : finset ι) (f : ι → finset α) :
disjoint s (t.bind f) ↔ (∀i∈t, disjoint s (f i)) :=
by simpa only [disjoint.comm] using disjoint_bind_left t f s
@[simp] theorem card_disjoint_union {s t : finset α} (h : disjoint s t) :
card (s ∪ t) = card s + card t :=
by rw [← card_union_add_card_inter, disjoint_iff_inter_eq_empty.1 h, card_empty, add_zero]
theorem card_sdiff {s t : finset α} (h : s ⊆ t) : card (t \ s) = card t - card s :=
suffices card (t \ s) = card ((t \ s) ∪ s) - card s, by rwa sdiff_union_of_subset h at this,
by rw [card_disjoint_union sdiff_disjoint, nat.add_sub_cancel]
lemma disjoint_filter {s : finset α} {p q : α → Prop} [decidable_pred p] [decidable_pred q] :
disjoint (s.filter p) (s.filter q) ↔ (∀ x ∈ s, p x → ¬ q x) :=
by split; simp [disjoint_left] {contextual := tt}
lemma pi_disjoint_of_disjoint {δ : α → Type*} [∀a, decidable_eq (δ a)]
{s : finset α} [decidable_eq (Πa∈s, δ a)]
(t₁ t₂ : Πa, finset (δ a)) {a : α} (ha : a ∈ s) (h : disjoint (t₁ a) (t₂ a)) :
disjoint (s.pi t₁) (s.pi t₂) :=
disjoint_iff_ne.2 $ λ f₁ hf₁ f₂ hf₂ eq₁₂,
disjoint_iff_ne.1 h (f₁ a ha) (mem_pi.mp hf₁ a ha) (f₂ a ha) (mem_pi.mp hf₂ a ha)
$ congr_fun (congr_fun eq₁₂ a) ha
end disjoint
instance [has_repr α] : has_repr (finset α) := ⟨λ s, repr s.1⟩
/-- Given a finset `s` of `ℕ` contained in `{0,..., n-1}`, the corresponding finset in `fin n`
is `s.attach_fin h` where `h` is a proof that all elements of `s` are less than `n`. -/
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 _ _ _
/-! ### choose -/
section choose
variables (p : α → Prop) [decidable_pred p] (l : finset α)
/-- Given a finset `l` and a predicate `p`, associate to a proof that there is a unique element of
`l` satisfying `p` this unique element, as an element of the corresponding subtype. -/
def choose_x (hp : (∃! a, a ∈ l ∧ p a)) : { a // a ∈ l ∧ p a } :=
multiset.choose_x p l.val hp
/-- Given a finset `l` and a predicate `p`, associate to a proof that there is a unique element of
`l` satisfying `p` this unique element, as an element of the ambient type. -/
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 {α} : 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 α]
end decidable_linear_order
/-! ### intervals -/
/- Ico (a closed open interval) -/
variables {n m l : ℕ}
/-- `Ico n m` is the set of natural numbers `n ≤ k < m`. -/
def Ico (n m : ℕ) : finset ℕ := ⟨_, Ico.nodup n m⟩
namespace Ico
@[simp] theorem val (n m : ℕ) : (Ico n m).1 = multiset.Ico n m := rfl
@[simp] theorem to_finset (n m : ℕ) : (multiset.Ico n m).to_finset = Ico n m :=
(multiset.to_finset_eq _).symm
theorem image_add (n m k : ℕ) : (Ico n m).image ((+) k) = Ico (n + k) (m + k) :=
by simp [image, multiset.Ico.map_add]
theorem image_sub (n m k : ℕ) (h : k ≤ n) : (Ico n m).image (λ x, x - k) = Ico (n - k) (m - k) :=
begin
dsimp [image],
rw [multiset.Ico.map_sub _ _ _ h, ←multiset.to_finset_eq],
refl,
end
theorem zero_bot (n : ℕ) : Ico 0 n = range n :=
eq_of_veq $ multiset.Ico.zero_bot _
@[simp] theorem card (n m : ℕ) : (Ico n m).card = m - n :=
multiset.Ico.card _ _
@[simp] theorem mem {n m l : ℕ} : l ∈ Ico n m ↔ n ≤ l ∧ l < m :=
multiset.Ico.mem
theorem eq_empty_of_le {n m : ℕ} (h : m ≤ n) : Ico n m = ∅ :=
eq_of_veq $ multiset.Ico.eq_zero_of_le h
@[simp] theorem self_eq_empty (n : ℕ) : Ico n n = ∅ :=
eq_empty_of_le $ le_refl n
@[simp] theorem eq_empty_iff {n m : ℕ} : Ico n m = ∅ ↔ m ≤ n :=
iff.trans val_eq_zero.symm multiset.Ico.eq_zero_iff
theorem subset_iff {m₁ n₁ m₂ n₂ : ℕ} (hmn : m₁ < n₁) :
Ico m₁ n₁ ⊆ Ico m₂ n₂ ↔ (m₂ ≤ m₁ ∧ n₁ ≤ n₂) :=
begin
simp only [subset_iff, mem],
refine ⟨λ h, ⟨_, _⟩, _⟩,
{ exact (h ⟨le_refl _, hmn⟩).1 },
{ refine le_of_pred_lt (@h (pred n₁) ⟨le_pred_of_lt hmn, pred_lt _⟩).2,
exact ne_of_gt (lt_of_le_of_lt (nat.zero_le m₁) hmn) },
{ rintros ⟨hm, hn⟩ k ⟨hmk, hkn⟩,
exact ⟨le_trans hm hmk, lt_of_lt_of_le hkn hn⟩ }
end
protected theorem subset {m₁ n₁ m₂ n₂ : ℕ} (hmm : m₂ ≤ m₁) (hnn : n₁ ≤ n₂) :
Ico m₁ n₁ ⊆ Ico m₂ n₂ :=
begin
simp only [finset.subset_iff, Ico.mem],
assume x hx,
exact ⟨le_trans hmm hx.1, lt_of_lt_of_le hx.2 hnn⟩
end
lemma union_consecutive {n m l : ℕ} (hnm : n ≤ m) (hml : m ≤ l) :
Ico n m ∪ Ico m l = Ico n l :=
by rw [← to_finset, ← to_finset, ← multiset.to_finset_add,
multiset.Ico.add_consecutive hnm hml, to_finset]
@[simp] lemma inter_consecutive (n m l : ℕ) : Ico n m ∩ Ico m l = ∅ :=
begin
rw [← to_finset, ← to_finset, ← multiset.to_finset_inter, multiset.Ico.inter_consecutive],
simp,
end
lemma disjoint_consecutive (n m l : ℕ) : disjoint (Ico n m) (Ico m l) :=
le_of_eq $ inter_consecutive n m l
@[simp] theorem succ_singleton (n : ℕ) : Ico n (n+1) = {n} :=
eq_of_veq $ multiset.Ico.succ_singleton
theorem succ_top {n m : ℕ} (h : n ≤ m) : Ico n (m + 1) = insert m (Ico n m) :=
by rw [← to_finset, multiset.Ico.succ_top h, multiset.to_finset_cons, to_finset]
theorem succ_top' {n m : ℕ} (h : n < m) : Ico n m = insert (m - 1) (Ico n (m - 1)) :=
begin
have w : m = m - 1 + 1 := (nat.sub_add_cancel (nat.one_le_of_lt h)).symm,
conv { to_lhs, rw w },
rw succ_top,
exact nat.le_pred_of_lt h
end
theorem insert_succ_bot {n m : ℕ} (h : n < m) : insert n (Ico (n + 1) m) = Ico n m :=
by rw [eq_comm, ← to_finset, multiset.Ico.eq_cons h, multiset.to_finset_cons, to_finset]
@[simp] theorem pred_singleton {m : ℕ} (h : 0 < m) : Ico (m - 1) m = {m - 1} :=
eq_of_veq $ multiset.Ico.pred_singleton h
@[simp] theorem not_mem_top {n m : ℕ} : m ∉ Ico n m :=
multiset.Ico.not_mem_top
lemma filter_lt_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, x < l) = Ico n m :=
eq_of_veq $ multiset.Ico.filter_lt_of_top_le hml
lemma filter_lt_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, x < l) = ∅ :=
eq_of_veq $ multiset.Ico.filter_lt_of_le_bot hln
lemma filter_lt_of_ge {n m l : ℕ} (hlm : l ≤ m) : (Ico n m).filter (λ x, x < l) = Ico n l :=
eq_of_veq $ multiset.Ico.filter_lt_of_ge hlm
@[simp] lemma filter_lt (n m l : ℕ) : (Ico n m).filter (λ x, x < l) = Ico n (min m l) :=
eq_of_veq $ multiset.Ico.filter_lt n m l
lemma filter_le_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, l ≤ x) = Ico n m :=
eq_of_veq $ multiset.Ico.filter_le_of_le_bot hln
lemma filter_le_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, l ≤ x) = ∅ :=
eq_of_veq $ multiset.Ico.filter_le_of_top_le hml
lemma filter_le_of_le {n m l : ℕ} (hnl : n ≤ l) : (Ico n m).filter (λ x, l ≤ x) = Ico l m :=
eq_of_veq $ multiset.Ico.filter_le_of_le hnl
@[simp] lemma filter_le (n m l : ℕ) : (Ico n m).filter (λ x, l ≤ x) = Ico (max n l) m :=
eq_of_veq $ multiset.Ico.filter_le n m l
@[simp] lemma diff_left (l n m : ℕ) : (Ico n m) \ (Ico n l) = Ico (max n l) m :=
by ext k; by_cases n ≤ k; simp [h, and_comm]
@[simp] lemma diff_right (l n m : ℕ) : (Ico n m) \ (Ico l m) = Ico n (min m l) :=
have ∀k, (k < m ∧ (l ≤ k → m ≤ k)) ↔ (k < m ∧ k < l) :=
assume k, and_congr_right $ assume hk, by rw [← not_imp_not]; simp [hk],
by ext k; by_cases n ≤ k; simp [h, this]
end Ico
-- TODO We don't yet attempt to reproduce the entire interface for `Ico` for `Ico_ℤ`.
/-- `Ico_ℤ l u` is the set of integers `l ≤ k < u`. -/
def Ico_ℤ (l u : ℤ) : finset ℤ :=
(finset.range (u - l).to_nat).map
{ to_fun := λ n, n + l,
inj := λ n m h, by simpa using h }
@[simp] lemma Ico_ℤ.mem {n m l : ℤ} : l ∈ Ico_ℤ n m ↔ n ≤ l ∧ l < m :=
begin
dsimp [Ico_ℤ],
simp only [int.lt_to_nat, exists_prop, mem_range, add_comm, function.embedding.coe_fn_mk, mem_map],
split,
{ rintro ⟨a, ⟨h, rfl⟩⟩,
exact ⟨int.le.intro rfl, lt_sub_iff_add_lt'.mp h⟩ },
{ rintro ⟨h₁, h₂⟩,
use (l - n).to_nat,
split; simp [h₁, h₂], }
end
end finset
namespace multiset
lemma count_sup [decidable_eq β] (s : finset α) (f : α → multiset β) (b : β) :
count b (s.sup f) = s.sup (λa, count b (f a)) :=
begin
letI := classical.dec_eq α,
refine s.induction _ _,
{ exact count_zero _ },
{ assume i s his ih,
rw [finset.sup_insert, sup_eq_union, count_union, finset.sup_insert, ih],
refl }
end
end multiset
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
section lattice
variables {ι : Sort*} [complete_lattice α] [decidable_eq ι]
lemma supr_eq_supr_finset (s : ι → α) : (⨆i, s i) = (⨆t:finset (plift ι), ⨆i∈t, s (plift.down i)) :=
le_antisymm
(supr_le $ assume b, le_supr_of_le {plift.up b} $ le_supr_of_le (plift.up b) $ le_supr_of_le
(by simp) $ le_refl _)
(supr_le $ assume t, supr_le $ assume b, supr_le $ assume hb, le_supr _ _)
lemma infi_eq_infi_finset (s : ι → α) : (⨅i, s i) = (⨅t:finset (plift ι), ⨅i∈t, s (plift.down i)) :=
le_antisymm
(le_infi $ assume t, le_infi $ assume b, le_infi $ assume hb, infi_le _ _)
(le_infi $ assume b, infi_le_of_le {plift.up b} $ infi_le_of_le (plift.up b) $ infi_le_of_le
(by simp) $ le_refl _)
end lattice
namespace set
variables {ι : Sort*} [decidable_eq ι]
lemma Union_eq_Union_finset (s : ι → set α) :
(⋃i, s i) = (⋃t:finset (plift ι), ⋃i∈t, s (plift.down i)) :=
supr_eq_supr_finset s
lemma Inter_eq_Inter_finset (s : ι → set α) :
(⋂i, s i) = (⋂t:finset (plift ι), ⋂i∈t, s (plift.down i)) :=
infi_eq_infi_finset s
end set
namespace finset
namespace nat
/-- The antidiagonal of a natural number `n` is
the finset of pairs `(i,j)` such that `i+j = n`. -/
def antidiagonal (n : ℕ) : finset (ℕ × ℕ) :=
(multiset.nat.antidiagonal n).to_finset
/-- A pair (i,j) is contained in the antidiagonal of `n` if and only if `i+j=n`. -/
@[simp] lemma mem_antidiagonal {n : ℕ} {x : ℕ × ℕ} :
x ∈ antidiagonal n ↔ x.1 + x.2 = n :=
by rw [antidiagonal, multiset.mem_to_finset, multiset.nat.mem_antidiagonal]
/-- The cardinality of the antidiagonal of `n` is `n+1`. -/
@[simp] lemma card_antidiagonal (n : ℕ) : (antidiagonal n).card = n+1 :=
by simpa using list.to_finset_card_of_nodup (list.nat.nodup_antidiagonal n)
/-- The antidiagonal of `0` is the list `[(0,0)]` -/
@[simp] lemma antidiagonal_zero : antidiagonal 0 = {(0, 0)} :=
by { rw [antidiagonal, multiset.nat.antidiagonal_zero], refl }
end nat
end finset
namespace finset
/-! ### bUnion -/
variables [decidable_eq α]
@[simp] theorem bUnion_singleton (a : α) (s : α → set β) : (⋃ x ∈ ({a} : finset α), s x) = s a :=
supr_singleton
theorem supr_union {α} [complete_lattice α] {β} [decidable_eq β] {f : β → α} {s t : finset β} :
(⨆ x ∈ s ∪ t, f x) = (⨆x∈s, f x) ⊔ (⨆x∈t, f x) :=
calc (⨆ x ∈ s ∪ t, f x) = (⨆ x, (⨆h : x∈s, f x) ⊔ (⨆h : x∈t, f x)) :
congr_arg _ $ funext $ λ x, by { convert supr_or, rw finset.mem_union, rw finset.mem_union, refl, refl }
... = (⨆x∈s, f x) ⊔ (⨆x∈t, f x) : supr_sup_eq
lemma bUnion_union (s t : finset α) (u : α → set β) :
(⋃ x ∈ s ∪ t, u x) = (⋃ x ∈ s, u x) ∪ (⋃ x ∈ t, u x) :=
supr_union
@[simp] lemma bUnion_insert (a : α) (s : finset α) (t : α → set β) :
(⋃ x ∈ insert a s, t x) = t a ∪ (⋃ x ∈ s, t x) :=
begin rw insert_eq, simp only [bUnion_union, finset.bUnion_singleton] end
end finset
|
73e71a175c6a59d7276b828af1db9c39da8327c2 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/algebra/ne_zero.lean | 40db44f08d73f684e04b19216faa160727bb01d8 | [
"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 | 3,711 | lean | /-
Copyright (c) 2021 Eric Rodriguez. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Rodriguez
-/
import data.zmod.basic
/-!
# `ne_zero` typeclass
We create a typeclass `ne_zero n` which carries around the fact that `(n : R) ≠ 0`.
## Main declarations
* `ne_zero`: `n ≠ 0` as a typeclass.
-/
/-- A type-class version of `n ≠ 0`. -/
class ne_zero {R} [has_zero R] (n : R) : Prop := (out : n ≠ 0)
lemma ne_zero.ne {R} [has_zero R] (n : R) [h : ne_zero n] : n ≠ 0 := h.out
lemma ne_zero.ne' (n : ℕ) (R) [add_monoid_with_one R] [h : ne_zero (n : R)] :
(n : R) ≠ 0 := h.out
lemma ne_zero_iff {R : Type*} [has_zero R] {n : R} : ne_zero n ↔ n ≠ 0 :=
⟨λ h, h.out, ne_zero.mk⟩
lemma not_ne_zero {R : Type*} [has_zero R] {n : R} : ¬ ne_zero n ↔ n = 0 :=
by simp [ne_zero_iff]
namespace ne_zero
variables {R S M F : Type*} {r : R} {x y : M} {n p : ℕ} {a : ℕ+}
instance pnat : ne_zero (a : ℕ) := ⟨a.ne_zero⟩
instance succ : ne_zero (n + 1) := ⟨n.succ_ne_zero⟩
lemma of_pos [preorder M] [has_zero M] (h : 0 < x) : ne_zero x := ⟨h.ne'⟩
lemma of_gt [canonically_ordered_add_monoid M] (h : x < y) : ne_zero y := of_pos $ pos_of_gt h
instance char_zero [ne_zero n] [add_monoid_with_one M] [char_zero M] : ne_zero (n : M) :=
⟨nat.cast_ne_zero.mpr $ ne_zero.ne n⟩
@[priority 100] instance invertible [mul_zero_one_class M] [nontrivial M] [invertible x] :
ne_zero x := ⟨nonzero_of_invertible x⟩
instance coe_trans [has_zero M] [has_coe R S] [has_coe_t S M] [h : ne_zero (r : M)] :
ne_zero ((r : S) : M) := ⟨h.out⟩
lemma trans [has_zero M] [has_coe R S] [has_coe_t S M] (h : ne_zero ((r : S) : M)) :
ne_zero (r : M) := ⟨h.out⟩
lemma of_map [has_zero R] [has_zero M] [zero_hom_class F R M] (f : F) [ne_zero (f r)] :
ne_zero r := ⟨λ h, ne (f r) $ by convert map_zero f⟩
lemma nat_of_ne_zero [semiring R] [semiring S] [ring_hom_class F R S] (f : F)
[hn : ne_zero (n : S)] : ne_zero (n : R) :=
begin
apply ne_zero.of_map f,
simp [hn]
end
lemma of_injective [has_zero R] [h : ne_zero r] [has_zero M] [zero_hom_class F R M]
{f : F} (hf : function.injective f) : ne_zero (f r) :=
⟨by { rw ←map_zero f, exact hf.ne (ne r) }⟩
lemma nat_of_injective [non_assoc_semiring M] [non_assoc_semiring R] [h : ne_zero (n : R)]
[ring_hom_class F R M] {f : F} (hf : function.injective f) : ne_zero (n : M) :=
⟨λ h, (ne_zero.ne' n R) $ hf $ by simpa⟩
lemma pos (r : R) [canonically_ordered_add_monoid R] [ne_zero r] : 0 < r :=
(zero_le r).lt_of_ne $ ne_zero.out.symm
variables (R M)
lemma of_not_dvd [add_monoid_with_one M] [char_p M p] (h : ¬ p ∣ n) : ne_zero (n : M) :=
⟨(not_iff_not.mpr $ char_p.cast_eq_zero_iff M p n).mpr h⟩
lemma of_no_zero_smul_divisors (n : ℕ) [comm_ring R] [ne_zero (n : R)] [ring M] [nontrivial M]
[algebra R M] [no_zero_smul_divisors R M] : ne_zero (n : M) :=
nat_of_injective $ no_zero_smul_divisors.algebra_map_injective R M
lemma of_ne_zero_coe [add_monoid_with_one R] [h : ne_zero (n : R)] : ne_zero n :=
⟨by {casesI h, rintro rfl, by simpa using h}⟩
lemma not_char_dvd [add_monoid_with_one R] (p : ℕ) [char_p R p] (k : ℕ) [h : ne_zero (k : R)] :
¬ p ∣ k :=
by rwa [←not_iff_not.mpr $ char_p.cast_eq_zero_iff R p k, ←ne.def, ←ne_zero_iff]
lemma pos_of_ne_zero_coe [add_monoid_with_one R] [ne_zero (n : R)] : 0 < n :=
(ne_zero.of_ne_zero_coe R).out.bot_lt
end ne_zero
lemma eq_zero_or_ne_zero {α} [has_zero α] (a : α) : a = 0 ∨ ne_zero a :=
(eq_or_ne a 0).imp_right ne_zero.mk
namespace zmod
instance fintype' (n : ℕ) [ne_zero n] : fintype (zmod n) :=
@zmod.fintype n ⟨ne_zero.pos n⟩
end zmod
|
7c0dbd492300df7fdd693986c388e8172ac02fa2 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/MetavarContext.lean | 9b1733936af9560303dc3271c5581463ef04f025 | [
"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 | 65,552 | 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.MonadCache
import Lean.LocalContext
namespace Lean
/-!
The metavariable context stores metavariable declarations and their
assignments. It is used in the elaborator, tactic framework, unifier
(aka `isDefEq`), and type class resolution (TC). First, we list all
the requirements imposed by these modules.
- We may invoke TC while executing `isDefEq`. We need this feature to
be able to solve unification problems such as:
```
f ?a (ringAdd ?s) ?x ?y =?= f Int intAdd n m
```
where `(?a : Type) (?s : Ring ?a) (?x ?y : ?a)`
During `isDefEq` (i.e., unification), it will need to solve the constrain
```
ringAdd ?s =?= intAdd
```
We say `ringAdd ?s` is stuck because it cannot be reduced until we
synthesize the term `?s : Ring ?a` using TC. This can be done since we
have assigned `?a := Int` when solving `?a =?= Int`.
- TC uses `isDefEq`, and `isDefEq` may create TC problems as shown
above. Thus, we may have nested TC problems.
- `isDefEq` extends the local context when going inside binders. Thus,
the local context for nested TC may be an extension of the local
context for outer TC.
- TC should not assign metavariables created by the elaborator, simp,
tactic framework, and outer TC problems. Reason: TC commits to the
first solution it finds. Consider the TC problem `Coe Nat ?x`,
where `?x` is a metavariable created by the caller. There are many
solutions to this problem (e.g., `?x := Int`, `?x := Real`, ...),
and it doesn’t make sense to commit to the first one since TC does
not know the constraints the caller may impose on `?x` after the
TC problem is solved.
Remark: we claim it is not feasible to make the whole system backtrackable,
and allow the caller to backtrack back to TC and ask it for another solution
if the first one found did not work. We claim it would be too inefficient.
- TC metavariables should not leak outside of TC. Reason: we want to
get rid of them after we synthesize the instance.
- `simp` invokes `isDefEq` for matching the left-hand-side of
equations to terms in our goal. Thus, it may invoke TC indirectly.
- In Lean3, we didn’t have to create a fresh pattern for trying to
match the left-hand-side of equations when executing `simp`. We had a
mechanism called "tmp" metavariables. It avoided this overhead, but it
created many problems since `simp` may indirectly call TC which may
recursively call TC. Moreover, we may want to allow TC to invoke
tactics in the future. Thus, when `simp` invokes `isDefEq`, it may indirectly invoke
a tactic and `simp` itself. The Lean3 approach assumed that
metavariables were short-lived, this is not true in Lean4, and to some
extent was also not true in Lean3 since `simp`, in principle, could
trigger an arbitrary number of nested TC problems.
- Here are some possible call stack traces we could have in Lean3 (and Lean4).
```
Elaborator (-> TC -> isDefEq)+
Elaborator -> isDefEq (-> TC -> isDefEq)*
Elaborator -> simp -> isDefEq (-> TC -> isDefEq)*
```
In Lean4, TC may also invoke tactics in the future.
- In Lean3 and Lean4, TC metavariables are not really short-lived. We
solve an arbitrary number of unification problems, and we may have
nested TC invocations.
- TC metavariables do not share the same local context even in the
same invocation. In the C++ and Lean implementations we use a trick to
ensure they do:
https://github.com/leanprover/lean/blob/92826917a252a6092cffaf5fc5f1acb1f8cef379/src/library/type_context.cpp#L3583-L3594
- Metavariables may be natural, synthetic or syntheticOpaque.
a) Natural metavariables may be assigned by unification (i.e., `isDefEq`).
b) Synthetic metavariables may still be assigned by unification,
but whenever possible `isDefEq` will avoid the assignment. For example,
if we have the unification constraint `?m =?= ?n`, where `?m` is synthetic,
but `?n` is not, `isDefEq` solves it by using the assignment `?n := ?m`.
We use synthetic metavariables for type class resolution.
Any module that creates synthetic metavariables, must also check
whether they have been assigned by `isDefEq`, and then still synthesize
them, and check whether the synthesized result is compatible with the one
assigned by `isDefEq`.
c) SyntheticOpaque metavariables are never assigned by `isDefEq`.
That is, the constraint `?n =?= Nat.succ Nat.zero` always fail
if `?n` is a syntheticOpaque metavariable. This kind of metavariable
is created by tactics such as `intro`. Reason: in the tactic framework,
subgoals as represented as metavariables, and a subgoal `?n` is considered
as solved whenever the metavariable is assigned.
This distinction was not precise in Lean3 and produced
counterintuitive behavior. For example, the following hack was added
in Lean3 to work around one of these issues:
https://github.com/leanprover/lean/blob/92826917a252a6092cffaf5fc5f1acb1f8cef379/src/library/type_context.cpp#L2751
- When creating lambda/forall expressions, we need to convert/abstract
free variables and convert them to bound variables. Now, suppose we are
trying to create a lambda/forall expression by abstracting free
variable `xs` and a term `t[?m]` which contains a metavariable `?m`,
and the local context of `?m` contains `xs`. The term
```
fun xs => t[?m]
```
will be ill-formed if we later assign a term `s` to `?m`, and
`s` contains free variables in `xs`. We address this issue by changing
the free variable abstraction procedure. We consider two cases: `?m`
is natural or synthetic, or `?m` is syntheticOpaque. Assume the type of `?m` is
`A[xs]`. Then, in both cases we create an auxiliary metavariable `?n` with
type `forall xs => A[xs]`, and local context := local context of `?m` - `xs`.
In both cases, we produce the term `fun xs => t[?n xs]`
1- If `?m` is natural or synthetic, then we assign `?m := ?n xs`, and we produce
the term `fun xs => t[?n xs]`
2- If `?m` is syntheticOpaque, then we mark `?n` as a syntheticOpaque variable.
However, `?n` is managed by the metavariable context itself.
We say we have a "delayed assignment" `?n xs := ?m`.
That is, after a term `s` is assigned to `?m`, and `s`
does not contain metavariables, we replace any occurrence
`?n ts` with `s[xs := ts]`.
Gruesome details:
- When we create the type `forall xs => A` for `?n`, we may
encounter the same issue if `A` contains metavariables. So, the
process above is recursive. We claim it terminates because we keep
creating new metavariables with smaller local contexts.
- Suppose, we have `t[?m]` and we want to create a let-expression by
abstracting a let-decl free variable `x`, and the local context of
`?m` contains `x`. Similarly to the previous case
```
let x : T := v; t[?m]
```
will be ill-formed if we later assign a term `s` to `?m`, and
`s` contains free variable `x`. Again, assume the type of `?m` is `A[x]`.
1- If `?m` is natural or synthetic, then we create `?n : (let x : T := v; A[x])` with
and local context := local context of `?m` - `x`, we assign `?m := ?n`,
and produce the term `let x : T := v; t[?n]`. That is, we are just making
sure `?n` must never be assigned to a term containing `x`.
2- If `?m` is syntheticOpaque, we create a fresh syntheticOpaque `?n`
with type `?n : T -> (let x : T := v; A[x])` and local context := local context of `?m` - `x`,
create the delayed assignment `?n #[x] := ?m`, and produce the term `let x : T := v; t[?n x]`.
Now suppose we assign `s` to `?m`. We do not assign the term `fun (x : T) => s` to `?n`, since
`fun (x : T) => s` may not even be type correct. Instead, we just replace applications `?n r`
with `s[x/r]`. The term `r` may not necessarily be a bound variable. For example, a tactic
may have reduced `let x : T := v; t[?n x]` into `t[?n v]`.
We are essentially using the pair "delayed assignment + application" to implement a delayed
substitution.
- We use TC for implementing coercions. Both Joe Hendrix and Reid Barton
reported a nasty limitation. In Lean3, TC will not be used if there are
metavariables in the TC problem. For example, the elaborator will not try
to synthesize `Coe Nat ?x`. This is good, but this constraint is too
strict for problems such as `Coe (Vector Bool ?n) (BV ?n)`. The coercion
exists independently of `?n`. Thus, during TC, we want `isDefEq` to throw
an exception instead of return `false` whenever it tries to assign
a metavariable owned by its caller. The idea is to sign to the caller that
it cannot solve the TC problem at this point, and more information is needed.
That is, the caller must make progress an assign its metavariables before
trying to invoke TC again.
In Lean4, we are using a simpler design for the `MetavarContext`.
- No distinction between temporary and regular metavariables.
- Metavariables have a `depth` Nat field.
- MetavarContext also has a `depth` field.
- We bump the `MetavarContext` depth when we create a nested problem.
Example: Elaborator (depth = 0) -> Simplifier matcher (depth = 1) -> TC (level = 2) -> TC (level = 3) -> ...
- When `MetavarContext` is at depth N, `isDefEq` does not assign variables from `depth < N`.
- Metavariables from depth N+1 must be fully assigned before we return to level N.
- New design even allows us to invoke tactics from TC.
* Main concern
We don't have tmp metavariables anymore in Lean4. Thus, before trying to match
the left-hand-side of an equation in `simp`. We first must bump the level of the `MetavarContext`,
create fresh metavariables, then create a new pattern by replacing the free variable on the left-hand-side with
these metavariables. We are hoping to minimize this overhead by
- Using better indexing data structures in `simp`. They should reduce the number of time `simp` must invoke `isDefEq`.
- Implementing `isDefEqApprox` which ignores metavariables and returns only `false` or `undef`.
It is a quick filter that allows us to fail quickly and avoid the creation of new fresh metavariables,
and a new pattern.
- Adding built-in support for arithmetic, Logical connectives, etc. Thus, we avoid a bunch of lemmas in the simp set.
- Adding support for AC-rewriting. In Lean3, users use AC lemmas as
rewriting rules for "sorting" terms. This is inefficient, requires
a quadratic number of rewrite steps, and does not preserve the
structure of the goal.
The temporary metavariables were also used in the "app builder" module used in Lean3. The app builder uses
`isDefEq`. So, it could, in principle, invoke an arbitrary number of nested TC problems. However, in Lean3,
all app builder uses are controlled. That is, it is mainly used to synthesize implicit arguments using
very simple unification and/or non-nested TC. So, if the "app builder" becomes a bottleneck without tmp metavars,
we may solve the issue by implementing `isDefEqCheap` that never invokes TC and uses tmp metavars.
-/
/--
`LocalInstance` represents a local typeclass instance registered by and for
the elaborator. It stores the name of the typeclass in `className`, and the
concrete typeclass instance in `fvar`. Note that the kernel does not care about
this information, since typeclasses are entirely eliminated during elaboration.
-/
structure LocalInstance where
className : Name
fvar : Expr
deriving Inhabited
abbrev LocalInstances := Array LocalInstance
instance : BEq LocalInstance where
beq i₁ i₂ := i₁.fvar == i₂.fvar
instance : Hashable LocalInstance where
hash i := hash i.fvar
/-- Remove local instance with the given `fvarId`. Do nothing if `localInsts` does not contain any free variable with id `fvarId`. -/
def LocalInstances.erase (localInsts : LocalInstances) (fvarId : FVarId) : LocalInstances :=
match localInsts.findIdx? (fun inst => inst.fvar.fvarId! == fvarId) with
| some idx => localInsts.eraseIdx idx
| _ => localInsts
/-- A kind for the metavariable that determines its unification behaviour.
For more information see the large comment at the beginning of this file. -/
inductive MetavarKind where
/-- Normal unification behaviour -/
| natural
/-- `isDefEq` avoids assignment -/
| synthetic
/-- Never assigned by isDefEq -/
| syntheticOpaque
deriving Inhabited, Repr
def MetavarKind.isSyntheticOpaque : MetavarKind → Bool
| MetavarKind.syntheticOpaque => true
| _ => false
def MetavarKind.isNatural : MetavarKind → Bool
| MetavarKind.natural => true
| _ => false
/-- Information about a metavariable. -/
structure MetavarDecl where
/-- A user-friendly name for the metavariable. If anonymous then there is no such name. -/
userName : Name := Name.anonymous
/-- The local context containing the free variables that the mvar is permitted to depend upon. -/
lctx : LocalContext
/-- The type of the metavarible, in the given `lctx`. -/
type : Expr
/--
The nesting depth of this metavariable. We do not want
unification subproblems to influence the results of parent
problems. The depth keeps track of this information and ensures
that unification subproblems cannot leak information out, by unifying
based on depth.
-/
depth : Nat
localInstances : LocalInstances
kind : MetavarKind
/-- See comment at `CheckAssignment` `Meta/ExprDefEq.lean` -/
numScopeArgs : Nat := 0
/-- We use this field to track how old a metavariable is. It is set using a counter at `MetavarContext` -/
index : Nat
deriving Inhabited
/--
A delayed assignment for a metavariable `?m`. It represents an assignment of the form `?m := (fun fvars => (mkMVar mvarIdPending))`.
`mvarIdPending` is a `syntheticOpaque` metavariable that has not been synthesized yet. The delayed assignment becomes a real one
as soon as `mvarIdPending` has been fully synthesized.
`fvars` are variables in the `mvarIdPending` local context.
See the comment below `assignDelayedMVar ` for the rationale of delayed assignments.
Recall that we use a locally nameless approach when dealing with binders. Suppose we are
trying to synthesize `?n` in the expression `e`, in the context of `(fun x => e)`.
The metavariable `?n` might depend on the bound variable `x`. However, since we are locally nameless,
the bound variable `x` is in fact represented by some free variable `fvar_x`. Thus, when we exit
the scope, we must rebind the value of `fvar_x` in `?n` to the de-bruijn index of the bound variable `x`.
-/
structure DelayedMetavarAssignment where
fvars : Array Expr
mvarIdPending : MVarId
/-- The metavariable context is a set of metavariable declarations and their assignments.
For more information on specifics see the comment in the file that `MetavarContext` is defined in.
-/
structure MetavarContext where
/-- Depth is used to control whether an mvar can be assigned in unification. -/
depth : Nat := 0
/-- At what depth level mvars can be assigned. -/
levelAssignDepth : Nat := 0
/-- Counter for setting the field `index` at `MetavarDecl` -/
mvarCounter : Nat := 0
lDepth : PersistentHashMap LMVarId Nat := {}
/-- Metavariable declarations. -/
decls : PersistentHashMap MVarId MetavarDecl := {}
/-- Index mapping user-friendly names to ids. -/
userNames : PersistentHashMap Name MVarId := {}
/-- Assignment table for universe level metavariables.-/
lAssignment : PersistentHashMap LMVarId Level := {}
/-- Assignment table for expression metavariables.-/
eAssignment : PersistentHashMap MVarId Expr := {}
/-- Assignment table for delayed abstraction metavariables.
For more information about delayed abstraction, see the docstring for `DelayedMetavarAssignment`. -/
dAssignment : PersistentHashMap MVarId DelayedMetavarAssignment := {}
/-- A monad with a stateful metavariable context, defining `getMCtx` and `modifyMCtx`. -/
class MonadMCtx (m : Type → Type) where
getMCtx : m MetavarContext
modifyMCtx : (MetavarContext → MetavarContext) → m Unit
export MonadMCtx (getMCtx modifyMCtx)
@[always_inline]
instance (m n) [MonadLift m n] [MonadMCtx m] : MonadMCtx n where
getMCtx := liftM (getMCtx : m _)
modifyMCtx := fun f => liftM (modifyMCtx f : m _)
abbrev setMCtx [MonadMCtx m] (mctx : MetavarContext) : m Unit :=
modifyMCtx fun _ => mctx
abbrev getLevelMVarAssignment? [Monad m] [MonadMCtx m] (mvarId : LMVarId) : m (Option Level) :=
return (← getMCtx).lAssignment.find? mvarId
def MetavarContext.getExprAssignmentCore? (m : MetavarContext) (mvarId : MVarId) : Option Expr :=
m.eAssignment.find? mvarId
def getExprMVarAssignment? [Monad m] [MonadMCtx m] (mvarId : MVarId) : m (Option Expr) :=
return (← getMCtx).getExprAssignmentCore? mvarId
def getDelayedMVarAssignment? [Monad m] [MonadMCtx m] (mvarId : MVarId) : m (Option DelayedMetavarAssignment) :=
return (← getMCtx).dAssignment.find? mvarId
/-- Given a sequence of delayed assignments
```
mvarId₁ := mvarId₂ ...;
...
mvarIdₙ := mvarId_root ... -- where `mvarId_root` is not delayed assigned
```
in `mctx`, `getDelayedRoot mctx mvarId₁` return `mvarId_root`.
If `mvarId₁` is not delayed assigned then return `mvarId₁` -/
partial def getDelayedMVarRoot [Monad m] [MonadMCtx m] (mvarId : MVarId) : m MVarId := do
match (← getDelayedMVarAssignment? mvarId) with
| some d => getDelayedMVarRoot d.mvarIdPending
| none => return mvarId
def isLevelMVarAssigned [Monad m] [MonadMCtx m] (mvarId : LMVarId) : m Bool :=
return (← getMCtx).lAssignment.contains mvarId
/-- Return `true` if the give metavariable is already assigned. -/
def _root_.Lean.MVarId.isAssigned [Monad m] [MonadMCtx m] (mvarId : MVarId) : m Bool :=
return (← getMCtx).eAssignment.contains mvarId
@[deprecated MVarId.isAssigned]
def isExprMVarAssigned [Monad m] [MonadMCtx m] (mvarId : MVarId) : m Bool := do
mvarId.isAssigned
def _root_.Lean.MVarId.isDelayedAssigned [Monad m] [MonadMCtx m] (mvarId : MVarId) : m Bool :=
return (← getMCtx).dAssignment.contains mvarId
@[deprecated MVarId.isDelayedAssigned]
def isMVarDelayedAssigned [Monad m] [MonadMCtx m] (mvarId : MVarId) : m Bool := do
mvarId.isDelayedAssigned
def isLevelMVarAssignable [Monad m] [MonadMCtx m] (mvarId : LMVarId) : m Bool := do
let mctx ← getMCtx
match mctx.lDepth.find? mvarId with
| some d => return d >= mctx.levelAssignDepth
| _ => panic! "unknown universe metavariable"
def MetavarContext.getDecl (mctx : MetavarContext) (mvarId : MVarId) : MetavarDecl :=
match mctx.decls.find? mvarId with
| some decl => decl
| none => panic! "unknown metavariable"
def _root_.Lean.MVarId.isAssignable [Monad m] [MonadMCtx m] (mvarId : MVarId) : m Bool := do
let mctx ← getMCtx
let decl := mctx.getDecl mvarId
return decl.depth == mctx.depth
@[deprecated MVarId.isAssignable]
def isExprMVarAssignable [Monad m] [MonadMCtx m] (mvarId : MVarId) : m Bool := do
mvarId.isAssignable
/-- Return true iff the given level contains an assigned metavariable. -/
def hasAssignedLevelMVar [Monad m] [MonadMCtx m] : Level → m Bool
| .succ lvl => pure lvl.hasMVar <&&> hasAssignedLevelMVar lvl
| .max lvl₁ lvl₂ => (pure lvl₁.hasMVar <&&> hasAssignedLevelMVar lvl₁) <||> (pure lvl₂.hasMVar <&&> hasAssignedLevelMVar lvl₂)
| .imax lvl₁ lvl₂ => (pure lvl₁.hasMVar <&&> hasAssignedLevelMVar lvl₁) <||> (pure lvl₂.hasMVar <&&> hasAssignedLevelMVar lvl₂)
| .mvar mvarId => isLevelMVarAssigned mvarId
| .zero => pure false
| .param _ => pure false
/-- Return `true` iff expression contains assigned (level/expr) metavariables or delayed assigned mvars -/
def hasAssignedMVar [Monad m] [MonadMCtx m] : Expr → m Bool
| .const _ lvls => lvls.anyM hasAssignedLevelMVar
| .sort lvl => hasAssignedLevelMVar lvl
| .app f a => (pure f.hasMVar <&&> hasAssignedMVar f) <||> (pure a.hasMVar <&&> hasAssignedMVar a)
| .letE _ t v b _ => (pure t.hasMVar <&&> hasAssignedMVar t) <||> (pure v.hasMVar <&&> hasAssignedMVar v) <||> (pure b.hasMVar <&&> hasAssignedMVar b)
| .forallE _ d b _ => (pure d.hasMVar <&&> hasAssignedMVar d) <||> (pure b.hasMVar <&&> hasAssignedMVar b)
| .lam _ d b _ => (pure d.hasMVar <&&> hasAssignedMVar d) <||> (pure b.hasMVar <&&> hasAssignedMVar b)
| .fvar _ => return false
| .bvar _ => return false
| .lit _ => return false
| .mdata _ e => pure e.hasMVar <&&> hasAssignedMVar e
| .proj _ _ e => pure e.hasMVar <&&> hasAssignedMVar e
| .mvar mvarId => mvarId.isAssigned <||> mvarId.isDelayedAssigned
/-- Return true iff the given level contains a metavariable that can be assigned. -/
def hasAssignableLevelMVar [Monad m] [MonadMCtx m] : Level → m Bool
| .succ lvl => pure lvl.hasMVar <&&> hasAssignableLevelMVar lvl
| .max lvl₁ lvl₂ => (pure lvl₁.hasMVar <&&> hasAssignableLevelMVar lvl₁) <||> (pure lvl₂.hasMVar <&&> hasAssignableLevelMVar lvl₂)
| .imax lvl₁ lvl₂ => (pure lvl₁.hasMVar <&&> hasAssignableLevelMVar lvl₁) <||> (pure lvl₂.hasMVar <&&> hasAssignableLevelMVar lvl₂)
| .mvar mvarId => isLevelMVarAssignable mvarId
| .zero => return false
| .param _ => return false
/-- Return `true` iff expression contains a metavariable that can be assigned. -/
def hasAssignableMVar [Monad m] [MonadMCtx m] : Expr → m Bool
| .const _ lvls => lvls.anyM hasAssignableLevelMVar
| .sort lvl => hasAssignableLevelMVar lvl
| .app f a => (pure f.hasMVar <&&> hasAssignableMVar f) <||> (pure a.hasMVar <&&> hasAssignableMVar a)
| .letE _ t v b _ => (pure t.hasMVar <&&> hasAssignableMVar t) <||> (pure v.hasMVar <&&> hasAssignableMVar v) <||> (pure b.hasMVar <&&> hasAssignableMVar b)
| .forallE _ d b _ => (pure d.hasMVar <&&> hasAssignableMVar d) <||> (pure b.hasMVar <&&> hasAssignableMVar b)
| .lam _ d b _ => (pure d.hasMVar <&&> hasAssignableMVar d) <||> (pure b.hasMVar <&&> hasAssignableMVar b)
| .fvar _ => return false
| .bvar _ => return false
| .lit _ => return false
| .mdata _ e => pure e.hasMVar <&&> hasAssignableMVar e
| .proj _ _ e => pure e.hasMVar <&&> hasAssignableMVar e
| .mvar mvarId => mvarId.isAssignable
/--
Add `mvarId := u` to the universe metavariable assignment.
This method does not check whether `mvarId` is already assigned, nor it checks whether
a cycle is being introduced.
This is a low-level API, and it is safer to use `isLevelDefEq (mkLevelMVar mvarId) u`.
-/
def assignLevelMVar [MonadMCtx m] (mvarId : LMVarId) (val : Level) : m Unit :=
modifyMCtx fun m => { m with lAssignment := m.lAssignment.insert mvarId val }
/--
Add `mvarId := x` to the metavariable assignment.
This method does not check whether `mvarId` is already assigned, nor it checks whether
a cycle is being introduced, or whether the expression has the right type.
This is a low-level API, and it is safer to use `isDefEq (mkMVar mvarId) x`.
-/
def _root_.Lean.MVarId.assign [MonadMCtx m] (mvarId : MVarId) (val : Expr) : m Unit :=
modifyMCtx fun m => { m with eAssignment := m.eAssignment.insert mvarId val }
@[deprecated MVarId.assign]
def assignExprMVar [MonadMCtx m] (mvarId : MVarId) (val : Expr) : m Unit :=
mvarId.assign val
def assignDelayedMVar [MonadMCtx m] (mvarId : MVarId) (fvars : Array Expr) (mvarIdPending : MVarId) : m Unit :=
modifyMCtx fun m => { m with dAssignment := m.dAssignment.insert mvarId { fvars, mvarIdPending } }
/-!
Notes on artificial eta-expanded terms due to metavariables.
We try avoid synthetic terms such as `((fun x y => t) a b)` in the output produced by the elaborator.
This kind of term may be generated when instantiating metavariable assignments.
This module tries to avoid their generation because they often introduce unnecessary dependencies and
may affect automation.
When elaborating terms, we use metavariables to represent "holes". Each hole has a context which includes
all free variables that may be used to "fill" the hole. Suppose, we create a metavariable (hole) `?m : Nat` in a context
containing `(x : Nat) (y : Nat) (b : Bool)`, then we can assign terms such as `x + y` to `?m` since `x` and `y`
are in the context used to create `?m`. Now, suppose we have the term `?m + 1` and we want to create the lambda expression
`fun x => ?m + 1`. This term is not correct since we may assign to `?m` a term containing `x`.
We address this issue by create a synthetic metavariable `?n : Nat → Nat` and adding the delayed assignment
`?n #[x] := ?m`, and the term `fun x => ?n x + 1`. When we later assign a term `t[x]` to `?m`, `fun x => t[x]` is assigned to
`?n`, and if we substitute it at `fun x => ?n x + 1`, we produce `fun x => ((fun x => t[x]) x) + 1`.
To avoid this term eta-expanded term, we apply beta-reduction when instantiating metavariable assignments in this module.
This operation is performed at `instantiateExprMVars`, `elimMVarDeps`, and `levelMVarToParam`.
-/
partial def instantiateLevelMVars [Monad m] [MonadMCtx m] : Level → m Level
| lvl@(Level.succ lvl₁) => return Level.updateSucc! lvl (← instantiateLevelMVars lvl₁)
| lvl@(Level.max lvl₁ lvl₂) => return Level.updateMax! lvl (← instantiateLevelMVars lvl₁) (← instantiateLevelMVars lvl₂)
| lvl@(Level.imax lvl₁ lvl₂) => return Level.updateIMax! lvl (← instantiateLevelMVars lvl₁) (← instantiateLevelMVars lvl₂)
| lvl@(Level.mvar mvarId) => do
match (← getLevelMVarAssignment? mvarId) with
| some newLvl =>
if !newLvl.hasMVar then pure newLvl
else do
let newLvl' ← instantiateLevelMVars newLvl
assignLevelMVar mvarId newLvl'
pure newLvl'
| none => pure lvl
| lvl => pure lvl
/-- instantiateExprMVars main function -/
partial def instantiateExprMVars [Monad m] [MonadMCtx m] [STWorld ω m] [MonadLiftT (ST ω) m] (e : Expr) : MonadCacheT ExprStructEq Expr m Expr :=
if !e.hasMVar then
pure e
else checkCache { val := e : ExprStructEq } fun _ => do match e with
| .proj _ _ s => return e.updateProj! (← instantiateExprMVars s)
| .forallE _ d b _ => return e.updateForallE! (← instantiateExprMVars d) (← instantiateExprMVars b)
| .lam _ d b _ => return e.updateLambdaE! (← instantiateExprMVars d) (← instantiateExprMVars b)
| .letE _ t v b _ => return e.updateLet! (← instantiateExprMVars t) (← instantiateExprMVars v) (← instantiateExprMVars b)
| .const _ lvls => return e.updateConst! (← lvls.mapM instantiateLevelMVars)
| .sort lvl => return e.updateSort! (← instantiateLevelMVars lvl)
| .mdata _ b => return e.updateMData! (← instantiateExprMVars b)
| .app .. => e.withApp fun f args => do
let instArgs (f : Expr) : MonadCacheT ExprStructEq Expr m Expr := do
let args ← args.mapM instantiateExprMVars
pure (mkAppN f args)
let instApp : MonadCacheT ExprStructEq Expr m Expr := do
let wasMVar := f.isMVar
let f ← instantiateExprMVars f
if wasMVar && f.isLambda then
/- Some of the arguments in args are irrelevant after we beta reduce. -/
instantiateExprMVars (f.betaRev args.reverse)
else
instArgs f
match f with
| .mvar mvarId =>
match (← getDelayedMVarAssignment? mvarId) with
| none => instApp
| some { fvars, mvarIdPending } =>
/-
Apply "delayed substitution" (i.e., delayed assignment + application).
That is, `f` is some metavariable `?m`, that is delayed assigned to `val`.
If after instantiating `val`, we obtain `newVal`, and `newVal` does not contain
metavariables, we replace the free variables `fvars` in `newVal` with the first
`fvars.size` elements of `args`. -/
if fvars.size > args.size then
/- We don't have sufficient arguments for instantiating the free variables `fvars`.
This can only happen if a tactic or elaboration function is not implemented correctly.
We decided to not use `panic!` here and report it as an error in the frontend
when we are checking for unassigned metavariables in an elaborated term. -/
instArgs f
else
let newVal ← instantiateExprMVars (mkMVar mvarIdPending)
if newVal.hasExprMVar then
instArgs f
else do
let args ← args.mapM instantiateExprMVars
/-
Example: suppose we have
`?m t1 t2 t3`
That is, `f := ?m` and `args := #[t1, t2, t3]`
Morever, `?m` is delayed assigned
`?m #[x, y] := f x y`
where, `fvars := #[x, y]` and `newVal := f x y`.
After abstracting `newVal`, we have `f (Expr.bvar 0) (Expr.bvar 1)`.
After `instantiaterRevRange 0 2 args`, we have `f t1 t2`.
After `mkAppRange 2 3`, we have `f t1 t2 t3` -/
let newVal := newVal.abstract fvars
let result := newVal.instantiateRevRange 0 fvars.size args
let result := mkAppRange result fvars.size args.size args
pure result
| _ => instApp
| e@(.mvar mvarId) => checkCache { val := e : ExprStructEq } fun _ => do
match (← getExprMVarAssignment? mvarId) with
| some newE => do
let newE' ← instantiateExprMVars newE
mvarId.assign newE'
pure newE'
| none => pure e
| e => pure e
instance : MonadMCtx (StateRefT MetavarContext (ST ω)) where
getMCtx := get
modifyMCtx := modify
def instantiateMVarsCore (mctx : MetavarContext) (e : Expr) : Expr × MetavarContext :=
let instantiate {ω} (e : Expr) : (MonadCacheT ExprStructEq Expr <| StateRefT MetavarContext (ST ω)) Expr :=
instantiateExprMVars e
runST fun _ => instantiate e |>.run |>.run mctx
def instantiateMVars [Monad m] [MonadMCtx m] (e : Expr) : m Expr := do
if !e.hasMVar then
return e
else
let (r, mctx) := instantiateMVarsCore (← getMCtx) e
modifyMCtx fun _ => mctx
return r
def instantiateLCtxMVars [Monad m] [MonadMCtx m] (lctx : LocalContext) : m LocalContext :=
lctx.foldlM (init := {}) fun lctx ldecl => do
match ldecl with
| .cdecl _ fvarId userName type bi k =>
let type ← instantiateMVars type
return lctx.mkLocalDecl fvarId userName type bi k
| .ldecl _ fvarId userName type value nonDep k =>
let type ← instantiateMVars type
let value ← instantiateMVars value
return lctx.mkLetDecl fvarId userName type value nonDep k
def instantiateMVarDeclMVars [Monad m] [MonadMCtx m] (mvarId : MVarId) : m Unit := do
let mvarDecl := (← getMCtx).getDecl mvarId
let lctx ← instantiateLCtxMVars mvarDecl.lctx
let type ← instantiateMVars mvarDecl.type
modifyMCtx fun mctx => { mctx with decls := mctx.decls.insert mvarId { mvarDecl with lctx, type } }
def instantiateLocalDeclMVars [Monad m] [MonadMCtx m] (localDecl : LocalDecl) : m LocalDecl := do
match localDecl with
| .cdecl idx id n type bi k =>
return .cdecl idx id n (← instantiateMVars type) bi k
| .ldecl idx id n type val nonDep k =>
return .ldecl idx id n (← instantiateMVars type) (← instantiateMVars val) nonDep k
namespace DependsOn
structure State where
visited : ExprSet := {}
mctx : MetavarContext
private abbrev M := StateM State
instance : MonadMCtx M where
getMCtx := return (← get).mctx
modifyMCtx f := modify fun s => { s with mctx := f s.mctx }
private def shouldVisit (e : Expr) : M Bool := do
if !e.hasMVar && !e.hasFVar then
return false
else if (← get).visited.contains e then
return false
else
modify fun s => { s with visited := s.visited.insert e }
return true
@[specialize] private partial def dep (pf : FVarId → Bool) (pm : MVarId → Bool) (e : Expr) : M Bool :=
let rec
visit (e : Expr) : M Bool := do
if !(← shouldVisit e) then
pure false
else
visitMain e,
visitApp : Expr → M Bool
| .app f a .. => visitApp f <||> visit a
| e => visit e,
visitMain : Expr → M Bool
| .proj _ _ s => visit s
| .forallE _ d b _ => visit d <||> visit b
| .lam _ d b _ => visit d <||> visit b
| .letE _ t v b _ => visit t <||> visit v <||> visit b
| .mdata _ b => visit b
| e@(.app ..) => do
let f := e.getAppFn
if f.isMVar then
let e' ← instantiateMVars e
if e'.getAppFn != f then
visitMain e'
else if pm f.mvarId! then
return true
else
visitApp e
else
visitApp e
| .mvar mvarId => do
match (← getExprMVarAssignment? mvarId) with
| some a => visit a
| none =>
if pm mvarId then
return true
else
let lctx := (← getMCtx).getDecl mvarId |>.lctx
return lctx.any fun decl => pf decl.fvarId
| .fvar fvarId => return pf fvarId
| _ => pure false
visit e
@[inline] partial def main (pf : FVarId → Bool) (pm : MVarId → Bool) (e : Expr) : M Bool :=
if !e.hasFVar && !e.hasMVar then pure false else dep pf pm e
end DependsOn
/--
Return `true` iff `e` depends on a free variable `x` s.t. `pf x` is `true`, or an unassigned metavariable `?m` s.t. `pm ?m` is true.
For each metavariable `?m` (that does not satisfy `pm` occurring in `x`
1- If `?m := t`, then we visit `t` looking for `x`
2- If `?m` is unassigned, then we consider the worst case and check whether `x` is in the local context of `?m`.
This case is a "may dependency". That is, we may assign a term `t` to `?m` s.t. `t` contains `x`. -/
@[inline] def findExprDependsOn [Monad m] [MonadMCtx m] (e : Expr) (pf : FVarId → Bool := fun _ => false) (pm : MVarId → Bool := fun _ => false) : m Bool := do
let (result, { mctx, .. }) := DependsOn.main pf pm e |>.run { mctx := (← getMCtx) }
setMCtx mctx
return result
/--
Similar to `findExprDependsOn`, but checks the expressions in the given local declaration
depends on a free variable `x` s.t. `pf x` is `true` or an unassigned metavariable `?m` s.t. `pm ?m` is true. -/
@[inline] def findLocalDeclDependsOn [Monad m] [MonadMCtx m] (localDecl : LocalDecl) (pf : FVarId → Bool := fun _ => false) (pm : MVarId → Bool := fun _ => false) : m Bool := do
match localDecl with
| .cdecl (type := t) .. => findExprDependsOn t pf pm
| .ldecl (type := t) (value := v) .. =>
let (result, { mctx, .. }) := (DependsOn.main pf pm t <||> DependsOn.main pf pm v).run { mctx := (← getMCtx) }
setMCtx mctx
return result
def exprDependsOn [Monad m] [MonadMCtx m] (e : Expr) (fvarId : FVarId) : m Bool :=
findExprDependsOn e (fvarId == ·)
/-- Return true iff `e` depends on the free variable `fvarId` -/
def dependsOn [Monad m] [MonadMCtx m] (e : Expr) (fvarId : FVarId) : m Bool :=
exprDependsOn e fvarId
/-- Return true iff `localDecl` depends on the free variable `fvarId` -/
def localDeclDependsOn [Monad m] [MonadMCtx m] (localDecl : LocalDecl) (fvarId : FVarId) : m Bool :=
findLocalDeclDependsOn localDecl (fvarId == ·)
/-- Similar to `exprDependsOn`, but `x` can be a free variable or an unassigned metavariable. -/
def exprDependsOn' [Monad m] [MonadMCtx m] (e : Expr) (x : Expr) : m Bool :=
if x.isFVar then
findExprDependsOn e (x.fvarId! == ·)
else if x.isMVar then
findExprDependsOn e (pm := (x.mvarId! == ·))
else
return false
/-- Similar to `localDeclDependsOn`, but `x` can be a free variable or an unassigned metavariable. -/
def localDeclDependsOn' [Monad m] [MonadMCtx m] (localDecl : LocalDecl) (x : Expr) : m Bool :=
if x.isFVar then
findLocalDeclDependsOn localDecl (x.fvarId! == ·)
else if x.isMVar then
findLocalDeclDependsOn localDecl (pm := (x.mvarId! == ·))
else
return false
/-- Return true iff `e` depends on a free variable `x` s.t. `pf x`, or an unassigned metavariable `?m` s.t. `pm ?m` is true. -/
def dependsOnPred [Monad m] [MonadMCtx m] (e : Expr) (pf : FVarId → Bool := fun _ => false) (pm : MVarId → Bool := fun _ => false) : m Bool :=
findExprDependsOn e pf pm
/-- Return true iff the local declaration `localDecl` depends on a free variable `x` s.t. `pf x`, an unassigned metavariable `?m` s.t. `pm ?m` is true. -/
def localDeclDependsOnPred [Monad m] [MonadMCtx m] (localDecl : LocalDecl) (pf : FVarId → Bool := fun _ => false) (pm : MVarId → Bool := fun _ => false) : m Bool := do
findLocalDeclDependsOn localDecl pf pm
namespace MetavarContext
instance : Inhabited MetavarContext := ⟨{}⟩
@[export lean_mk_metavar_ctx]
def mkMetavarContext : Unit → MetavarContext := fun _ => {}
/-- Low level API for adding/declaring metavariable declarations.
It is used to implement actions in the monads `MetaM`, `ElabM` and `TacticM`.
It should not be used directly since the argument `(mvarId : MVarId)` is assumed to be "unique". -/
def addExprMVarDecl (mctx : MetavarContext)
(mvarId : MVarId)
(userName : Name)
(lctx : LocalContext)
(localInstances : LocalInstances)
(type : Expr)
(kind : MetavarKind := MetavarKind.natural)
(numScopeArgs : Nat := 0) : MetavarContext :=
{ mctx with
mvarCounter := mctx.mvarCounter + 1
decls := mctx.decls.insert mvarId {
depth := mctx.depth
index := mctx.mvarCounter
userName
lctx
localInstances
type
kind
numScopeArgs }
userNames := if userName.isAnonymous then mctx.userNames else mctx.userNames.insert userName mvarId }
def addExprMVarDeclExp (mctx : MetavarContext) (mvarId : MVarId) (userName : Name) (lctx : LocalContext) (localInstances : LocalInstances)
(type : Expr) (kind : MetavarKind) : MetavarContext :=
addExprMVarDecl mctx mvarId userName lctx localInstances type kind
/-- Low level API for adding/declaring universe level metavariable declarations.
It is used to implement actions in the monads `MetaM`, `ElabM` and `TacticM`.
It should not be used directly since the argument `(mvarId : MVarId)` is assumed to be "unique". -/
def addLevelMVarDecl (mctx : MetavarContext) (mvarId : LMVarId) : MetavarContext :=
{ mctx with lDepth := mctx.lDepth.insert mvarId mctx.depth }
def findDecl? (mctx : MetavarContext) (mvarId : MVarId) : Option MetavarDecl :=
mctx.decls.find? mvarId
def findUserName? (mctx : MetavarContext) (userName : Name) : Option MVarId :=
mctx.userNames.find? userName
def setMVarKind (mctx : MetavarContext) (mvarId : MVarId) (kind : MetavarKind) : MetavarContext :=
let decl := mctx.getDecl mvarId
{ mctx with decls := mctx.decls.insert mvarId { decl with kind := kind } }
/--
Set the metavariable user facing name.
-/
def setMVarUserName (mctx : MetavarContext) (mvarId : MVarId) (userName : Name) : MetavarContext :=
let decl := mctx.getDecl mvarId
{ mctx with
decls := mctx.decls.insert mvarId { decl with userName := userName }
userNames :=
let userNames := mctx.userNames.erase decl.userName
if userName.isAnonymous then userNames else userNames.insert userName mvarId }
/--
Low-level version of `setMVarUserName`.
It does not update the table `userNames`. Thus, `findUserName?` cannot see the modification.
It is meant for `mkForallFVars'` where we temporarily set the user facing name of metavariables to get more
meaningful binder names.
-/
def setMVarUserNameTemporarily (mctx : MetavarContext) (mvarId : MVarId) (userName : Name) : MetavarContext :=
let decl := mctx.getDecl mvarId
{ mctx with decls := mctx.decls.insert mvarId { decl with userName := userName } }
/-- Update the type of the given metavariable. This function assumes the new type is
definitionally equal to the current one -/
def setMVarType (mctx : MetavarContext) (mvarId : MVarId) (type : Expr) : MetavarContext :=
let decl := mctx.getDecl mvarId
{ mctx with decls := mctx.decls.insert mvarId { decl with type := type } }
def findLevelDepth? (mctx : MetavarContext) (mvarId : LMVarId) : Option Nat :=
mctx.lDepth.find? mvarId
def getLevelDepth (mctx : MetavarContext) (mvarId : LMVarId) : Nat :=
match mctx.findLevelDepth? mvarId with
| some d => d
| none => panic! "unknown metavariable"
def isAnonymousMVar (mctx : MetavarContext) (mvarId : MVarId) : Bool :=
match mctx.findDecl? mvarId with
| none => false
| some mvarDecl => mvarDecl.userName.isAnonymous
def incDepth (mctx : MetavarContext) (allowLevelAssignments := false) : MetavarContext :=
let depth := mctx.depth + 1
let levelAssignDepth :=
if allowLevelAssignments then mctx.levelAssignDepth else depth
{ mctx with depth, levelAssignDepth }
instance : MonadMCtx (StateRefT MetavarContext (ST ω)) where
getMCtx := get
modifyMCtx := modify
namespace MkBinding
inductive Exception where
| revertFailure (mctx : MetavarContext) (lctx : LocalContext) (toRevert : Array Expr) (varName : String)
instance : ToString Exception where
toString
| Exception.revertFailure _ lctx toRevert varName =>
"failed to revert "
++ toString (toRevert.map (fun x => "'" ++ toString (lctx.getFVar! x).userName ++ "'"))
++ ", '" ++ toString varName ++ "' depends on them, and it is an auxiliary declaration created by the elaborator"
++ " (possible solution: use tactic 'clear' to remove '" ++ toString varName ++ "' from local context)"
/--
`MkBinding` and `elimMVarDepsAux` are mutually recursive, but `cache` is only used at `elimMVarDepsAux`.
We use a single state object for convenience.
We have a `NameGenerator` because we need to generate fresh auxiliary metavariables. -/
structure State where
mctx : MetavarContext
nextMacroScope : MacroScope
ngen : NameGenerator
cache : HashMap ExprStructEq Expr := {}
structure Context where
mainModule : Name
preserveOrder : Bool
/-- When creating binders for abstracted metavariables, we use the following `BinderInfo`. -/
binderInfoForMVars : BinderInfo := BinderInfo.implicit
/-- Set of unassigned metavariables being abstracted. -/
mvarIdsToAbstract : MVarIdSet := {}
abbrev MCore := EStateM Exception State
abbrev M := ReaderT Context MCore
instance : MonadMCtx M where
getMCtx := return (← get).mctx
modifyMCtx f := modify fun s => { s with mctx := f s.mctx }
private def mkFreshBinderName (n : Name := `x) : M Name := do
let fresh ← modifyGet fun s => (s.nextMacroScope, { s with nextMacroScope := s.nextMacroScope + 1 })
return addMacroScope (← read).mainModule n fresh
def preserveOrder : M Bool :=
return (← read).preserveOrder
instance : MonadHashMapCacheAdapter ExprStructEq Expr M where
getCache := do let s ← get; pure s.cache
modifyCache := fun f => modify fun s => { s with cache := f s.cache }
/-- Return the local declaration of the free variable `x` in `xs` with the smallest index -/
private def getLocalDeclWithSmallestIdx (lctx : LocalContext) (xs : Array Expr) : LocalDecl := Id.run do
let mut d : LocalDecl := lctx.getFVar! xs[0]!
for x in xs[1:] do
if x.isFVar then
let curr := lctx.getFVar! x
if curr.index < d.index then
d := curr
return d
/--
Given `toRevert` an array of free variables s.t. `lctx` contains their declarations,
return a new array of free variables that contains `toRevert` and all variables
in `lctx` that may depend on `toRevert`.
Remark: the result is sorted by `LocalDecl` indices.
Remark: We used to throw an `Exception.revertFailure` exception when an auxiliary declaration
had to be reversed. Recall that auxiliary declarations are created when compiling (mutually)
recursive definitions. The `revertFailure` due to auxiliary declaration dependency was originally
introduced in Lean3 to address issue https://github.com/leanprover/lean/issues/1258.
In Lean4, this solution is not satisfactory because all definitions/theorems are potentially
recursive. So, even a simple (incomplete) definition such as
```
variables {α : Type} in
def f (a : α) : List α :=
_
```
would trigger the `Exception.revertFailure` exception. In the definition above,
the elaborator creates the auxiliary definition `f : {α : Type} → List α`.
The `_` is elaborated as a new fresh variable `?m` that contains `α : Type`, `a : α`, and `f : α → List α` in its context,
When we try to create the lambda `fun {α : Type} (a : α) => ?m`, we first need to create
an auxiliary `?n` which does not contain `α` and `a` in its context. That is,
we create the metavariable `?n : {α : Type} → (a : α) → (f : α → List α) → List α`,
add the delayed assignment `?n #[α, a, f] := ?m`, and create the lambda
`fun {α : Type} (a : α) => ?n α a f`.
See `elimMVarDeps` for more information.
If we kept using the Lean3 approach, we would get the `Exception.revertFailure` exception because we are
reverting the auxiliary definition `f`.
Note that https://github.com/leanprover/lean/issues/1258 is not an issue in Lean4 because
we have changed how we compile recursive definitions.
-/
def collectForwardDeps (lctx : LocalContext) (toRevert : Array Expr) : M (Array Expr) := do
if toRevert.size == 0 then
pure toRevert
else
if (← preserveOrder) then
-- Make sure toRevert[j] does not depend on toRevert[i] for j < i
toRevert.size.forM fun i => do
let fvar := toRevert[i]!
i.forM fun j => do
let prevFVar := toRevert[j]!
let prevDecl := lctx.getFVar! prevFVar
if (← localDeclDependsOn prevDecl fvar.fvarId!) then
throw (Exception.revertFailure (← getMCtx) lctx toRevert prevDecl.userName.toString)
let newToRevert := if (← preserveOrder) then toRevert else Array.mkEmpty toRevert.size
let firstDeclToVisit := getLocalDeclWithSmallestIdx lctx toRevert
let initSize := newToRevert.size
lctx.foldlM (init := newToRevert) (start := firstDeclToVisit.index) fun (newToRevert : Array Expr) decl => do
if initSize.any fun i => decl.fvarId == newToRevert[i]!.fvarId! then
return newToRevert
else if toRevert.any fun x => decl.fvarId == x.fvarId! then
return newToRevert.push decl.toExpr
else if (← findLocalDeclDependsOn decl (newToRevert.any fun x => x.fvarId! == ·)) then
return newToRevert.push decl.toExpr
else
return newToRevert
/-- Create a new `LocalContext` by removing the free variables in `toRevert` from `lctx`.
We use this function when we create auxiliary metavariables at `elimMVarDepsAux`. -/
def reduceLocalContext (lctx : LocalContext) (toRevert : Array Expr) : LocalContext :=
toRevert.foldr (init := lctx) fun x lctx =>
if x.isFVar then lctx.erase x.fvarId! else lctx
/-- Return free variables in `xs` that are in the local context `lctx` -/
private def getInScope (lctx : LocalContext) (xs : Array Expr) : Array Expr :=
xs.foldl (init := #[]) fun scope x =>
if !x.isFVar then
scope
else if lctx.contains x.fvarId! then
scope.push x
else
scope
/-- Execute `x` with an empty cache, and then restore the original cache. -/
@[inline] private def withFreshCache (x : M α) : M α := do
let cache ← modifyGet fun s => (s.cache, { s with cache := {} })
let a ← x
modify fun s => { s with cache := cache }
pure a
/--
Create an application `mvar ys` where `ys` are the free variables.
See "Gruesome details" in the beginning of the file for understanding
how let-decl free variables are handled. -/
private def mkMVarApp (lctx : LocalContext) (mvar : Expr) (xs : Array Expr) (kind : MetavarKind) : Expr :=
xs.foldl (init := mvar) fun e x =>
if !x.isFVar then
e
else
match kind with
| MetavarKind.syntheticOpaque => mkApp e x
| _ => if (lctx.getFVar! x).isLet then e else mkApp e x
mutual
private partial def visit (xs : Array Expr) (e : Expr) : M Expr :=
if !e.hasMVar then pure e else checkCache { val := e : ExprStructEq } fun _ => elim xs e
private partial def elim (xs : Array Expr) (e : Expr) : M Expr :=
match e with
| .proj _ _ s => return e.updateProj! (← visit xs s)
| .forallE _ d b _ => return e.updateForallE! (← visit xs d) (← visit xs b)
| .lam _ d b _ => return e.updateLambdaE! (← visit xs d) (← visit xs b)
| .letE _ t v b _ => return e.updateLet! (← visit xs t) (← visit xs v) (← visit xs b)
| .mdata _ b => return e.updateMData! (← visit xs b)
| .app .. => e.withApp fun f args => elimApp xs f args
| .mvar _ => elimApp xs e #[]
| e => return e
/--
Given a metavariable with type `e`, kind `kind` and free/meta variables `xs` in its local context `lctx`,
create the type for a new auxiliary metavariable. These auxiliary metavariables are created by `elimMVar`.
See "Gruesome details" section in the beginning of the file.
Note: It is assumed that `xs` is the result of calling `collectForwardDeps` on a subset of variables in `lctx`.
-/
private partial def mkAuxMVarType (lctx : LocalContext) (xs : Array Expr) (kind : MetavarKind) (e : Expr) : M Expr := do
let e ← abstractRangeAux xs xs.size e
xs.size.foldRevM (init := e) fun i e => do
let x := xs[i]!
if x.isFVar then
match lctx.getFVar! x with
| LocalDecl.cdecl _ _ n type bi _ =>
let type := type.headBeta
let type ← abstractRangeAux xs i type
return Lean.mkForall n bi type e
| LocalDecl.ldecl _ _ n type value nonDep _ =>
let type := type.headBeta
let type ← abstractRangeAux xs i type
let value ← abstractRangeAux xs i value
let e := mkLet n type value e nonDep
match kind with
| MetavarKind.syntheticOpaque =>
-- See "Gruesome details" section in the beginning of the file
let e := e.liftLooseBVars 0 1
return mkForall n BinderInfo.default type e
| _ => pure e
else
-- `xs` may contain metavariables as "may dependencies" (see `findExprDependsOn`)
let mvarDecl := (← get).mctx.getDecl x.mvarId!
let type := mvarDecl.type.headBeta
let type ← abstractRangeAux xs i type
let id ← if mvarDecl.userName.isAnonymous then mkFreshBinderName else pure mvarDecl.userName
return Lean.mkForall id (← read).binderInfoForMVars type e
where
abstractRangeAux (xs : Array Expr) (i : Nat) (e : Expr) : M Expr := do
let e ← elim xs e
pure (e.abstractRange i xs)
/--
"Eliminate" the given variables `xs` from the context of the metavariable represented `mvarId`
by returning the application of a new metavariable whose type abstracts the forward dependencies
on `xs` after restricting it to the free variables in the local context of `mvarId`.
See details in the comment at the top of the file.
-/
private partial def elimMVar (xs : Array Expr) (mvarId : MVarId) (args : Array Expr) : M (Expr × Array Expr) := do
let mvarDecl := (← getMCtx).getDecl mvarId
let mvarLCtx := mvarDecl.lctx
let toRevert := getInScope mvarLCtx xs
if toRevert.size == 0 then
let args ← args.mapM (visit xs)
return (mkAppN (mkMVar mvarId) args, #[])
else
/- `newMVarKind` is the kind for the new auxiliary metavariable.
There is an alternative approach where we use
```
let newMVarKind := if !mctx.isAssignable mvarId || mvarDecl.isSyntheticOpaque then MetavarKind.syntheticOpaque else MetavarKind.natural
```
In this approach, we use the natural kind for the new auxiliary metavariable if the original metavariable is synthetic and assignable.
Since we mainly use synthetic metavariables for pending type class (TC) resolution problems,
this approach may minimize the number of TC resolution problems that may need to be resolved.
A potential disadvantage is that `isDefEq` will not eagerly use `synthPending` for natural metavariables.
That being said, we should try this approach as soon as we have an extensive test suite.
-/
let newMVarKind := if !(← mvarId.isAssignable) then MetavarKind.syntheticOpaque else mvarDecl.kind
let args ← args.mapM (visit xs)
-- Note that `toRevert` only contains free variables at this point since it is the result of `getInScope`;
-- after `collectForwardDeps`, this may no longer be the case because it may include metavariables
-- whose local contexts depend on `toRevert` (i.e. "may dependencies")
let toRevert ← collectForwardDeps mvarLCtx toRevert
let newMVarLCtx := reduceLocalContext mvarLCtx toRevert
let newLocalInsts := mvarDecl.localInstances.filter fun inst => toRevert.all fun x => inst.fvar != x
-- Remark: we must reset the cache before processing `mkAuxMVarType` because `toRevert` may not be equal to `xs`
let newMVarType ← withFreshCache do mkAuxMVarType mvarLCtx toRevert newMVarKind mvarDecl.type
let newMVarId := { name := (← get).ngen.curr }
let newMVar := mkMVar newMVarId
let result := mkMVarApp mvarLCtx newMVar toRevert newMVarKind
let numScopeArgs := mvarDecl.numScopeArgs + result.getAppNumArgs
modify fun s => { s with
mctx := s.mctx.addExprMVarDecl newMVarId Name.anonymous newMVarLCtx newLocalInsts newMVarType newMVarKind numScopeArgs,
ngen := s.ngen.next
}
if !mvarDecl.kind.isSyntheticOpaque then
mvarId.assign result
else
/- If `mvarId` is the lhs of a delayed assignment `?m #[x_1, ... x_n] := ?mvarPending`,
then `nestedFVars` is `#[x_1, ..., x_n]`.
In this case, `newMVarId` is also `syntheticOpaque` and we add the delayed assignment delayed assignment
```
?newMVar #[y_1, ..., y_m, x_1, ... x_n] := ?m
```
where `#[y_1, ..., y_m]` is `toRevert` after `collectForwardDeps`.
-/
let (mvarIdPending, nestedFVars) ← match (← getDelayedMVarAssignment? mvarId) with
| none => pure (mvarId, #[])
| some { fvars, mvarIdPending } => pure (mvarIdPending, fvars)
assignDelayedMVar newMVarId (toRevert ++ nestedFVars) mvarIdPending
return (mkAppN result args, toRevert)
private partial def elimApp (xs : Array Expr) (f : Expr) (args : Array Expr) : M Expr := do
match f with
| Expr.mvar mvarId =>
match (← getExprMVarAssignment? mvarId) with
| some newF =>
if newF.isLambda then
let args ← args.mapM (visit xs)
/- Arguments in `args` can become irrelevant after we beta reduce. -/
elim xs <| newF.betaRev args.reverse
else
elimApp xs newF args
| none =>
if (← read).mvarIdsToAbstract.contains mvarId then
return mkAppN f (← args.mapM (visit xs))
else
return (← elimMVar xs mvarId args).1
| _ =>
return mkAppN (← visit xs f) (← args.mapM (visit xs))
end
partial def elimMVarDeps (xs : Array Expr) (e : Expr) : M Expr :=
if !e.hasMVar then
return e
else
withFreshCache do
elim xs e
/--
Revert the variables `xs` from the local context of `mvarId`, returning
an expression representing the (new) reverted metavariable and the list of
variables that were actually reverted (this list will include any forward dependencies).
See details in the comment at the top of the file.
-/
partial def revert (xs : Array Expr) (mvarId : MVarId) : M (Expr × Array Expr) :=
withFreshCache do
elimMVar xs mvarId #[]
/--
Similar to `Expr.abstractRange`, but handles metavariables correctly.
It uses `elimMVarDeps` to ensure `e` and the type of the free variables `xs` do not
contain a metavariable `?m` s.t. local context of `?m` contains a free variable in `xs`.
-/
@[inline] def abstractRange (xs : Array Expr) (i : Nat) (e : Expr) : M Expr := do
let e ← elimMVarDeps xs e
pure (e.abstractRange i xs)
/--
Similar to `LocalContext.mkBinding`, but handles metavariables correctly.
If `usedOnly == true` then `forall` and `lambda` expressions are created only for used variables.
If `usedLetOnly == true` then `let` expressions are created only for used (let-) variables. -/
@[specialize] def mkBinding (isLambda : Bool) (lctx : LocalContext) (xs : Array Expr) (e : Expr) (usedOnly : Bool) (usedLetOnly : Bool) : M (Expr × Nat) := do
let e ← abstractRange xs xs.size e
xs.size.foldRevM (init := (e, 0)) fun i (e, num) => do
let x := xs[i]!
if x.isFVar then
match lctx.getFVar! x with
| LocalDecl.cdecl _ _ n type bi _ =>
if !usedOnly || e.hasLooseBVar 0 then
let type := type.headBeta;
let type ← abstractRange xs i type
if isLambda then
return (Lean.mkLambda n bi type e, num + 1)
else
return (Lean.mkForall n bi type e, num + 1)
else
return (e.lowerLooseBVars 1 1, num)
| LocalDecl.ldecl _ _ n type value nonDep _ =>
if !usedLetOnly || e.hasLooseBVar 0 then
let type ← abstractRange xs i type
let value ← abstractRange xs i value
return (mkLet n type value e nonDep, num + 1)
else
return (e.lowerLooseBVars 1 1, num)
else
let mvarDecl := (← get).mctx.getDecl x.mvarId!
let type := mvarDecl.type.headBeta
let type ← abstractRange xs i type
let id ← if mvarDecl.userName.isAnonymous then mkFreshBinderName else pure mvarDecl.userName
if isLambda then
return (Lean.mkLambda id (← read).binderInfoForMVars type e, num + 1)
else
return (Lean.mkForall id (← read).binderInfoForMVars type e, num + 1)
end MkBinding
structure MkBindingM.Context where
mainModule : Name
lctx : LocalContext
abbrev MkBindingM := ReaderT MkBindingM.Context MkBinding.MCore
def elimMVarDeps (xs : Array Expr) (e : Expr) (preserveOrder : Bool) : MkBindingM Expr := fun ctx =>
MkBinding.elimMVarDeps xs e { preserveOrder, mainModule := ctx.mainModule }
def revert (xs : Array Expr) (mvarId : MVarId) (preserveOrder : Bool) : MkBindingM (Expr × Array Expr) := fun ctx =>
MkBinding.revert xs mvarId { preserveOrder, mainModule := ctx.mainModule }
def mkBinding (isLambda : Bool) (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) (binderInfoForMVars := BinderInfo.implicit) : MkBindingM (Expr × Nat) := fun ctx =>
let mvarIdsToAbstract := xs.foldl (init := {}) fun s x => if x.isMVar then s.insert x.mvarId! else s
MkBinding.mkBinding isLambda ctx.lctx xs e usedOnly usedLetOnly { preserveOrder := false, binderInfoForMVars, mvarIdsToAbstract, mainModule := ctx.mainModule }
@[inline] def mkLambda (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) (binderInfoForMVars := BinderInfo.implicit) : MkBindingM Expr :=
return (← mkBinding (isLambda := true) xs e usedOnly usedLetOnly binderInfoForMVars).1
@[inline] def mkForall (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) (binderInfoForMVars := BinderInfo.implicit) : MkBindingM Expr :=
return (← mkBinding (isLambda := false) xs e usedOnly usedLetOnly binderInfoForMVars).1
@[inline] def abstractRange (e : Expr) (n : Nat) (xs : Array Expr) : MkBindingM Expr := fun ctx =>
MkBinding.abstractRange xs n e { preserveOrder := false, mainModule := ctx.mainModule }
@[inline] def collectForwardDeps (toRevert : Array Expr) (preserveOrder : Bool) : MkBindingM (Array Expr) := fun ctx =>
MkBinding.collectForwardDeps ctx.lctx toRevert { preserveOrder, mainModule := ctx.mainModule }
/--
`isWellFormed lctx e` returns true iff
- All locals in `e` are declared in `lctx`
- All metavariables `?m` in `e` have a local context which is a subprefix of `lctx` or are assigned, and the assignment is well-formed. -/
partial def isWellFormed [Monad m] [MonadMCtx m] (lctx : LocalContext) : Expr → m Bool
| .mdata _ e => isWellFormed lctx e
| .proj _ _ e => isWellFormed lctx e
| e@(.app f a) => pure (!e.hasExprMVar && !e.hasFVar) <||> (isWellFormed lctx f <&&> isWellFormed lctx a)
| e@(.lam _ d b _) => pure (!e.hasExprMVar && !e.hasFVar) <||> (isWellFormed lctx d <&&> isWellFormed lctx b)
| e@(.forallE _ d b _) => pure (!e.hasExprMVar && !e.hasFVar) <||> (isWellFormed lctx d <&&> isWellFormed lctx b)
| e@(.letE _ t v b _) => pure (!e.hasExprMVar && !e.hasFVar) <||> (isWellFormed lctx t <&&> isWellFormed lctx v <&&> isWellFormed lctx b)
| .const .. => return true
| .bvar .. => return true
| .sort .. => return true
| .lit .. => return true
| .mvar mvarId => do
let mvarDecl := (← getMCtx).getDecl mvarId;
if mvarDecl.lctx.isSubPrefixOf lctx then
return true
else match (← getExprMVarAssignment? mvarId) with
| none => return false
| some v => isWellFormed lctx v
| .fvar fvarId => return lctx.contains fvarId
namespace LevelMVarToParam
structure Context where
paramNamePrefix : Name
alreadyUsedPred : Name → Bool
except : LMVarId → Bool
structure State where
mctx : MetavarContext
paramNames : Array Name := #[]
nextParamIdx : Nat
cache : HashMap ExprStructEq Expr := {}
abbrev M := ReaderT Context <| StateM State
instance : MonadMCtx M where
getMCtx := return (← get).mctx
modifyMCtx f := modify fun s => { s with mctx := f s.mctx }
instance : MonadCache ExprStructEq Expr M where
findCached? e := return (← get).cache.find? e
cache e v := modify fun s => { s with cache := s.cache.insert e v }
partial def mkParamName : M Name := do
let ctx ← read
let s ← get
let newParamName := ctx.paramNamePrefix.appendIndexAfter s.nextParamIdx
if ctx.alreadyUsedPred newParamName then
modify fun s => { s with nextParamIdx := s.nextParamIdx + 1 }
mkParamName
else do
modify fun s => { s with nextParamIdx := s.nextParamIdx + 1, paramNames := s.paramNames.push newParamName }
pure newParamName
partial def visitLevel (u : Level) : M Level := do
match u with
| .succ v => return u.updateSucc! (← visitLevel v)
| .max v₁ v₂ => return u.updateMax! (← visitLevel v₁) (← visitLevel v₂)
| .imax v₁ v₂ => return u.updateIMax! (← visitLevel v₁) (← visitLevel v₂)
| .zero => return u
| .param .. => return u
| .mvar mvarId =>
match (← getLevelMVarAssignment? mvarId) with
| some v => visitLevel v
| none =>
if (← read).except mvarId then
return u
else
let p ← mkParamName
let p := mkLevelParam p
assignLevelMVar mvarId p
return p
partial def main (e : Expr) : M Expr :=
if !e.hasMVar then
return e
else
checkCache { val := e : ExprStructEq } fun _ => do
match e with
| .proj _ _ s => return e.updateProj! (← main s)
| .forallE _ d b _ => return e.updateForallE! (← main d) (← main b)
| .lam _ d b _ => return e.updateLambdaE! (← main d) (← main b)
| .letE _ t v b _ => return e.updateLet! (← main t) (← main v) (← main b)
| .app .. => e.withApp fun f args => visitApp f args
| .mdata _ b => return e.updateMData! (← main b)
| .const _ us => return e.updateConst! (← us.mapM visitLevel)
| .sort u => return e.updateSort! (← visitLevel u)
| .mvar .. => visitApp e #[]
| e => return e
where
visitApp (f : Expr) (args : Array Expr) : M Expr := do
match f with
| .mvar mvarId .. =>
match (← getExprMVarAssignment? mvarId) with
| some v => return (← visitApp v args).headBeta
| none => return mkAppN f (← args.mapM main)
| _ => return mkAppN (← main f) (← args.mapM main)
end LevelMVarToParam
structure UnivMVarParamResult where
mctx : MetavarContext
newParamNames : Array Name
nextParamIdx : Nat
expr : Expr
def levelMVarToParam (mctx : MetavarContext) (alreadyUsedPred : Name → Bool) (except : LMVarId → Bool) (e : Expr) (paramNamePrefix : Name := `u) (nextParamIdx : Nat := 1)
: UnivMVarParamResult :=
let (e, s) := LevelMVarToParam.main e { except, paramNamePrefix, alreadyUsedPred } { mctx, nextParamIdx }
{ mctx := s.mctx
newParamNames := s.paramNames
nextParamIdx := s.nextParamIdx
expr := e }
def getExprAssignmentDomain (mctx : MetavarContext) : Array MVarId :=
mctx.eAssignment.foldl (init := #[]) fun a mvarId _ => Array.push a mvarId
end MetavarContext
end Lean
|
78f4502300ffe7077c6cec4f0bef6e9261dc9928 | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/data/padics/padic_integers.lean | bb91f19f58070153e8f9439fec65ee4e8a364f63 | [
"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 | 19,834 | lean | /-
Copyright (c) 2018 Robert Y. Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Robert Y. Lewis, Mario Carneiro, Johan Commelin
-/
import data.int.modeq
import data.zmod.basic
import linear_algebra.adic_completion
import data.padics.padic_numbers
import ring_theory.discrete_valuation_ring
import topology.metric_space.cau_seq_filter
/-!
# p-adic integers
This file defines the p-adic integers `ℤ_p` as the subtype of `ℚ_p` with norm `≤ 1`.
We show that `ℤ_p`
* is complete
* is nonarchimedean
* is a normed ring
* is a local ring
* is a discrete valuation ring
The relation between `ℤ_[p]` and `zmod p` is established in another file.
## Important definitions
* `padic_int` : the type of p-adic numbers
## Notation
We introduce the notation `ℤ_[p]` for the p-adic integers.
## Implementation notes
Much, but not all, of this file assumes that `p` is prime. This assumption is inferred automatically
by taking `[fact (nat.prime p)] as a type class argument.
Coercions into `ℤ_p` are set up to work with the `norm_cast` tactic.
## References
* [F. Q. Gouêva, *p-adic numbers*][gouvea1997]
* [R. Y. Lewis, *A formal proof of Hensel's lemma over the p-adic integers*][lewis2019]
* <https://en.wikipedia.org/wiki/P-adic_number>
## Tags
p-adic, p adic, padic, p-adic integer
-/
open nat padic metric local_ring
noncomputable theory
open_locale classical
/-- The p-adic integers ℤ_p are the p-adic numbers with norm ≤ 1. -/
def padic_int (p : ℕ) [fact p.prime] := {x : ℚ_[p] // ∥x∥ ≤ 1}
notation `ℤ_[`p`]` := padic_int p
namespace padic_int
/-! ### Ring structure and coercion to `ℚ_[p]` -/
variables {p : ℕ} [fact p.prime]
instance : has_coe ℤ_[p] ℚ_[p] := ⟨subtype.val⟩
lemma ext {x y : ℤ_[p]} : (x : ℚ_[p]) = y → x = y := subtype.ext_iff_val.2
/-- Addition on ℤ_p is inherited from ℚ_p. -/
instance : has_add ℤ_[p] :=
⟨λ ⟨x, hx⟩ ⟨y, hy⟩, ⟨x+y,
le_trans (padic_norm_e.nonarchimedean _ _) (max_le_iff.2 ⟨hx,hy⟩)⟩⟩
/-- Multiplication on ℤ_p is inherited from ℚ_p. -/
instance : has_mul ℤ_[p] :=
⟨λ ⟨x, hx⟩ ⟨y, hy⟩, ⟨x*y,
begin rw padic_norm_e.mul, apply mul_le_one; {assumption <|> apply norm_nonneg} end⟩⟩
/-- Negation on ℤ_p is inherited from ℚ_p. -/
instance : has_neg ℤ_[p] :=
⟨λ ⟨x, hx⟩, ⟨-x, by simpa⟩⟩
/-- Zero on ℤ_p is inherited from ℚ_p. -/
instance : has_zero ℤ_[p] :=
⟨⟨0, by norm_num⟩⟩
instance : inhabited ℤ_[p] := ⟨0⟩
/-- One on ℤ_p is inherited from ℚ_p. -/
instance : has_one ℤ_[p] :=
⟨⟨1, by norm_num⟩⟩
@[simp] lemma mk_zero {h} : (⟨0, h⟩ : ℤ_[p]) = (0 : ℤ_[p]) := rfl
@[simp] lemma val_eq_coe (z : ℤ_[p]) : z.val = z := rfl
@[simp, norm_cast] lemma coe_add : ∀ (z1 z2 : ℤ_[p]), ((z1 + z2 : ℤ_[p]) : ℚ_[p]) = z1 + z2
| ⟨_, _⟩ ⟨_, _⟩ := rfl
@[simp, norm_cast] lemma coe_mul : ∀ (z1 z2 : ℤ_[p]), ((z1 * z2 : ℤ_[p]) : ℚ_[p]) = z1 * z2
| ⟨_, _⟩ ⟨_, _⟩ := rfl
@[simp, norm_cast] lemma coe_neg : ∀ (z1 : ℤ_[p]), ((-z1 : ℤ_[p]) : ℚ_[p]) = -z1
| ⟨_, _⟩ := rfl
@[simp, norm_cast] lemma coe_one : ((1 : ℤ_[p]) : ℚ_[p]) = 1 := rfl
@[simp, norm_cast] lemma coe_coe : ∀ n : ℕ, ((n : ℤ_[p]) : ℚ_[p]) = n
| 0 := rfl
| (k+1) := by simp [coe_coe]
@[simp, norm_cast] lemma coe_coe_int : ∀ (z : ℤ), ((z : ℤ_[p]) : ℚ_[p]) = z
| (int.of_nat n) := by simp
| -[1+n] := by simp
@[simp, norm_cast] lemma coe_zero : ((0 : ℤ_[p]) : ℚ_[p]) = 0 := rfl
instance : ring ℤ_[p] :=
begin
refine { add := (+),
mul := (*),
neg := has_neg.neg,
zero := 0,
one := 1,
.. };
intros; ext; simp; ring
end
/-- The coercion from ℤ[p] to ℚ[p] as a ring homomorphism. -/
def coe.ring_hom : ℤ_[p] →+* ℚ_[p] :=
{ to_fun := (coe : ℤ_[p] → ℚ_[p]),
map_zero' := rfl,
map_one' := rfl,
map_mul' := coe_mul,
map_add' := coe_add }
@[simp, norm_cast] lemma coe_sub : ∀ (z1 z2 : ℤ_[p]), (↑(z1 - z2) : ℚ_[p]) = ↑z1 - ↑z2 :=
coe.ring_hom.map_sub
@[simp, norm_cast] lemma coet_pow (x : ℤ_[p]) (n : ℕ) : (↑(x^n) : ℚ_[p]) = (↑x : ℚ_[p])^n :=
coe.ring_hom.map_pow x n
@[simp] lemma mk_coe : ∀ (k : ℤ_[p]), (⟨k, k.2⟩ : ℤ_[p]) = k
| ⟨_, _⟩ := rfl
/-- The inverse of a p-adic integer with norm equal to 1 is also a p-adic integer. Otherwise, the
inverse is defined to be 0. -/
def inv : ℤ_[p] → ℤ_[p]
| ⟨k, _⟩ := if h : ∥k∥ = 1 then ⟨1/k, by simp [h]⟩ else 0
instance : char_zero ℤ_[p] :=
{ cast_injective :=
λ m n h, cast_injective $
show (m:ℚ_[p]) = n, by { rw subtype.ext_iff at h, norm_cast at h, exact h } }
@[simp, norm_cast] lemma coe_int_eq (z1 z2 : ℤ) : (z1 : ℤ_[p]) = z2 ↔ z1 = z2 :=
suffices (z1 : ℚ_[p]) = z2 ↔ z1 = z2, from iff.trans (by norm_cast) this,
by norm_cast
/--
A sequence of integers that is Cauchy with respect to the `p`-adic norm
converges to a `p`-adic integer.
-/
def of_int_seq (seq : ℕ → ℤ) (h : is_cau_seq (padic_norm p) (λ n, seq n)) : ℤ_[p] :=
⟨⟦⟨_, h⟩⟧,
show ↑(padic_seq.norm _) ≤ (1 : ℝ), begin
rw padic_seq.norm,
split_ifs with hne; norm_cast,
{ exact zero_le_one },
{ apply padic_norm.of_int }
end ⟩
end padic_int
namespace padic_int
/-!
### Instances
We now show that `ℤ_[p]` is a
* complete metric space
* normed ring
* integral domain
-/
variables (p : ℕ) [fact p.prime]
instance : metric_space ℤ_[p] := subtype.metric_space
instance complete_space : complete_space ℤ_[p] :=
begin
delta padic_int,
rw [complete_space_iff_is_complete_range uniform_embedding_subtype_coe,
subtype.range_coe_subtype],
have : is_complete (closed_ball (0 : ℚ_[p]) 1) := is_closed_ball.is_complete,
simpa [closed_ball],
end
instance : has_norm ℤ_[p] := ⟨λ z, ∥(z : ℚ_[p])∥⟩
variables {p}
protected lemma mul_comm : ∀ z1 z2 : ℤ_[p], z1*z2 = z2*z1
| ⟨q1, h1⟩ ⟨q2, h2⟩ := show (⟨q1*q2, _⟩ : ℤ_[p]) = ⟨q2*q1, _⟩, by simp [_root_.mul_comm]
protected lemma zero_ne_one : (0 : ℤ_[p]) ≠ 1 :=
show (⟨(0 : ℚ_[p]), _⟩ : ℤ_[p]) ≠ ⟨(1 : ℚ_[p]), _⟩, from mt subtype.ext_iff_val.1 zero_ne_one
protected lemma eq_zero_or_eq_zero_of_mul_eq_zero :
∀ (a b : ℤ_[p]), a * b = 0 → a = 0 ∨ b = 0
| ⟨a, ha⟩ ⟨b, hb⟩ := λ h : (⟨a * b, _⟩ : ℤ_[p]) = ⟨0, _⟩,
have a * b = 0, from subtype.ext_iff_val.1 h,
(mul_eq_zero.1 this).elim
(λ h1, or.inl (by simp [h1]; refl))
(λ h2, or.inr (by simp [h2]; refl))
lemma norm_def {z : ℤ_[p]} : ∥z∥ = ∥(z : ℚ_[p])∥ := rfl
variables (p)
instance : normed_comm_ring ℤ_[p] :=
{ dist_eq := λ ⟨_, _⟩ ⟨_, _⟩, rfl,
norm_mul := λ ⟨_, _⟩ ⟨_, _⟩, norm_mul_le _ _,
mul_comm := padic_int.mul_comm }
instance : norm_one_class ℤ_[p] := ⟨norm_def.trans norm_one⟩
instance is_absolute_value : is_absolute_value (λ z : ℤ_[p], ∥z∥) :=
{ abv_nonneg := norm_nonneg,
abv_eq_zero := λ ⟨_, _⟩, by simp [norm_eq_zero],
abv_add := λ ⟨_,_⟩ ⟨_, _⟩, norm_add_le _ _,
abv_mul := λ _ _, by simp only [norm_def, padic_norm_e.mul, padic_int.coe_mul]}
variables {p}
instance : integral_domain ℤ_[p] :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := λ x y, padic_int.eq_zero_or_eq_zero_of_mul_eq_zero x y,
exists_pair_ne := ⟨0, 1, padic_int.zero_ne_one⟩,
.. padic_int.normed_comm_ring p }
end padic_int
namespace padic_int
/-! ### Norm -/
variables {p : ℕ} [fact p.prime]
lemma norm_le_one : ∀ z : ℤ_[p], ∥z∥ ≤ 1
| ⟨_, h⟩ := h
@[simp] lemma norm_mul (z1 z2 : ℤ_[p]) : ∥z1 * z2∥ = ∥z1∥ * ∥z2∥ :=
by simp [norm_def]
@[simp] lemma norm_pow (z : ℤ_[p]) : ∀ n : ℕ, ∥z^n∥ = ∥z∥^n
| 0 := by simp
| (k+1) := show ∥z*z^k∥ = ∥z∥*∥z∥^k, by {rw norm_mul, congr, apply norm_pow}
theorem nonarchimedean : ∀ (q r : ℤ_[p]), ∥q + r∥ ≤ max (∥q∥) (∥r∥)
| ⟨_, _⟩ ⟨_, _⟩ := padic_norm_e.nonarchimedean _ _
theorem norm_add_eq_max_of_ne : ∀ {q r : ℤ_[p]}, ∥q∥ ≠ ∥r∥ → ∥q+r∥ = max (∥q∥) (∥r∥)
| ⟨_, _⟩ ⟨_, _⟩ := padic_norm_e.add_eq_max_of_ne
lemma norm_eq_of_norm_add_lt_right {z1 z2 : ℤ_[p]}
(h : ∥z1 + z2∥ < ∥z2∥) : ∥z1∥ = ∥z2∥ :=
by_contradiction $ λ hne,
not_lt_of_ge (by rw norm_add_eq_max_of_ne hne; apply le_max_right) h
lemma norm_eq_of_norm_add_lt_left {z1 z2 : ℤ_[p]}
(h : ∥z1 + z2∥ < ∥z1∥) : ∥z1∥ = ∥z2∥ :=
by_contradiction $ λ hne,
not_lt_of_ge (by rw norm_add_eq_max_of_ne hne; apply le_max_left) h
@[simp] lemma padic_norm_e_of_padic_int (z : ℤ_[p]) : ∥(↑z : ℚ_[p])∥ = ∥z∥ :=
by simp [norm_def]
lemma norm_int_cast_eq_padic_norm (z : ℤ) : ∥(z : ℤ_[p])∥ = ∥(z : ℚ_[p])∥ :=
by simp [norm_def]
@[simp] lemma norm_eq_padic_norm {q : ℚ_[p]} (hq : ∥q∥ ≤ 1) :
@norm ℤ_[p] _ ⟨q, hq⟩ = ∥q∥ := rfl
@[simp] lemma norm_p : ∥(p : ℤ_[p])∥ = p⁻¹ :=
show ∥((p : ℤ_[p]) : ℚ_[p])∥ = p⁻¹, by exact_mod_cast padic_norm_e.norm_p
@[simp] lemma norm_p_pow (n : ℕ) : ∥(p : ℤ_[p])^n∥ = p^(-n:ℤ) :=
show ∥((p^n : ℤ_[p]) : ℚ_[p])∥ = p^(-n:ℤ),
by { convert padic_norm_e.norm_p_pow n, simp, }
private def cau_seq_to_rat_cau_seq (f : cau_seq ℤ_[p] norm) :
cau_seq ℚ_[p] (λ a, ∥a∥) :=
⟨ λ n, f n,
λ _ hε, by simpa [norm, norm_def] using f.cauchy hε ⟩
variables (p)
instance complete : cau_seq.is_complete ℤ_[p] norm :=
⟨ λ f,
have hqn : ∥cau_seq.lim (cau_seq_to_rat_cau_seq f)∥ ≤ 1,
from padic_norm_e_lim_le zero_lt_one (λ _, norm_le_one _),
⟨ ⟨_, hqn⟩,
λ ε, by simpa [norm, norm_def] using cau_seq.equiv_lim (cau_seq_to_rat_cau_seq f) ε⟩⟩
end padic_int
namespace padic_int
variables (p : ℕ) [hp_prime : fact p.prime]
include hp_prime
lemma exists_pow_neg_lt {ε : ℝ} (hε : 0 < ε) :
∃ (k : ℕ), ↑p ^ -((k : ℕ) : ℤ) < ε :=
begin
obtain ⟨k, hk⟩ := exists_nat_gt ε⁻¹,
use k,
rw ← inv_lt_inv hε (_root_.fpow_pos_of_pos _ _),
{ rw [fpow_neg, inv_inv', fpow_coe_nat],
apply lt_of_lt_of_le hk,
norm_cast,
apply le_of_lt,
convert nat.lt_pow_self _ _ using 1,
exact hp_prime.one_lt },
{ exact_mod_cast hp_prime.pos }
end
lemma exists_pow_neg_lt_rat {ε : ℚ} (hε : 0 < ε) :
∃ (k : ℕ), ↑p ^ -((k : ℕ) : ℤ) < ε :=
begin
obtain ⟨k, hk⟩ := @exists_pow_neg_lt p _ ε (by exact_mod_cast hε),
use k,
rw (show (p : ℝ) = (p : ℚ), by simp) at hk,
exact_mod_cast hk
end
variable {p}
lemma norm_int_lt_one_iff_dvd (k : ℤ) : ∥(k : ℤ_[p])∥ < 1 ↔ ↑p ∣ k :=
suffices ∥(k : ℚ_[p])∥ < 1 ↔ ↑p ∣ k, by rwa norm_int_cast_eq_padic_norm,
padic_norm_e.norm_int_lt_one_iff_dvd k
lemma norm_int_le_pow_iff_dvd {k : ℤ} {n : ℕ} : ∥(k : ℤ_[p])∥ ≤ ((↑p)^(-n : ℤ)) ↔ ↑p^n ∣ k :=
suffices ∥(k : ℚ_[p])∥ ≤ ((↑p)^(-n : ℤ)) ↔ ↑(p^n) ∣ k, by simpa [norm_int_cast_eq_padic_norm],
padic_norm_e.norm_int_le_pow_iff_dvd _ _
/-! ### Valuation on `ℤ_[p]` -/
/-- `padic_int.valuation` lifts the p-adic valuation on `ℚ` to `ℤ_[p]`. -/
def valuation (x : ℤ_[p]) := padic.valuation (x : ℚ_[p])
lemma norm_eq_pow_val {x : ℤ_[p]} (hx : x ≠ 0) :
∥x∥ = p^(-x.valuation) :=
begin
convert padic.norm_eq_pow_val _,
contrapose! hx,
exact subtype.val_injective hx
end
@[simp] lemma valuation_zero : valuation (0 : ℤ_[p]) = 0 :=
padic.valuation_zero
@[simp] lemma valuation_one : valuation (1 : ℤ_[p]) = 0 :=
padic.valuation_one
@[simp] lemma valuation_p : valuation (p : ℤ_[p]) = 1 :=
by simp [valuation, -cast_eq_of_rat_of_nat]
lemma valuation_nonneg (x : ℤ_[p]) : 0 ≤ x.valuation :=
begin
by_cases hx : x = 0,
{ simp [hx] },
have h : (1 : ℝ) < p := by exact_mod_cast hp_prime.one_lt,
rw [← neg_nonpos, ← (fpow_strict_mono h).le_iff_le],
show (p : ℝ) ^ -valuation x ≤ p ^ 0,
rw [← norm_eq_pow_val hx],
simpa using x.property,
end
@[simp] lemma valuation_p_pow_mul (n : ℕ) (c : ℤ_[p]) (hc : c ≠ 0) :
(↑p ^ n * c).valuation = n + c.valuation :=
begin
have : ∥↑p ^ n * c∥ = ∥(p ^ n : ℤ_[p])∥ * ∥c∥,
{ exact norm_mul _ _ },
have aux : ↑p ^ n * c ≠ 0,
{ contrapose! hc, rw mul_eq_zero at hc, cases hc,
{ refine (hp_prime.ne_zero _).elim,
exact_mod_cast (pow_eq_zero hc) },
{ exact hc } },
rwa [norm_eq_pow_val aux, norm_p_pow, norm_eq_pow_val hc,
← fpow_add, ← neg_add, fpow_inj, neg_inj] at this,
{ exact_mod_cast hp_prime.pos },
{ exact_mod_cast hp_prime.ne_one },
{ exact_mod_cast hp_prime.ne_zero },
end
section units
/-! ### Units of `ℤ_[p]` -/
local attribute [reducible] padic_int
lemma mul_inv : ∀ {z : ℤ_[p]}, ∥z∥ = 1 → z * z.inv = 1
| ⟨k, _⟩ h :=
begin
have hk : k ≠ 0, from λ h', @zero_ne_one ℚ_[p] _ _ (by simpa [h'] using h),
unfold padic_int.inv, split_ifs,
{ change (⟨k * (1/k), _⟩ : ℤ_[p]) = 1,
simp [hk], refl },
{ apply subtype.ext_iff_val.2, simp [mul_inv_cancel hk] }
end
lemma inv_mul {z : ℤ_[p]} (hz : ∥z∥ = 1) : z.inv * z = 1 :=
by rw [mul_comm, mul_inv hz]
lemma is_unit_iff {z : ℤ_[p]} : is_unit z ↔ ∥z∥ = 1 :=
⟨λ h, begin
rcases is_unit_iff_dvd_one.1 h with ⟨w, eq⟩,
refine le_antisymm (norm_le_one _) _,
have := mul_le_mul_of_nonneg_left (norm_le_one w) (norm_nonneg z),
rwa [mul_one, ← norm_mul, ← eq, norm_one] at this
end, λ h, ⟨⟨z, z.inv, mul_inv h, inv_mul h⟩, rfl⟩⟩
lemma norm_lt_one_add {z1 z2 : ℤ_[p]} (hz1 : ∥z1∥ < 1) (hz2 : ∥z2∥ < 1) : ∥z1 + z2∥ < 1 :=
lt_of_le_of_lt (nonarchimedean _ _) (max_lt hz1 hz2)
lemma norm_lt_one_mul {z1 z2 : ℤ_[p]} (hz2 : ∥z2∥ < 1) : ∥z1 * z2∥ < 1 :=
calc ∥z1 * z2∥ = ∥z1∥ * ∥z2∥ : by simp
... < 1 : mul_lt_one_of_nonneg_of_lt_one_right (norm_le_one _) (norm_nonneg _) hz2
@[simp] lemma mem_nonunits {z : ℤ_[p]} : z ∈ nonunits ℤ_[p] ↔ ∥z∥ < 1 :=
by rw lt_iff_le_and_ne; simp [norm_le_one z, nonunits, is_unit_iff]
/-- A `p`-adic number `u` with `∥u∥ = 1` is a unit of `ℤ_[p]`. -/
def mk_units {u : ℚ_[p]} (h : ∥u∥ = 1) : units ℤ_[p] :=
let z : ℤ_[p] := ⟨u, le_of_eq h⟩ in ⟨z, z.inv, mul_inv h, inv_mul h⟩
@[simp]
lemma mk_units_eq {u : ℚ_[p]} (h : ∥u∥ = 1) : ((mk_units h : ℤ_[p]) : ℚ_[p]) = u :=
rfl
@[simp] lemma norm_units (u : units ℤ_[p]) : ∥(u : ℤ_[p])∥ = 1 :=
is_unit_iff.mp $ by simp
/-- `unit_coeff hx` is the unit `u` in the unique representation `x = u * p ^ n`.
See `unit_coeff_spec`. -/
def unit_coeff {x : ℤ_[p]} (hx : x ≠ 0) : units ℤ_[p] :=
let u : ℚ_[p] := x*p^(-x.valuation) in
have hu : ∥u∥ = 1,
by simp [hx, nat.fpow_ne_zero_of_pos (by exact_mod_cast hp_prime.pos) x.valuation,
norm_eq_pow_val, fpow_neg, inv_mul_cancel, -cast_eq_of_rat_of_nat],
mk_units hu
@[simp] lemma unit_coeff_coe {x : ℤ_[p]} (hx : x ≠ 0) :
(unit_coeff hx : ℚ_[p]) = x * p ^ (-x.valuation) := rfl
lemma unit_coeff_spec {x : ℤ_[p]} (hx : x ≠ 0) :
x = (unit_coeff hx : ℤ_[p]) * p ^ int.nat_abs (valuation x) :=
begin
apply subtype.coe_injective,
push_cast,
have repr : (x : ℚ_[p]) = (unit_coeff hx) * p ^ x.valuation,
{ rw [unit_coeff_coe, mul_assoc, ← fpow_add],
{ simp },
{ exact_mod_cast hp_prime.ne_zero } },
convert repr using 2,
rw [← fpow_coe_nat, int.nat_abs_of_nonneg (valuation_nonneg x)],
end
end units
section norm_le_iff
/-! ### Various characterizations of open unit balls -/
lemma norm_le_pow_iff_le_valuation (x : ℤ_[p]) (hx : x ≠ 0) (n : ℕ) :
∥x∥ ≤ p ^ (-n : ℤ) ↔ ↑n ≤ x.valuation :=
begin
rw norm_eq_pow_val hx,
lift x.valuation to ℕ using x.valuation_nonneg with k hk,
simp only [int.coe_nat_le, fpow_neg, fpow_coe_nat],
have aux : ∀ n : ℕ, 0 < (p ^ n : ℝ),
{ apply pow_pos, exact_mod_cast nat.prime.pos ‹_› },
rw [inv_le_inv (aux _) (aux _)],
have : p ^ n ≤ p ^ k ↔ n ≤ k := (pow_right_strict_mono (nat.prime.two_le ‹_›)).le_iff_le,
rw [← this],
norm_cast,
end
lemma mem_span_pow_iff_le_valuation (x : ℤ_[p]) (hx : x ≠ 0) (n : ℕ) :
x ∈ (ideal.span {p ^ n} : ideal ℤ_[p]) ↔ ↑n ≤ x.valuation :=
begin
rw [ideal.mem_span_singleton],
split,
{ rintro ⟨c, rfl⟩,
suffices : c ≠ 0,
{ rw [valuation_p_pow_mul _ _ this, le_add_iff_nonneg_right], apply valuation_nonneg, },
contrapose! hx, rw [hx, mul_zero], },
{ rw [unit_coeff_spec hx] { occs := occurrences.pos [2] },
lift x.valuation to ℕ using x.valuation_nonneg with k hk,
simp only [int.nat_abs_of_nat, is_unit_unit, is_unit.dvd_mul_left, int.coe_nat_le],
intro H,
obtain ⟨k, rfl⟩ := nat.exists_eq_add_of_le H,
simp only [pow_add, dvd_mul_right], }
end
lemma norm_le_pow_iff_mem_span_pow (x : ℤ_[p]) (n : ℕ) :
∥x∥ ≤ p ^ (-n : ℤ) ↔ x ∈ (ideal.span {p ^ n} : ideal ℤ_[p]) :=
begin
by_cases hx : x = 0,
{ subst hx,
simp only [norm_zero, fpow_neg, fpow_coe_nat, inv_nonneg, iff_true, submodule.zero_mem],
exact_mod_cast nat.zero_le _ },
rw [norm_le_pow_iff_le_valuation x hx, mem_span_pow_iff_le_valuation x hx],
end
lemma norm_le_pow_iff_norm_lt_pow_add_one (x : ℤ_[p]) (n : ℤ) :
∥x∥ ≤ p ^ n ↔ ∥x∥ < p ^ (n + 1) :=
begin
have aux : ∀ n : ℤ, 0 < (p ^ n : ℝ),
{ apply nat.fpow_pos_of_pos, exact nat.prime.pos ‹_› },
by_cases hx0 : x = 0, { simp [hx0, norm_zero, aux, le_of_lt (aux _)], },
rw norm_eq_pow_val hx0,
have h1p : 1 < (p : ℝ), { exact_mod_cast nat.prime.one_lt ‹_› },
have H := fpow_strict_mono h1p,
rw [H.le_iff_le, H.lt_iff_lt, int.lt_add_one_iff],
end
lemma norm_lt_pow_iff_norm_le_pow_sub_one (x : ℤ_[p]) (n : ℤ) :
∥x∥ < p ^ n ↔ ∥x∥ ≤ p ^ (n - 1) :=
by rw [norm_le_pow_iff_norm_lt_pow_add_one, sub_add_cancel]
lemma norm_lt_one_iff_dvd (x : ℤ_[p]) : ∥x∥ < 1 ↔ ↑p ∣ x :=
begin
have := norm_le_pow_iff_mem_span_pow x 1,
rw [ideal.mem_span_singleton, pow_one] at this,
rw [← this, norm_le_pow_iff_norm_lt_pow_add_one],
simp only [fpow_zero, int.coe_nat_zero, int.coe_nat_succ, add_left_neg, zero_add],
end
@[simp] lemma pow_p_dvd_int_iff (n : ℕ) (a : ℤ) : (p ^ n : ℤ_[p]) ∣ a ↔ ↑p ^ n ∣ a :=
by rw [← norm_int_le_pow_iff_dvd, norm_le_pow_iff_mem_span_pow, ideal.mem_span_singleton]
end norm_le_iff
section dvr
/-! ### Discrete valuation ring -/
instance : local_ring ℤ_[p] :=
local_of_nonunits_ideal zero_ne_one $ λ x y, by simp; exact norm_lt_one_add
lemma p_nonnunit : (p : ℤ_[p]) ∈ nonunits ℤ_[p] :=
have (p : ℝ)⁻¹ < 1, from inv_lt_one $ by exact_mod_cast hp_prime.one_lt,
by simp [this]
lemma maximal_ideal_eq_span_p : maximal_ideal ℤ_[p] = ideal.span {p} :=
begin
apply le_antisymm,
{ intros x hx,
rw ideal.mem_span_singleton,
simp only [local_ring.mem_maximal_ideal, mem_nonunits] at hx,
rwa ← norm_lt_one_iff_dvd, },
{ rw [ideal.span_le, set.singleton_subset_iff], exact p_nonnunit }
end
lemma prime_p : prime (p : ℤ_[p]) :=
begin
rw [← ideal.span_singleton_prime, ← maximal_ideal_eq_span_p],
{ apply_instance },
{ exact_mod_cast hp_prime.ne_zero }
end
lemma irreducible_p : irreducible (p : ℤ_[p]) :=
irreducible_of_prime prime_p
instance : discrete_valuation_ring ℤ_[p] :=
discrete_valuation_ring.of_has_unit_mul_pow_irreducible_factorization
⟨p, irreducible_p, λ x hx, ⟨x.valuation.nat_abs, unit_coeff hx,
by rw [mul_comm, ← unit_coeff_spec hx]⟩⟩
lemma ideal_eq_span_pow_p {s : ideal ℤ_[p]} (hs : s ≠ ⊥) :
∃ n : ℕ, s = ideal.span {p ^ n} :=
discrete_valuation_ring.ideal_eq_span_pow_irreducible hs irreducible_p
end dvr
end padic_int
|
5104e78bac962f580204f4c4fc0229f9779c2e54 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/tactic/hint.lean | 4be3aaa342a26ce8a24c40a05230c91148a92f1b | [
"Apache-2.0"
] | permissive | jjgarzella/mathlib | 96a345378c4e0bf26cf604aed84f90329e4896a2 | 395d8716c3ad03747059d482090e2bb97db612c8 | refs/heads/master | 1,686,480,124,379 | 1,625,163,323,000 | 1,625,163,323,000 | 281,190,421 | 2 | 0 | Apache-2.0 | 1,595,268,170,000 | 1,595,268,169,000 | null | UTF-8 | Lean | false | false | 3,969 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import tactic.solve_by_elim
import tactic.interactive
namespace tactic
namespace hint
/-- An attribute marking a `tactic unit` or `tactic string` which should be used by the `hint`
tactic. -/
@[user_attribute] meta def hint_tactic_attribute : user_attribute := {
name := `hint_tactic,
descr := "A tactic that should be tried by `hint`."
}
add_tactic_doc
{ name := "hint_tactic",
category := doc_category.attr,
decl_names := [`tactic.hint.hint_tactic_attribute],
tags := ["rewrite", "search"] }
open lean lean.parser interactive
private meta def add_tactic_hint (n : name) (t : expr) : tactic unit :=
do
add_decl $ declaration.defn n [] `(tactic string) t reducibility_hints.opaque ff,
hint_tactic_attribute.set n () tt
/--
`add_hint_tactic t` runs the tactic `t` whenever `hint` is invoked.
The typical use case is `add_hint_tactic "foo"` for some interactive tactic `foo`.
-/
@[user_command] meta def add_hint_tactic (_ : parse (tk "add_hint_tactic")) : parser unit :=
do n ← parser.pexpr,
e ← to_expr n,
s ← eval_expr string e,
let t := "`[" ++ s ++ "]",
(t, _) ← with_input parser.pexpr t,
of_tactic $ do
let h := s <.> "_hint",
t ← to_expr ``(do %%t, pure %%n),
add_tactic_hint h t.
add_tactic_doc
{ name := "add_hint_tactic",
category := doc_category.cmd,
decl_names := [`tactic.hint.add_hint_tactic],
tags := ["search"] }
add_hint_tactic "refl"
add_hint_tactic "exact dec_trivial"
add_hint_tactic "assumption"
-- tidy does something better here: it suggests the actual "intros X Y f" string.
-- perhaps add a wrapper?
add_hint_tactic "intro"
add_hint_tactic "apply_auto_param"
add_hint_tactic "dsimp at *"
add_hint_tactic "simp at *" -- TODO hook up to squeeze_simp?
add_hint_tactic "fconstructor"
add_hint_tactic "injections_and_clear"
add_hint_tactic "solve_by_elim"
add_hint_tactic "unfold_coes"
add_hint_tactic "unfold_aux"
end hint
/--
Report a list of tactics that can make progress against the current goal,
and for each such tactic, the number of remaining goals afterwards.
-/
meta def hint : tactic (list (string × ℕ)) :=
do
names ← attribute.get_instances `hint_tactic,
focus1 $ try_all_sorted (names.reverse.map name_to_tactic)
namespace interactive
/--
Report a list of tactics that can make progress against the current goal.
-/
meta def hint : tactic unit :=
do
hints ← tactic.hint,
if hints.length = 0 then
fail "no hints available"
else do
t ← hints.nth 0,
if t.2 = 0 then do
trace "the following tactics solve the goal:\n----",
(hints.filter (λ p : string × ℕ, p.2 = 0)).mmap' (λ p, tactic.trace format!"Try this: {p.1}")
else do
trace "the following tactics make progress:\n----",
hints.mmap' (λ p, tactic.trace format!"Try this: {p.1}")
/--
`hint` lists possible tactics which will make progress (that is, not fail) against the current goal.
```lean
example {P Q : Prop} (p : P) (h : P → Q) : Q :=
begin
hint,
/- the following tactics make progress:
----
Try this: solve_by_elim
Try this: finish
Try this: tauto
-/
solve_by_elim,
end
```
You can add a tactic to the list that `hint` tries by either using
1. `attribute [hint_tactic] my_tactic`, if `my_tactic` is already of type `tactic string`
(`tactic unit` is allowed too, in which case the printed string will be the name of the
tactic), or
2. `add_hint_tactic "my_tactic"`, specifying a string which works as an interactive tactic.
-/
add_tactic_doc
{ name := "hint",
category := doc_category.tactic,
decl_names := [`tactic.interactive.hint],
tags := ["search", "Try this"] }
end interactive
end tactic
|
2ff4bf357956ca6728ea0c326e1d0a8b5bc22a58 | 568eee7258acff70c0460211026cba9092199e52 | /library/init/data/nat/lemmas.lean | b4d0410f43c05558797c8f82b56f6c8c6a0eb2eb | [
"Apache-2.0"
] | permissive | digama0/lean | 3495089da1afce44e737770e667c7c7a75293698 | 25b46580d9f57be6242dcb3bf764ff11cd19b580 | refs/heads/master | 1,624,905,273,289 | 1,623,415,532,000 | 1,623,415,532,000 | 39,644,278 | 0 | 0 | null | 1,437,754,440,000 | 1,437,754,440,000 | null | UTF-8 | Lean | false | false | 49,007 | 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, Jeremy Avigad
-/
prelude
import init.data.nat.basic init.data.nat.div init.meta init.algebra.functions
universes u
namespace nat
attribute [pre_smt] nat_zero_eq_zero
protected lemma add_comm : ∀ n m : ℕ, n + m = m + n
| n 0 := eq.symm (nat.zero_add n)
| n (m+1) :=
suffices succ (n + m) = succ (m + n), from
eq.symm (succ_add m n) ▸ this,
congr_arg succ (add_comm n m)
protected lemma add_assoc : ∀ n m k : ℕ, (n + m) + k = n + (m + k)
| n m 0 := rfl
| n m (succ k) := by rw [add_succ, add_succ, add_assoc]
protected lemma add_left_comm : ∀ (n m k : ℕ), n + (m + k) = m + (n + k) :=
left_comm nat.add nat.add_comm nat.add_assoc
protected lemma add_left_cancel : ∀ {n m k : ℕ}, n + m = n + k → m = k
| 0 m k := by simp [nat.zero_add] {contextual := tt}
| (succ n) m k := λ h,
have n+m = n+k, by { simp [succ_add] at h, assumption },
add_left_cancel this
protected lemma add_right_cancel {n m k : ℕ} (h : n + m = k + m) : n = k :=
have m + n = m + k, by rwa [nat.add_comm n m, nat.add_comm k m] at h,
nat.add_left_cancel this
lemma succ_ne_zero (n : ℕ) : succ n ≠ 0 :=
assume h, nat.no_confusion h
lemma succ_ne_self : ∀ n : ℕ, succ n ≠ n
| 0 h := absurd h (nat.succ_ne_zero 0)
| (n+1) h := succ_ne_self n (nat.no_confusion h (λ h, h))
protected lemma one_ne_zero : 1 ≠ (0 : ℕ) :=
assume h, nat.no_confusion h
protected lemma zero_ne_one : 0 ≠ (1 : ℕ) :=
assume h, nat.no_confusion h
lemma eq_zero_of_add_eq_zero_right : ∀ {n m : ℕ}, n + m = 0 → n = 0
| 0 m := by simp [nat.zero_add]
| (n+1) m := λ h,
begin
exfalso,
rw [add_one, succ_add] at h,
apply succ_ne_zero _ h
end
lemma eq_zero_of_add_eq_zero_left {n m : ℕ} (h : n + m = 0) : m = 0 :=
@eq_zero_of_add_eq_zero_right m n (nat.add_comm n m ▸ h)
@[simp]
lemma pred_zero : pred 0 = 0 :=
rfl
@[simp]
lemma pred_succ (n : ℕ) : pred (succ n) = n :=
rfl
protected lemma mul_zero (n : ℕ) : n * 0 = 0 :=
rfl
lemma mul_succ (n m : ℕ) : n * succ m = n * m + n :=
rfl
protected theorem zero_mul : ∀ (n : ℕ), 0 * n = 0
| 0 := rfl
| (succ n) := by rw [mul_succ, zero_mul]
private meta def sort_add :=
`[simp [nat.add_assoc, nat.add_comm, nat.add_left_comm]]
lemma succ_mul : ∀ (n m : ℕ), (succ n) * m = (n * m) + m
| n 0 := rfl
| n (succ m) :=
begin
simp [mul_succ, add_succ, succ_mul n m],
sort_add
end
protected lemma right_distrib : ∀ (n m k : ℕ), (n + m) * k = n * k + m * k
| n m 0 := rfl
| n m (succ k) :=
begin simp [mul_succ, right_distrib n m k], sort_add end
protected lemma left_distrib : ∀ (n m k : ℕ), n * (m + k) = n * m + n * k
| 0 m k := by simp [nat.zero_mul]
| (succ n) m k :=
begin simp [succ_mul, left_distrib n m k], sort_add end
protected lemma mul_comm : ∀ (n m : ℕ), n * m = m * n
| n 0 := by rw [nat.zero_mul, nat.mul_zero]
| n (succ m) := by simp [mul_succ, succ_mul, mul_comm n m]
protected lemma mul_assoc : ∀ (n m k : ℕ), (n * m) * k = n * (m * k)
| n m 0 := rfl
| n m (succ k) := by simp [mul_succ, nat.left_distrib, mul_assoc n m k]
protected lemma mul_one : ∀ (n : ℕ), n * 1 = n := nat.zero_add
protected lemma one_mul (n : ℕ) : 1 * n = n :=
by rw [nat.mul_comm, nat.mul_one]
/- properties of inequality -/
protected lemma le_of_eq {n m : ℕ} (p : n = m) : n ≤ m :=
p ▸ less_than_or_equal.refl
lemma le_succ_of_le {n m : ℕ} (h : n ≤ m) : n ≤ succ m :=
nat.le_trans h (le_succ m)
lemma le_of_succ_le {n m : ℕ} (h : succ n ≤ m) : n ≤ m :=
nat.le_trans (le_succ n) h
protected lemma le_of_lt {n m : ℕ} (h : n < m) : n ≤ m :=
le_of_succ_le h
lemma lt.step {n m : ℕ} : n < m → n < succ m := less_than_or_equal.step
lemma eq_zero_or_pos (n : ℕ) : n = 0 ∨ 0 < n :=
by {cases n, exact or.inl rfl, exact or.inr (succ_pos _)}
protected lemma pos_of_ne_zero {n : nat} : n ≠ 0 → 0 < n :=
or.resolve_left (eq_zero_or_pos n)
protected lemma lt_trans {n m k : ℕ} (h₁ : n < m) : m < k → n < k :=
nat.le_trans (less_than_or_equal.step h₁)
protected lemma lt_of_le_of_lt {n m k : ℕ} (h₁ : n ≤ m) : m < k → n < k :=
nat.le_trans (succ_le_succ h₁)
lemma lt.base (n : ℕ) : n < succ n := nat.le_refl (succ n)
lemma lt_succ_self (n : ℕ) : n < succ n := lt.base n
protected lemma le_antisymm {n m : ℕ} (h₁ : n ≤ m) : m ≤ n → n = m :=
less_than_or_equal.cases_on h₁ (λ a, rfl) (λ a b c, absurd (nat.lt_of_le_of_lt b c) (nat.lt_irrefl n))
protected lemma lt_or_ge : ∀ (a b : ℕ), a < b ∨ b ≤ a
| a 0 := or.inr (zero_le a)
| a (b+1) :=
match lt_or_ge a b with
| or.inl h := or.inl (le_succ_of_le h)
| or.inr h :=
match nat.eq_or_lt_of_le h with
| or.inl h1 := or.inl (h1 ▸ lt_succ_self b)
| or.inr h1 := or.inr h1
end
end
protected lemma le_total {m n : ℕ} : m ≤ n ∨ n ≤ m :=
or.imp_left nat.le_of_lt (nat.lt_or_ge m n)
protected lemma lt_of_le_and_ne {m n : ℕ} (h1 : m ≤ n) : m ≠ n → m < n :=
or.resolve_right (or.swap (nat.eq_or_lt_of_le h1))
protected lemma lt_iff_le_not_le {m n : ℕ} : m < n ↔ (m ≤ n ∧ ¬ n ≤ m) :=
⟨λ hmn, ⟨nat.le_of_lt hmn, λ hnm, nat.lt_irrefl _ (nat.lt_of_le_of_lt hnm hmn)⟩,
λ ⟨hmn, hnm⟩, nat.lt_of_le_and_ne hmn (λ heq, hnm (heq ▸ nat.le_refl _))⟩
instance : linear_order ℕ :=
{ le := nat.less_than_or_equal,
le_refl := @nat.le_refl,
le_trans := @nat.le_trans,
le_antisymm := @nat.le_antisymm,
le_total := @nat.le_total,
lt := nat.lt,
lt_iff_le_not_le := @nat.lt_iff_le_not_le,
decidable_lt := nat.decidable_lt,
decidable_le := nat.decidable_le,
decidable_eq := nat.decidable_eq }
lemma eq_zero_of_le_zero {n : nat} (h : n ≤ 0) : n = 0 :=
le_antisymm h (zero_le _)
lemma succ_lt_succ {a b : ℕ} : a < b → succ a < succ b :=
succ_le_succ
lemma lt_of_succ_lt {a b : ℕ} : succ a < b → a < b :=
le_of_succ_le
lemma lt_of_succ_lt_succ {a b : ℕ} : succ a < succ b → a < b :=
le_of_succ_le_succ
lemma pred_lt_pred : ∀ {n m : ℕ}, n ≠ 0 → n < m → pred n < pred m
| 0 _ h₁ h := absurd rfl h₁
| _ 0 h₁ h := absurd h (not_lt_zero _)
| (succ n) (succ m) _ h := lt_of_succ_lt_succ h
lemma lt_of_succ_le {a b : ℕ} (h : succ a ≤ b) : a < b := h
lemma succ_le_of_lt {a b : ℕ} (h : a < b) : succ a ≤ b := h
lemma le_add_right : ∀ (n k : ℕ), n ≤ n + k
| n 0 := nat.le_refl n
| n (k+1) := le_succ_of_le (le_add_right n k)
lemma le_add_left (n m : ℕ): n ≤ m + n :=
nat.add_comm n m ▸ le_add_right n m
lemma le.dest : ∀ {n m : ℕ}, n ≤ m → ∃ k, n + k = m
| n _ less_than_or_equal.refl := ⟨0, rfl⟩
| n _ (less_than_or_equal.step h) :=
match le.dest h with
| ⟨w, hw⟩ := ⟨succ w, hw ▸ add_succ n w⟩
end
lemma le.intro {n m k : ℕ} (h : n + k = m) : n ≤ m :=
h ▸ le_add_right n k
protected lemma add_le_add_left {n m : ℕ} (h : n ≤ m) (k : ℕ) : k + n ≤ k + m :=
match le.dest h with
| ⟨w, hw⟩ := @le.intro _ _ w begin rw [nat.add_assoc, hw] end
end
protected lemma add_le_add_right {n m : ℕ} (h : n ≤ m) (k : ℕ) : n + k ≤ m + k :=
begin rw [nat.add_comm n k, nat.add_comm m k], apply nat.add_le_add_left h end
protected lemma le_of_add_le_add_left {k n m : ℕ} (h : k + n ≤ k + m) : n ≤ m :=
match le.dest h with
| ⟨w, hw⟩ := @le.intro _ _ w
begin
rw [nat.add_assoc] at hw,
apply nat.add_left_cancel hw
end
end
protected lemma le_of_add_le_add_right {k n m : ℕ} : n + k ≤ m + k → n ≤ m :=
begin
rw [nat.add_comm _ k, nat.add_comm _ k],
apply nat.le_of_add_le_add_left
end
protected lemma add_le_add_iff_le_right (k n m : ℕ) : n + k ≤ m + k ↔ n ≤ m :=
⟨ nat.le_of_add_le_add_right , assume h, nat.add_le_add_right h _ ⟩
protected theorem lt_of_add_lt_add_left {k n m : ℕ} (h : k + n < k + m) : n < m :=
let h' := nat.le_of_lt h in
nat.lt_of_le_and_ne
(nat.le_of_add_le_add_left h')
(λ heq, nat.lt_irrefl (k + m) begin rw heq at h, assumption end)
protected lemma lt_of_add_lt_add_right {a b c : ℕ} (h : a + b < c + b) : a < c :=
nat.lt_of_add_lt_add_left $
show b + a < b + c, by rwa [nat.add_comm b a, nat.add_comm b c]
protected lemma add_lt_add_left {n m : ℕ} (h : n < m) (k : ℕ) : k + n < k + m :=
lt_of_succ_le (add_succ k n ▸ nat.add_le_add_left (succ_le_of_lt h) k)
protected lemma add_lt_add_right {n m : ℕ} (h : n < m) (k : ℕ) : n + k < m + k :=
nat.add_comm k m ▸ nat.add_comm k n ▸ nat.add_lt_add_left h k
protected lemma lt_add_of_pos_right {n k : ℕ} (h : 0 < k) : n < n + k :=
nat.add_lt_add_left h n
protected lemma lt_add_of_pos_left {n k : ℕ} (h : 0 < k) : n < k + n :=
by rw nat.add_comm; exact nat.lt_add_of_pos_right h
protected lemma add_lt_add {a b c d : ℕ} (h₁ : a < b) (h₂ : c < d) : a + c < b + d :=
lt_trans (nat.add_lt_add_right h₁ c) (nat.add_lt_add_left h₂ b)
protected lemma add_le_add {a b c d : ℕ} (h₁ : a ≤ b) (h₂ : c ≤ d) : a + c ≤ b + d :=
le_trans (nat.add_le_add_right h₁ c) (nat.add_le_add_left h₂ b)
protected lemma zero_lt_one : 0 < (1:nat) :=
zero_lt_succ 0
lemma mul_le_mul_left {n m : ℕ} (k : ℕ) (h : n ≤ m) : k * n ≤ k * m :=
match le.dest h with
| ⟨l, hl⟩ :=
have k * n + k * l = k * m, by rw [← nat.left_distrib, hl],
le.intro this
end
lemma mul_le_mul_right {n m : ℕ} (k : ℕ) (h : n ≤ m) : n * k ≤ m * k :=
nat.mul_comm k m ▸ nat.mul_comm k n ▸ mul_le_mul_left k h
protected lemma mul_lt_mul_of_pos_left {n m k : ℕ} (h : n < m) (hk : 0 < k) : k * n < k * m :=
nat.lt_of_lt_of_le (nat.lt_add_of_pos_right hk) (mul_succ k n ▸ nat.mul_le_mul_left k (succ_le_of_lt h))
protected lemma mul_lt_mul_of_pos_right {n m k : ℕ} (h : n < m) (hk : 0 < k) : n * k < m * k :=
nat.mul_comm k m ▸ nat.mul_comm k n ▸ nat.mul_lt_mul_of_pos_left h hk
protected lemma le_of_mul_le_mul_left {a b c : ℕ} (h : c * a ≤ c * b) (hc : 0 < c) : a ≤ b :=
not_lt.1
(assume h1 : b < a,
have h2 : c * b < c * a, from nat.mul_lt_mul_of_pos_left h1 hc,
not_le_of_gt h2 h)
lemma le_of_lt_succ {m n : nat} : m < succ n → m ≤ n :=
le_of_succ_le_succ
theorem eq_of_mul_eq_mul_left {m k n : ℕ} (Hn : 0 < n) (H : n * m = n * k) : m = k :=
le_antisymm (nat.le_of_mul_le_mul_left (le_of_eq H) Hn)
(nat.le_of_mul_le_mul_left (le_of_eq H.symm) Hn)
/- sub properties -/
@[simp] protected lemma zero_sub : ∀ a : ℕ, 0 - a = 0
| 0 := rfl
| (a+1) := congr_arg pred (zero_sub a)
lemma sub_lt_succ (a b : ℕ) : a - b < succ a :=
lt_succ_of_le (sub_le a b)
protected theorem sub_le_sub_right {n m : ℕ} (h : n ≤ m) : ∀ k, n - k ≤ m - k
| 0 := h
| (succ z) := pred_le_pred (sub_le_sub_right z)
/- bit0/bit1 properties -/
protected lemma bit1_eq_succ_bit0 (n : ℕ) : bit1 n = succ (bit0 n) :=
rfl
protected lemma bit1_succ_eq (n : ℕ) : bit1 (succ n) = succ (succ (bit1 n)) :=
eq.trans (nat.bit1_eq_succ_bit0 (succ n)) (congr_arg succ (nat.bit0_succ_eq n))
protected lemma bit1_ne_one : ∀ {n : ℕ}, n ≠ 0 → bit1 n ≠ 1
| 0 h h1 := absurd rfl h
| (n+1) h h1 := nat.no_confusion h1 (λ h2, absurd h2 (succ_ne_zero _))
protected lemma bit0_ne_one : ∀ n : ℕ, bit0 n ≠ 1
| 0 h := absurd h (ne.symm nat.one_ne_zero)
| (n+1) h :=
have h1 : succ (succ (n + n)) = 1, from succ_add n n ▸ h,
nat.no_confusion h1
(λ h2, absurd h2 (succ_ne_zero (n + n)))
protected lemma add_self_ne_one : ∀ (n : ℕ), n + n ≠ 1
| 0 h := nat.no_confusion h
| (n+1) h :=
have h1 : succ (succ (n + n)) = 1, from succ_add n n ▸ h,
nat.no_confusion h1 (λ h2, absurd h2 (nat.succ_ne_zero (n + n)))
protected lemma bit1_ne_bit0 : ∀ (n m : ℕ), bit1 n ≠ bit0 m
| 0 m h := absurd h (ne.symm (nat.add_self_ne_one m))
| (n+1) 0 h :=
have h1 : succ (bit0 (succ n)) = 0, from h,
absurd h1 (nat.succ_ne_zero _)
| (n+1) (m+1) h :=
have h1 : succ (succ (bit1 n)) = succ (succ (bit0 m)), from
nat.bit0_succ_eq m ▸ nat.bit1_succ_eq n ▸ h,
have h2 : bit1 n = bit0 m, from
nat.no_confusion h1 (λ h2', nat.no_confusion h2' (λ h2'', h2'')),
absurd h2 (bit1_ne_bit0 n m)
protected lemma bit0_ne_bit1 : ∀ (n m : ℕ), bit0 n ≠ bit1 m :=
λ n m : nat, ne.symm (nat.bit1_ne_bit0 m n)
protected lemma bit0_inj : ∀ {n m : ℕ}, bit0 n = bit0 m → n = m
| 0 0 h := rfl
| 0 (m+1) h := by contradiction
| (n+1) 0 h := by contradiction
| (n+1) (m+1) h :=
have succ (succ (n + n)) = succ (succ (m + m)),
by { unfold bit0 at h, simp [add_one, add_succ, succ_add] at h,
have aux : n + n = m + m := h, rw aux },
have n + n = m + m, by iterate { injection this with this },
have n = m, from bit0_inj this,
by rw this
protected lemma bit1_inj : ∀ {n m : ℕ}, bit1 n = bit1 m → n = m :=
λ n m h,
have succ (bit0 n) = succ (bit0 m), begin simp [nat.bit1_eq_succ_bit0] at h, rw h end,
have bit0 n = bit0 m, by injection this,
nat.bit0_inj this
protected lemma bit0_ne {n m : ℕ} : n ≠ m → bit0 n ≠ bit0 m :=
λ h₁ h₂, absurd (nat.bit0_inj h₂) h₁
protected lemma bit1_ne {n m : ℕ} : n ≠ m → bit1 n ≠ bit1 m :=
λ h₁ h₂, absurd (nat.bit1_inj h₂) h₁
protected lemma zero_ne_bit0 {n : ℕ} : n ≠ 0 → 0 ≠ bit0 n :=
λ h, ne.symm (nat.bit0_ne_zero h)
protected lemma zero_ne_bit1 (n : ℕ) : 0 ≠ bit1 n :=
ne.symm (nat.bit1_ne_zero n)
protected lemma one_ne_bit0 (n : ℕ) : 1 ≠ bit0 n :=
ne.symm (nat.bit0_ne_one n)
protected lemma one_ne_bit1 {n : ℕ} : n ≠ 0 → 1 ≠ bit1 n :=
λ h, ne.symm (nat.bit1_ne_one h)
protected lemma one_lt_bit1 : ∀ {n : nat}, n ≠ 0 → 1 < bit1 n
| 0 h := by contradiction
| (succ n) h :=
begin
rw nat.bit1_succ_eq,
apply succ_lt_succ,
apply zero_lt_succ
end
protected lemma one_lt_bit0 : ∀ {n : nat}, n ≠ 0 → 1 < bit0 n
| 0 h := by contradiction
| (succ n) h :=
begin
rw nat.bit0_succ_eq,
apply succ_lt_succ,
apply zero_lt_succ
end
protected lemma bit0_lt {n m : nat} (h : n < m) : bit0 n < bit0 m :=
nat.add_lt_add h h
protected lemma bit1_lt {n m : nat} (h : n < m) : bit1 n < bit1 m :=
succ_lt_succ (nat.add_lt_add h h)
protected lemma bit0_lt_bit1 {n m : nat} (h : n ≤ m) : bit0 n < bit1 m :=
lt_succ_of_le (nat.add_le_add h h)
protected lemma bit1_lt_bit0 : ∀ {n m : nat}, n < m → bit1 n < bit0 m
| n 0 h := absurd h (not_lt_zero _)
| n (succ m) h :=
have n ≤ m, from le_of_lt_succ h,
have succ (n + n) ≤ succ (m + m), from succ_le_succ (nat.add_le_add this this),
have succ (n + n) ≤ succ m + m, {rw succ_add, assumption},
show succ (n + n) < succ (succ m + m), from lt_succ_of_le this
protected lemma one_le_bit1 (n : ℕ) : 1 ≤ bit1 n :=
show 1 ≤ succ (bit0 n), from
succ_le_succ (zero_le (bit0 n))
protected lemma one_le_bit0 : ∀ (n : ℕ), n ≠ 0 → 1 ≤ bit0 n
| 0 h := absurd rfl h
| (n+1) h :=
suffices 1 ≤ succ (succ (bit0 n)), from
eq.symm (nat.bit0_succ_eq n) ▸ this,
succ_le_succ (zero_le (succ (bit0 n)))
/- subtraction -/
@[simp]
protected theorem sub_zero (n : ℕ) : n - 0 = n :=
rfl
theorem sub_succ (n m : ℕ) : n - succ m = pred (n - m) :=
rfl
theorem succ_sub_succ (n m : ℕ) : succ n - succ m = n - m :=
succ_sub_succ_eq_sub n m
protected theorem sub_self : ∀ (n : ℕ), n - n = 0
| 0 := by rw nat.sub_zero
| (succ n) := by rw [succ_sub_succ, sub_self n]
/- TODO(Leo): remove the following ematch annotations as soon as we have
arithmetic theory in the smt_stactic -/
@[ematch_lhs]
protected theorem add_sub_add_right : ∀ (n k m : ℕ), (n + k) - (m + k) = n - m
| n 0 m := by rw [nat.add_zero, nat.add_zero]
| n (succ k) m := by rw [add_succ, add_succ, succ_sub_succ, add_sub_add_right n k m]
@[ematch_lhs]
protected theorem add_sub_add_left (k n m : ℕ) : (k + n) - (k + m) = n - m :=
by rw [nat.add_comm k n, nat.add_comm k m, nat.add_sub_add_right]
@[ematch_lhs]
protected theorem add_sub_cancel (n m : ℕ) : n + m - m = n :=
suffices n + m - (0 + m) = n, from
by rwa [nat.zero_add] at this,
by rw [nat.add_sub_add_right, nat.sub_zero]
@[ematch_lhs]
protected theorem add_sub_cancel_left (n m : ℕ) : n + m - n = m :=
show n + m - (n + 0) = m, from
by rw [nat.add_sub_add_left, nat.sub_zero]
protected theorem sub_sub : ∀ (n m k : ℕ), n - m - k = n - (m + k)
| n m 0 := by rw [nat.add_zero, nat.sub_zero]
| n m (succ k) := by rw [add_succ, nat.sub_succ, nat.sub_succ, sub_sub n m k]
theorem le_of_le_of_sub_le_sub_right {n m k : ℕ}
(h₀ : k ≤ m)
(h₁ : n - k ≤ m - k)
: n ≤ m :=
begin
revert k m,
induction n with n ; intros k m h₀ h₁,
{ apply zero_le },
{ cases k with k,
{ apply h₁ },
cases m with m,
{ cases not_succ_le_zero _ h₀ },
{ simp [succ_sub_succ] at h₁,
apply succ_le_succ,
apply n_ih _ h₁,
apply le_of_succ_le_succ h₀ }, }
end
protected theorem sub_le_sub_right_iff (n m k : ℕ)
(h : k ≤ m)
: n - k ≤ m - k ↔ n ≤ m :=
⟨ le_of_le_of_sub_le_sub_right h , assume h, nat.sub_le_sub_right h k ⟩
theorem sub_self_add (n m : ℕ) : n - (n + m) = 0 :=
show (n + 0) - (n + m) = 0, from
by rw [nat.add_sub_add_left, nat.zero_sub]
theorem add_le_to_le_sub (x : ℕ) {y k : ℕ}
(h : k ≤ y)
: x + k ≤ y ↔ x ≤ y - k :=
by rw [← nat.add_sub_cancel x k, nat.sub_le_sub_right_iff _ _ _ h, nat.add_sub_cancel]
lemma sub_lt_of_pos_le (a b : ℕ) (h₀ : 0 < a) (h₁ : a ≤ b)
: b - a < b :=
begin
apply sub_lt _ h₀,
apply lt_of_lt_of_le h₀ h₁
end
theorem sub_one (n : ℕ) : n - 1 = pred n :=
rfl
theorem succ_sub_one (n : ℕ) : succ n - 1 = n :=
rfl
theorem succ_pred_eq_of_pos : ∀ {n : ℕ}, 0 < n → succ (pred n) = n
| 0 h := absurd h (lt_irrefl 0)
| (succ k) h := rfl
theorem sub_eq_zero_of_le {n m : ℕ} (h : n ≤ m) : n - m = 0 :=
exists.elim (nat.le.dest h)
(assume k, assume hk : n + k = m, by rw [← hk, sub_self_add])
protected theorem le_of_sub_eq_zero : ∀{n m : ℕ}, n - m = 0 → n ≤ m
| n 0 H := begin rw [nat.sub_zero] at H, simp [H] end
| 0 (m+1) H := zero_le _
| (n+1) (m+1) H := nat.add_le_add_right
(le_of_sub_eq_zero begin simp [nat.add_sub_add_right] at H, exact H end) _
protected theorem sub_eq_zero_iff_le {n m : ℕ} : n - m = 0 ↔ n ≤ m :=
⟨nat.le_of_sub_eq_zero, nat.sub_eq_zero_of_le⟩
theorem add_sub_of_le {n m : ℕ} (h : n ≤ m) : n + (m - n) = m :=
exists.elim (nat.le.dest h)
(assume k, assume hk : n + k = m,
by rw [← hk, nat.add_sub_cancel_left])
protected theorem sub_add_cancel {n m : ℕ} (h : m ≤ n) : n - m + m = n :=
by rw [nat.add_comm, add_sub_of_le h]
protected theorem add_sub_assoc {m k : ℕ} (h : k ≤ m) (n : ℕ) : n + m - k = n + (m - k) :=
exists.elim (nat.le.dest h)
(assume l, assume hl : k + l = m,
by rw [← hl, nat.add_sub_cancel_left, nat.add_comm k, ← nat.add_assoc, nat.add_sub_cancel])
protected lemma sub_eq_iff_eq_add {a b c : ℕ} (ab : b ≤ a) : a - b = c ↔ a = c + b :=
⟨assume c_eq, begin rw [c_eq.symm, nat.sub_add_cancel ab] end,
assume a_eq, begin rw [a_eq, nat.add_sub_cancel] end⟩
protected lemma lt_of_sub_eq_succ {m n l : ℕ} (H : m - n = nat.succ l) : n < m :=
not_le.1
(assume (H' : n ≥ m), begin simp [nat.sub_eq_zero_of_le H'] at H, contradiction end)
lemma zero_min (a : ℕ) : min 0 a = 0 :=
min_eq_left (zero_le a)
lemma min_zero (a : ℕ) : min a 0 = 0 :=
min_eq_right (zero_le a)
-- Distribute succ over min
theorem min_succ_succ (x y : ℕ) : min (succ x) (succ y) = succ (min x y) :=
have f : x ≤ y → min (succ x) (succ y) = succ (min x y), from λp,
calc min (succ x) (succ y)
= succ x : if_pos (succ_le_succ p)
... = succ (min x y) : congr_arg succ (eq.symm (if_pos p)),
have g : ¬ (x ≤ y) → min (succ x) (succ y) = succ (min x y), from λp,
calc min (succ x) (succ y)
= succ y : if_neg (λeq, p (pred_le_pred eq))
... = succ (min x y) : congr_arg succ (eq.symm (if_neg p)),
decidable.by_cases f g
theorem sub_eq_sub_min (n m : ℕ) : n - m = n - min n m :=
if h : n ≥ m then by rewrite [min_eq_right h]
else by rewrite [sub_eq_zero_of_le (le_of_not_ge h), min_eq_left (le_of_not_ge h), nat.sub_self]
@[simp] theorem sub_add_min_cancel (n m : ℕ) : n - m + min n m = n :=
by rw [sub_eq_sub_min, nat.sub_add_cancel (min_le_left n m)]
/- TODO(Leo): sub + inequalities -/
protected def strong_rec_on {p : nat → Sort u} (n : nat) (h : ∀ n, (∀ m, m < n → p m) → p n) : p n :=
suffices ∀ n m, m < n → p m, from this (succ n) n (lt_succ_self _),
begin
intros n, induction n with n ih,
{intros m h₁, exact absurd h₁ (not_lt_zero _)},
{intros m h₁,
apply or.by_cases (decidable.lt_or_eq_of_le (le_of_lt_succ h₁)),
{intros, apply ih, assumption},
{intros, subst m, apply h _ ih}}
end
protected lemma strong_induction_on {p : nat → Prop} (n : nat) (h : ∀ n, (∀ m, m < n → p m) → p n) : p n :=
nat.strong_rec_on n h
protected lemma case_strong_induction_on {p : nat → Prop} (a : nat)
(hz : p 0)
(hi : ∀ n, (∀ m, m ≤ n → p m) → p (succ n)) : p a :=
nat.strong_induction_on a $ λ n,
match n with
| 0 := λ _, hz
| (n+1) := λ h₁, hi n (λ m h₂, h₁ _ (lt_succ_of_le h₂))
end
/- mod -/
private lemma mod_core_congr {x y f1 f2} (h1 : x ≤ f1) (h2 : x ≤ f2) :
nat.mod_core y f1 x = nat.mod_core y f2 x :=
begin
cases y, { cases f1; cases f2; refl },
induction f1 with f1 ih generalizing x f2, { cases h1, cases f2; refl },
cases x, { cases f1; cases f2; refl },
cases f2, { cases h2 },
refine if_congr iff.rfl _ rfl,
simp only [succ_sub_succ],
exact ih
(le_trans (sub_le _ _) (le_of_succ_le_succ h1))
(le_trans (sub_le _ _) (le_of_succ_le_succ h2))
end
lemma mod_def (x y : nat) : x % y = if 0 < y ∧ y ≤ x then (x - y) % y else x :=
begin
cases x, { cases y; refl },
cases y, { refl },
refine if_congr iff.rfl (mod_core_congr _ _) rfl; simp [sub_le]
end
@[simp] lemma mod_zero (a : nat) : a % 0 = a :=
begin
rw mod_def,
have h : ¬ (0 < 0 ∧ 0 ≤ a),
simp [lt_irrefl],
simp [if_neg, h]
end
lemma mod_eq_of_lt {a b : nat} (h : a < b) : a % b = a :=
begin
rw mod_def,
have h' : ¬(0 < b ∧ b ≤ a),
simp [not_le_of_gt h],
simp [if_neg, h']
end
@[simp] lemma zero_mod (b : nat) : 0 % b = 0 :=
begin
rw mod_def,
have h : ¬(0 < b ∧ b ≤ 0),
{intro hn, cases hn with l r, exact absurd (lt_of_lt_of_le l r) (lt_irrefl 0)},
simp [if_neg, h]
end
lemma mod_eq_sub_mod {a b : nat} (h : b ≤ a) : a % b = (a - b) % b :=
or.elim (eq_zero_or_pos b)
(λb0, by rw [b0, nat.sub_zero])
(λh₂, by rw [mod_def, if_pos (and.intro h₂ h)])
lemma mod_lt (x : nat) {y : nat} (h : 0 < y) : x % y < y :=
begin
induction x using nat.case_strong_induction_on with x ih,
{ rw zero_mod, assumption },
{ by_cases h₁ : succ x < y,
{ rwa [mod_eq_of_lt h₁] },
{ have h₁ : succ x % y = (succ x - y) % y := mod_eq_sub_mod (not_lt.1 h₁),
have : succ x - y ≤ x := le_of_lt_succ (sub_lt (succ_pos x) h),
have h₂ : (succ x - y) % y < y := ih _ this,
rwa [← h₁] at h₂ } }
end
@[simp] theorem mod_self (n : nat) : n % n = 0 :=
by rw [mod_eq_sub_mod (le_refl _), nat.sub_self, zero_mod]
@[simp] lemma mod_one (n : ℕ) : n % 1 = 0 :=
have n % 1 < 1, from (mod_lt n) (succ_pos 0),
eq_zero_of_le_zero (le_of_lt_succ this)
lemma mod_two_eq_zero_or_one (n : ℕ) : n % 2 = 0 ∨ n % 2 = 1 :=
match n % 2, @nat.mod_lt n 2 dec_trivial with
| 0, _ := or.inl rfl
| 1, _ := or.inr rfl
| k+2, h := absurd h dec_trivial
end
/- div & mod -/
private lemma div_core_congr {x y f1 f2} (h1 : x ≤ f1) (h2 : x ≤ f2) :
nat.div_core y f1 x = nat.div_core y f2 x :=
begin
cases y, { cases f1; cases f2; refl },
induction f1 with f1 ih generalizing x f2, { cases h1, cases f2; refl },
cases x, { cases f1; cases f2; refl },
cases f2, { cases h2 },
refine if_congr iff.rfl _ rfl,
simp only [succ_sub_succ],
refine congr_arg (+1) _,
exact ih
(le_trans (sub_le _ _) (le_of_succ_le_succ h1))
(le_trans (sub_le _ _) (le_of_succ_le_succ h2))
end
lemma div_def (x y : nat) : x / y = if 0 < y ∧ y ≤ x then (x - y) / y + 1 else 0 :=
begin
cases x, { cases y; refl },
cases y, { refl },
refine if_congr iff.rfl (congr_arg (+1) _) rfl,
refine div_core_congr _ _; simp [sub_le]
end
lemma mod_add_div (m k : ℕ)
: m % k + k * (m / k) = m :=
begin
apply nat.strong_induction_on m,
clear m,
intros m IH,
cases decidable.em (0 < k ∧ k ≤ m) with h h',
-- 0 < k ∧ k ≤ m
{ have h' : m - k < m,
{ apply nat.sub_lt _ h.left,
apply lt_of_lt_of_le h.left h.right },
rw [div_def, mod_def, if_pos h, if_pos h],
simp [nat.left_distrib, IH _ h', nat.add_comm, nat.add_left_comm],
rw [nat.add_comm, ← nat.add_sub_assoc h.right, nat.mul_one, nat.add_sub_cancel_left] },
-- ¬ (0 < k ∧ k ≤ m)
{ rw [div_def, mod_def, if_neg h', if_neg h', nat.mul_zero, nat.add_zero] },
end
/- div -/
@[simp] protected lemma div_one (n : ℕ) : n / 1 = n :=
have n % 1 + 1 * (n / 1) = n, from mod_add_div _ _,
by { rwa [mod_one, nat.zero_add, nat.one_mul] at this }
@[simp] protected lemma div_zero (n : ℕ) : n / 0 = 0 :=
begin rw [div_def], simp [lt_irrefl] end
@[simp] protected lemma zero_div (b : ℕ) : 0 / b = 0 :=
eq.trans (div_def 0 b) $ if_neg (and.rec not_le_of_gt)
protected lemma div_le_of_le_mul {m n : ℕ} : ∀ {k}, m ≤ k * n → m / k ≤ n
| 0 h := by simp [nat.div_zero]; apply zero_le
| (succ k) h :=
suffices succ k * (m / succ k) ≤ succ k * n, from nat.le_of_mul_le_mul_left this (zero_lt_succ _),
calc
succ k * (m / succ k) ≤ m % succ k + succ k * (m / succ k) : le_add_left _ _
... = m : by rw mod_add_div
... ≤ succ k * n : h
protected lemma div_le_self : ∀ (m n : ℕ), m / n ≤ m
| m 0 := by simp [nat.div_zero]; apply zero_le
| m (succ n) :=
have m ≤ succ n * m, from calc
m = 1 * m : by rw nat.one_mul
... ≤ succ n * m : mul_le_mul_right _ (succ_le_succ (zero_le _)),
nat.div_le_of_le_mul this
lemma div_eq_sub_div {a b : nat} (h₁ : 0 < b) (h₂ : b ≤ a) : a / b = (a - b) / b + 1 :=
begin
rw [div_def a, if_pos],
split ; assumption
end
lemma div_eq_of_lt {a b : ℕ} (h₀ : a < b) : a / b = 0 :=
begin
rw [div_def a, if_neg],
intro h₁,
apply not_le_of_gt h₀ h₁.right
end
-- this is a Galois connection
-- f x ≤ y ↔ x ≤ g y
-- with
-- f x = x * k
-- g y = y / k
theorem le_div_iff_mul_le (x y : ℕ) {k : ℕ} (Hk : 0 < k) : x ≤ y / k ↔ x * k ≤ y :=
begin
-- Hk is needed because, despite div being made total, y / 0 := 0
-- x * 0 ≤ y ↔ x ≤ y / 0
-- ↔ 0 ≤ y ↔ x ≤ 0
-- ↔ true ↔ x = 0
-- ↔ x = 0
revert x,
apply nat.strong_induction_on y _,
clear y,
intros y IH x,
cases lt_or_le y k with h h,
-- base case: y < k
{ rw [div_eq_of_lt h],
cases x with x,
{ simp [nat.zero_mul, zero_le] },
{ simp [succ_mul, not_succ_le_zero, nat.add_comm],
apply lt_of_lt_of_le h,
apply le_add_right } },
-- step: k ≤ y
{ rw [div_eq_sub_div Hk h],
cases x with x,
{ simp [nat.zero_mul, zero_le] },
{ have Hlt : y - k < y,
{ apply sub_lt_of_pos_le ; assumption },
rw [ ← add_one
, nat.add_le_add_iff_le_right
, IH (y - k) Hlt x
, add_one
, succ_mul, add_le_to_le_sub _ h ]
} }
end
theorem div_lt_iff_lt_mul (x y : ℕ) {k : ℕ} (Hk : 0 < k) : x / k < y ↔ x < y * k :=
begin
simp [← not_le],
apply not_iff_not_of_iff,
apply le_div_iff_mul_le _ _ Hk
end
def iterate {α : Sort u} (op : α → α) : ℕ → α → α
| 0 a := a
| (succ k) a := iterate k (op a)
notation f`^[`n`]` := iterate f n
/- successor and predecessor -/
theorem add_one_ne_zero (n : ℕ) : n + 1 ≠ 0 := succ_ne_zero _
theorem eq_zero_or_eq_succ_pred (n : ℕ) : n = 0 ∨ n = succ (pred n) :=
by cases n; simp
theorem exists_eq_succ_of_ne_zero {n : ℕ} (H : n ≠ 0) : ∃k : ℕ, n = succ k :=
⟨_, (eq_zero_or_eq_succ_pred _).resolve_left H⟩
def discriminate {B : Sort u} {n : ℕ} (H1: n = 0 → B) (H2 : ∀m, n = succ m → B) : B :=
by induction h : n; [exact H1 h, exact H2 _ h]
theorem one_succ_zero : 1 = succ 0 := rfl
def two_step_induction {P : ℕ → Sort u} (H1 : P 0) (H2 : P 1)
(H3 : ∀ (n : ℕ) (IH1 : P n) (IH2 : P (succ n)), P (succ (succ n))) : Π (a : ℕ), P a
| 0 := H1
| 1 := H2
| (succ (succ n)) := H3 _ (two_step_induction _) (two_step_induction _)
def sub_induction {P : ℕ → ℕ → Sort u} (H1 : ∀m, P 0 m)
(H2 : ∀n, P (succ n) 0) (H3 : ∀n m, P n m → P (succ n) (succ m)) : Π (n m : ℕ), P n m
| 0 m := H1 _
| (succ n) 0 := H2 _
| (succ n) (succ m) := H3 _ _ (sub_induction n m)
/- addition -/
theorem succ_add_eq_succ_add (n m : ℕ) : succ n + m = n + succ m :=
by simp [succ_add, add_succ]
-- theorem one_add (n : ℕ) : 1 + n = succ n := by simp [add_comm]
protected theorem add_right_comm : ∀ (n m k : ℕ), n + m + k = n + k + m :=
right_comm nat.add nat.add_comm nat.add_assoc
theorem eq_zero_of_add_eq_zero {n m : ℕ} (H : n + m = 0) : n = 0 ∧ m = 0 :=
⟨nat.eq_zero_of_add_eq_zero_right H, nat.eq_zero_of_add_eq_zero_left H⟩
theorem eq_zero_of_mul_eq_zero : ∀ {n m : ℕ}, n * m = 0 → n = 0 ∨ m = 0
| 0 m := λ h, or.inl rfl
| (succ n) m :=
begin
rw succ_mul, intro h,
exact or.inr (eq_zero_of_add_eq_zero_left h)
end
/- properties of inequality -/
theorem le_succ_of_pred_le {n m : ℕ} : pred n ≤ m → n ≤ succ m :=
nat.cases_on n less_than_or_equal.step (λ a, succ_le_succ)
theorem le_lt_antisymm {n m : ℕ} (h₁ : n ≤ m) (h₂ : m < n) : false :=
nat.lt_irrefl n (nat.lt_of_le_of_lt h₁ h₂)
theorem lt_le_antisymm {n m : ℕ} (h₁ : n < m) (h₂ : m ≤ n) : false :=
le_lt_antisymm h₂ h₁
protected theorem lt_asymm {n m : ℕ} (h₁ : n < m) : ¬ m < n :=
le_lt_antisymm (nat.le_of_lt h₁)
protected def lt_ge_by_cases {a b : ℕ} {C : Sort u} (h₁ : a < b → C) (h₂ : b ≤ a → C) : C :=
decidable.by_cases h₁ (λ h, h₂ (or.elim (nat.lt_or_ge a b) (λ a, absurd a h) (λ a, a)))
protected def lt_by_cases {a b : ℕ} {C : Sort u} (h₁ : a < b → C) (h₂ : a = b → C)
(h₃ : b < a → C) : C :=
nat.lt_ge_by_cases h₁ (λ h₁,
nat.lt_ge_by_cases h₃ (λ h, h₂ (nat.le_antisymm h h₁)))
protected theorem lt_trichotomy (a b : ℕ) : a < b ∨ a = b ∨ b < a :=
nat.lt_by_cases (λ h, or.inl h) (λ h, or.inr (or.inl h)) (λ h, or.inr (or.inr h))
protected theorem eq_or_lt_of_not_lt {a b : ℕ} (hnlt : ¬ a < b) : a = b ∨ b < a :=
(nat.lt_trichotomy a b).resolve_left hnlt
theorem lt_succ_of_lt {a b : nat} (h : a < b) : a < succ b := le_succ_of_le h
lemma one_pos : 0 < 1 := nat.zero_lt_one
/- subtraction -/
protected theorem sub_le_sub_left {n m : ℕ} (k) (h : n ≤ m) : k - m ≤ k - n :=
by induction h; [refl, exact le_trans (pred_le _) h_ih]
theorem succ_sub_sub_succ (n m k : ℕ) : succ n - m - succ k = n - m - k :=
by rw [nat.sub_sub, nat.sub_sub, add_succ, succ_sub_succ]
protected theorem sub.right_comm (m n k : ℕ) : m - n - k = m - k - n :=
by rw [nat.sub_sub, nat.sub_sub, nat.add_comm]
theorem mul_pred_left : ∀ (n m : ℕ), pred n * m = n * m - m
| 0 m := by simp [nat.zero_sub, pred_zero, nat.zero_mul]
| (succ n) m := by rw [pred_succ, succ_mul, nat.add_sub_cancel]
theorem mul_pred_right (n m : ℕ) : n * pred m = n * m - n :=
by rw [nat.mul_comm, mul_pred_left, nat.mul_comm]
protected theorem mul_sub_right_distrib : ∀ (n m k : ℕ), (n - m) * k = n * k - m * k
| n 0 k := by simp [nat.sub_zero, nat.zero_mul]
| n (succ m) k := by rw [nat.sub_succ, mul_pred_left, mul_sub_right_distrib, succ_mul, nat.sub_sub]
protected theorem mul_sub_left_distrib (n m k : ℕ) : n * (m - k) = n * m - n * k :=
by rw [nat.mul_comm, nat.mul_sub_right_distrib, nat.mul_comm m n, nat.mul_comm n k]
protected theorem mul_self_sub_mul_self_eq (a b : nat) : a * a - b * b = (a + b) * (a - b) :=
by rw [nat.mul_sub_left_distrib, nat.right_distrib, nat.right_distrib, nat.mul_comm b a, nat.add_comm (a*a) (a*b),
nat.add_sub_add_left]
theorem succ_mul_succ_eq (a b : nat) : succ a * succ b = a*b + a + b + 1 :=
begin
rw [← add_one, ← add_one],
simp [nat.right_distrib, nat.left_distrib, nat.add_left_comm, nat.mul_one, nat.one_mul, nat.add_assoc],
end
theorem succ_sub {m n : ℕ} (h : n ≤ m) : succ m - n = succ (m - n) :=
exists.elim (nat.le.dest h)
(assume k, assume hk : n + k = m,
by rw [← hk, nat.add_sub_cancel_left, ← add_succ, nat.add_sub_cancel_left])
protected theorem sub_pos_of_lt {m n : ℕ} (h : m < n) : 0 < n - m :=
have 0 + m < n - m + m, begin rw [nat.zero_add, nat.sub_add_cancel (le_of_lt h)], exact h end,
nat.lt_of_add_lt_add_right this
protected theorem sub_sub_self {n m : ℕ} (h : m ≤ n) : n - (n - m) = m :=
(nat.sub_eq_iff_eq_add (nat.sub_le _ _)).2 (eq.symm (add_sub_of_le h))
protected theorem sub_add_comm {n m k : ℕ} (h : k ≤ n) : n + m - k = n - k + m :=
(nat.sub_eq_iff_eq_add (nat.le_trans h (nat.le_add_right _ _))).2
(by rwa [nat.add_right_comm, nat.sub_add_cancel])
theorem sub_one_sub_lt {n i} (h : i < n) : n - 1 - i < n := begin
rw nat.sub_sub,
apply nat.sub_lt,
apply lt_of_lt_of_le (nat.zero_lt_succ _) h,
rw nat.add_comm,
apply nat.zero_lt_succ
end
theorem pred_inj : ∀ {a b : nat}, 0 < a → 0 < b → nat.pred a = nat.pred b → a = b
| (succ a) (succ b) ha hb h := have a = b, from h, by rw this
| (succ a) 0 ha hb h := absurd hb (lt_irrefl _)
| 0 (succ b) ha hb h := absurd ha (lt_irrefl _)
| 0 0 ha hb h := rfl
/- find -/
section find
parameter {p : ℕ → Prop}
private def lbp (m n : ℕ) : Prop := m = n + 1 ∧ ∀ k ≤ n, ¬p k
parameters [decidable_pred p] (H : ∃n, p n)
private def wf_lbp : well_founded lbp :=
⟨let ⟨n, pn⟩ := H in
suffices ∀m k, n ≤ k + m → acc lbp k, from λa, this _ _ (nat.le_add_left _ _),
λm, nat.rec_on m
(λk kn, ⟨_, λy r, match y, r with ._, ⟨rfl, a⟩ := absurd pn (a _ kn) end⟩)
(λm IH k kn, ⟨_, λy r, match y, r with ._, ⟨rfl, a⟩ := IH _ (by rw nat.add_right_comm; exact kn) end⟩)⟩
protected def find_x : {n // p n ∧ ∀m < n, ¬p m} :=
@well_founded.fix _ (λk, (∀n < k, ¬p n) → {n // p n ∧ ∀m < n, ¬p m}) lbp wf_lbp
(λm IH al, if pm : p m then ⟨m, pm, al⟩ else
have ∀ n ≤ m, ¬p n, from λn h, or.elim (decidable.lt_or_eq_of_le h) (al n) (λe, by rw e; exact pm),
IH _ ⟨rfl, this⟩ (λn h, this n $ nat.le_of_succ_le_succ h))
0 (λn h, absurd h (nat.not_lt_zero _))
/--
If `p` is a (decidable) predicate on `ℕ` and `hp : ∃ (n : ℕ), p n` is a proof that
there exists some natural number satisfying `p`, then `nat.find hp` is the
smallest natural number satisfying `p`. Note that `nat.find` is protected,
meaning that you can't just write `find`, even if the `nat` namespace is open.
The API for `nat.find` is:
* `nat.find_spec` is the proof that `nat.find hp` satisfies `p`.
* `nat.find_min` is the proof that if `m < nat.find hp` then `m` does not satisfy `p`.
* `nat.find_min'` is the proof that if `m` does satisfy `p` then `nat.find hp ≤ m`.
-/
protected def find : ℕ := nat.find_x.1
protected theorem find_spec : p nat.find := nat.find_x.2.left
protected theorem find_min : ∀ {m : ℕ}, m < nat.find → ¬p m := nat.find_x.2.right
protected theorem find_min' {m : ℕ} (h : p m) : nat.find ≤ m :=
le_of_not_lt (λ l, find_min l h)
end find
/- mod -/
theorem mod_le (x y : ℕ) : x % y ≤ x :=
or.elim (lt_or_le x y)
(λxlty, by rw mod_eq_of_lt xlty; refl)
(λylex, or.elim (eq_zero_or_pos y)
(λy0, by rw [y0, mod_zero]; refl)
(λypos, le_trans (le_of_lt (mod_lt _ ypos)) ylex))
@[simp] theorem add_mod_right (x z : ℕ) : (x + z) % z = x % z :=
by rw [mod_eq_sub_mod (nat.le_add_left _ _), nat.add_sub_cancel]
@[simp] theorem add_mod_left (x z : ℕ) : (x + z) % x = z % x :=
by rw [nat.add_comm, add_mod_right]
@[simp] theorem add_mul_mod_self_left (x y z : ℕ) : (x + y * z) % y = x % y :=
by {induction z with z ih, rw [nat.mul_zero, nat.add_zero], rw [mul_succ, ← nat.add_assoc, add_mod_right, ih]}
@[simp] theorem add_mul_mod_self_right (x y z : ℕ) : (x + y * z) % z = x % z :=
by rw [nat.mul_comm, add_mul_mod_self_left]
@[simp] theorem mul_mod_right (m n : ℕ) : (m * n) % m = 0 :=
by rw [← nat.zero_add (m*n), add_mul_mod_self_left, zero_mod]
@[simp] theorem mul_mod_left (m n : ℕ) : (m * n) % n = 0 :=
by rw [nat.mul_comm, mul_mod_right]
theorem mul_mod_mul_left (z x y : ℕ) : (z * x) % (z * y) = z * (x % y) :=
if y0 : y = 0 then
by rw [y0, nat.mul_zero, mod_zero, mod_zero]
else if z0 : z = 0 then
by rw [z0, nat.zero_mul, nat.zero_mul, nat.zero_mul, mod_zero]
else x.strong_induction_on $ λn IH,
have y0 : y > 0, from nat.pos_of_ne_zero y0,
have z0 : z > 0, from nat.pos_of_ne_zero z0,
or.elim (le_or_lt y n)
(λyn, by rw [
mod_eq_sub_mod yn,
mod_eq_sub_mod (mul_le_mul_left z yn),
← nat.mul_sub_left_distrib];
exact IH _ (sub_lt (lt_of_lt_of_le y0 yn) y0))
(λyn, by rw [mod_eq_of_lt yn, mod_eq_of_lt (nat.mul_lt_mul_of_pos_left yn z0)])
theorem mul_mod_mul_right (z x y : ℕ) : (x * z) % (y * z) = (x % y) * z :=
by rw [nat.mul_comm x z, nat.mul_comm y z, nat.mul_comm (x % y) z]; apply mul_mod_mul_left
theorem cond_to_bool_mod_two (x : ℕ) [d : decidable (x % 2 = 1)]
: cond (@to_bool (x % 2 = 1) d) 1 0 = x % 2 :=
begin
by_cases h : x % 2 = 1,
{ simp! [*] },
{ cases mod_two_eq_zero_or_one x; simp! [*, nat.zero_ne_one] }
end
theorem sub_mul_mod (x k n : ℕ) (h₁ : n*k ≤ x) : (x - n*k) % n = x % n :=
begin
induction k with k,
{ rw [nat.mul_zero, nat.sub_zero] },
{ have h₂ : n * k ≤ x,
{ rw [mul_succ] at h₁,
apply nat.le_trans _ h₁,
apply le_add_right _ n },
have h₄ : x - n * k ≥ n,
{ apply @nat.le_of_add_le_add_right (n*k),
rw [nat.sub_add_cancel h₂],
simp [mul_succ, nat.add_comm] at h₁, simp [h₁] },
rw [mul_succ, ← nat.sub_sub, ← mod_eq_sub_mod h₄, k_ih h₂] }
end
/- div -/
theorem sub_mul_div (x n p : ℕ) (h₁ : n*p ≤ x) : (x - n*p) / n = x / n - p :=
begin
cases eq_zero_or_pos n with h₀ h₀,
{ rw [h₀, nat.div_zero, nat.div_zero, nat.zero_sub] },
{ induction p with p,
{ rw [nat.mul_zero, nat.sub_zero, nat.sub_zero] },
{ have h₂ : n*p ≤ x,
{ transitivity,
{ apply nat.mul_le_mul_left, apply le_succ },
{ apply h₁ } },
have h₃ : x - n * p ≥ n,
{ apply nat.le_of_add_le_add_right,
rw [nat.sub_add_cancel h₂, nat.add_comm],
rw [mul_succ] at h₁,
apply h₁ },
rw [sub_succ, ← p_ih h₂],
rw [@div_eq_sub_div (x - n*p) _ h₀ h₃],
simp [add_one, pred_succ, mul_succ, nat.sub_sub] } }
end
theorem div_mul_le_self : ∀ (m n : ℕ), m / n * n ≤ m
| m 0 := by simp; apply zero_le
| m (succ n) := (le_div_iff_mul_le _ _ (nat.succ_pos _)).1 (le_refl _)
@[simp] theorem add_div_right (x : ℕ) {z : ℕ} (H : 0 < z) : (x + z) / z = succ (x / z) :=
by rw [div_eq_sub_div H (nat.le_add_left _ _), nat.add_sub_cancel]
@[simp] theorem add_div_left (x : ℕ) {z : ℕ} (H : 0 < z) : (z + x) / z = succ (x / z) :=
by rw [nat.add_comm, add_div_right x H]
@[simp] theorem mul_div_right (n : ℕ) {m : ℕ} (H : 0 < m) : m * n / m = n :=
by {induction n; simp [*, mul_succ, nat.mul_zero] }
@[simp] theorem mul_div_left (m : ℕ) {n : ℕ} (H : 0 < n) : m * n / n = m :=
by rw [nat.mul_comm, mul_div_right _ H]
protected theorem div_self {n : ℕ} (H : 0 < n) : n / n = 1 :=
let t := add_div_right 0 H in by rwa [nat.zero_add, nat.zero_div] at t
theorem add_mul_div_left (x z : ℕ) {y : ℕ} (H : 0 < y) : (x + y * z) / y = x / y + z :=
begin
induction z with z ih,
{ rw [nat.mul_zero, nat.add_zero, nat.add_zero] },
{ rw [mul_succ, ← nat.add_assoc, add_div_right _ H, ih] }
end
theorem add_mul_div_right (x y : ℕ) {z : ℕ} (H : 0 < z) : (x + y * z) / z = x / z + y :=
by rw [nat.mul_comm, add_mul_div_left _ _ H]
protected theorem mul_div_cancel (m : ℕ) {n : ℕ} (H : 0 < n) : m * n / n = m :=
let t := add_mul_div_right 0 m H in by rwa [nat.zero_add, nat.zero_div, nat.zero_add] at t
protected theorem mul_div_cancel_left (m : ℕ) {n : ℕ} (H : 0 < n) : n * m / n = m :=
by rw [nat.mul_comm, nat.mul_div_cancel _ H]
protected theorem div_eq_of_eq_mul_left {m n k : ℕ} (H1 : 0 < n) (H2 : m = k * n) :
m / n = k :=
by rw [H2, nat.mul_div_cancel _ H1]
protected theorem div_eq_of_eq_mul_right {m n k : ℕ} (H1 : 0 < n) (H2 : m = n * k) :
m / n = k :=
by rw [H2, nat.mul_div_cancel_left _ H1]
protected theorem div_eq_of_lt_le {m n k : ℕ}
(lo : k * n ≤ m) (hi : m < succ k * n) :
m / n = k :=
have npos : 0 < n, from (eq_zero_or_pos _).resolve_left $ λ hn,
by rw [hn, nat.mul_zero] at hi lo; exact absurd lo (not_le_of_gt hi),
le_antisymm
(le_of_lt_succ ((nat.div_lt_iff_lt_mul _ _ npos).2 hi))
((nat.le_div_iff_mul_le _ _ npos).2 lo)
theorem mul_sub_div (x n p : ℕ) (h₁ : x < n*p) : (n * p - succ x) / n = p - succ (x / n) :=
begin
have npos : 0 < n := (eq_zero_or_pos _).resolve_left (λ n0,
by rw [n0, nat.zero_mul] at h₁; exact not_lt_zero _ h₁),
apply nat.div_eq_of_lt_le,
{ rw [nat.mul_sub_right_distrib, nat.mul_comm],
apply nat.sub_le_sub_left,
exact (div_lt_iff_lt_mul _ _ npos).1 (lt_succ_self _) },
{ change succ (pred (n * p - x)) ≤ (succ (pred (p - x / n))) * n,
rw [succ_pred_eq_of_pos (nat.sub_pos_of_lt h₁),
succ_pred_eq_of_pos (nat.sub_pos_of_lt _)],
{ rw [nat.mul_sub_right_distrib, nat.mul_comm],
apply nat.sub_le_sub_left, apply div_mul_le_self },
{ apply (div_lt_iff_lt_mul _ _ npos).2, rwa nat.mul_comm } }
end
protected lemma mul_pos {a b : ℕ} (ha : 0 < a) (hb : 0 < b) : 0 < a * b :=
have h : 0 * b < a * b, from nat.mul_lt_mul_of_pos_right ha hb,
by rwa nat.zero_mul at h
protected theorem div_div_eq_div_mul (m n k : ℕ) : m / n / k = m / (n * k) :=
begin
cases eq_zero_or_pos k with k0 kpos, {rw [k0, nat.mul_zero, nat.div_zero, nat.div_zero]},
cases eq_zero_or_pos n with n0 npos, {rw [n0, nat.zero_mul, nat.div_zero, nat.zero_div]},
apply le_antisymm,
{ apply (le_div_iff_mul_le _ _ (nat.mul_pos npos kpos)).2,
rw [nat.mul_comm n k, ← nat.mul_assoc],
apply (le_div_iff_mul_le _ _ npos).1,
apply (le_div_iff_mul_le _ _ kpos).1,
refl },
{ apply (le_div_iff_mul_le _ _ kpos).2,
apply (le_div_iff_mul_le _ _ npos).2,
rw [nat.mul_assoc, nat.mul_comm n k],
apply (le_div_iff_mul_le _ _ (nat.mul_pos kpos npos)).1,
refl }
end
protected theorem mul_div_mul {m : ℕ} (n k : ℕ) (H : 0 < m) : m * n / (m * k) = n / k :=
by rw [← nat.div_div_eq_div_mul, nat.mul_div_cancel_left _ H]
/- dvd -/
protected theorem dvd_mul_right (a b : ℕ) : a ∣ a * b := ⟨b, rfl⟩
protected theorem dvd_trans {a b c : ℕ} (h₁ : a ∣ b) (h₂ : b ∣ c) : a ∣ c :=
match h₁, h₂ with
| ⟨d, (h₃ : b = a * d)⟩, ⟨e, (h₄ : c = b * e)⟩ :=
⟨d * e, show c = a * (d * e), by simp [h₃, h₄, nat.mul_assoc]⟩
end
protected theorem eq_zero_of_zero_dvd {a : ℕ} (h : 0 ∣ a) : a = 0 :=
exists.elim h (assume c, assume H' : a = 0 * c, eq.trans H' (nat.zero_mul c))
protected theorem dvd_add {a b c : ℕ} (h₁ : a ∣ b) (h₂ : a ∣ c) : a ∣ b + c :=
exists.elim h₁ (λ d hd, exists.elim h₂ (λ e he, ⟨d + e, by simp [nat.left_distrib, hd, he]⟩))
protected theorem dvd_add_iff_right {k m n : ℕ} (h : k ∣ m) : k ∣ n ↔ k ∣ m + n :=
⟨nat.dvd_add h, exists.elim h $ λd hd, match m, hd with
| ._, rfl := λh₂, exists.elim h₂ $ λe he, ⟨e - d,
by rw [nat.mul_sub_left_distrib, ← he, nat.add_sub_cancel_left]⟩
end⟩
protected theorem dvd_add_iff_left {k m n : ℕ} (h : k ∣ n) : k ∣ m ↔ k ∣ m + n :=
by rw nat.add_comm; exact nat.dvd_add_iff_right h
theorem dvd_sub {k m n : ℕ} (H : n ≤ m) (h₁ : k ∣ m) (h₂ : k ∣ n) : k ∣ m - n :=
(nat.dvd_add_iff_left h₂).2 $ by rw nat.sub_add_cancel H; exact h₁
theorem dvd_mod_iff {k m n : ℕ} (h : k ∣ n) : k ∣ m % n ↔ k ∣ m :=
let t := @nat.dvd_add_iff_left _ (m % n) _ (nat.dvd_trans h (nat.dvd_mul_right n (m / n))) in
by rwa mod_add_div at t
theorem le_of_dvd {m n : ℕ} (h : 0 < n) : m ∣ n → m ≤ n :=
λ⟨k, e⟩, by {
revert h, rw e, refine k.cases_on _ _,
exact λhn, absurd hn (lt_irrefl _),
exact λk _, let t := mul_le_mul_left m (succ_pos k) in by rwa nat.mul_one at t }
theorem dvd_antisymm : Π {m n : ℕ}, m ∣ n → n ∣ m → m = n
| m 0 h₁ h₂ := nat.eq_zero_of_zero_dvd h₂
| 0 n h₁ h₂ := (nat.eq_zero_of_zero_dvd h₁).symm
| (succ m) (succ n) h₁ h₂ := le_antisymm (le_of_dvd (succ_pos _) h₁) (le_of_dvd (succ_pos _) h₂)
theorem pos_of_dvd_of_pos {m n : ℕ} (H1 : m ∣ n) (H2 : 0 < n) : 0 < m :=
nat.pos_of_ne_zero $ λm0, by rw m0 at H1; rw nat.eq_zero_of_zero_dvd H1 at H2; exact lt_irrefl _ H2
theorem eq_one_of_dvd_one {n : ℕ} (H : n ∣ 1) : n = 1 :=
le_antisymm (le_of_dvd dec_trivial H) (pos_of_dvd_of_pos H dec_trivial)
theorem dvd_of_mod_eq_zero {m n : ℕ} (H : n % m = 0) : m ∣ n :=
⟨n / m, by { have t := (mod_add_div n m).symm, rwa [H, nat.zero_add] at t }⟩
theorem mod_eq_zero_of_dvd {m n : ℕ} (H : m ∣ n) : n % m = 0 :=
exists.elim H (λ z H1, by rw [H1, mul_mod_right])
theorem dvd_iff_mod_eq_zero (m n : ℕ) : m ∣ n ↔ n % m = 0 :=
⟨mod_eq_zero_of_dvd, dvd_of_mod_eq_zero⟩
instance decidable_dvd : @decidable_rel ℕ (∣) :=
λm n, decidable_of_decidable_of_iff (by apply_instance) (dvd_iff_mod_eq_zero _ _).symm
protected theorem mul_div_cancel' {m n : ℕ} (H : n ∣ m) : n * (m / n) = m :=
let t := mod_add_div m n in by rwa [mod_eq_zero_of_dvd H, nat.zero_add] at t
protected theorem div_mul_cancel {m n : ℕ} (H : n ∣ m) : m / n * n = m :=
by rw [nat.mul_comm, nat.mul_div_cancel' H]
protected theorem mul_div_assoc (m : ℕ) {n k : ℕ} (H : k ∣ n) : m * n / k = m * (n / k) :=
or.elim (eq_zero_or_pos k)
(λh, by rw [h, nat.div_zero, nat.div_zero, nat.mul_zero])
(λh, have m * n / k = m * (n / k * k) / k, by rw nat.div_mul_cancel H,
by rw[this, ← nat.mul_assoc, nat.mul_div_cancel _ h])
theorem dvd_of_mul_dvd_mul_left {m n k : ℕ} (kpos : 0 < k) (H : k * m ∣ k * n) : m ∣ n :=
exists.elim H (λl H1, by rw nat.mul_assoc at H1; exact ⟨_, eq_of_mul_eq_mul_left kpos H1⟩)
theorem dvd_of_mul_dvd_mul_right {m n k : ℕ} (kpos : 0 < k) (H : m * k ∣ n * k) : m ∣ n :=
by rw [nat.mul_comm m k, nat.mul_comm n k] at H; exact dvd_of_mul_dvd_mul_left kpos H
/- --- -/
protected lemma mul_le_mul_of_nonneg_left {a b c : ℕ} (h₁ : a ≤ b) : c * a ≤ c * b :=
begin
by_cases hba : b ≤ a, { simp [le_antisymm hba h₁] },
by_cases hc0 : c ≤ 0, { simp [le_antisymm hc0 (zero_le c), nat.zero_mul] },
exact (le_not_le_of_lt (nat.mul_lt_mul_of_pos_left (lt_of_le_not_le h₁ hba) (lt_of_le_not_le (zero_le c) hc0))).left,
end
protected lemma mul_le_mul_of_nonneg_right {a b c : ℕ} (h₁ : a ≤ b) : a * c ≤ b * c :=
begin
by_cases hba : b ≤ a, { simp [le_antisymm hba h₁] },
by_cases hc0 : c ≤ 0, { simp [le_antisymm hc0 (zero_le c), nat.mul_zero] },
exact (le_not_le_of_lt (nat.mul_lt_mul_of_pos_right (lt_of_le_not_le h₁ hba) (lt_of_le_not_le (zero_le c) hc0))).left,
end
protected lemma mul_lt_mul {a b c d : ℕ} (hac : a < c) (hbd : b ≤ d) (pos_b : 0 < b) : a * b < c * d :=
calc
a * b < c * b : nat.mul_lt_mul_of_pos_right hac pos_b
... ≤ c * d : nat.mul_le_mul_of_nonneg_left hbd
protected lemma mul_lt_mul' {a b c d : ℕ} (h1 : a ≤ c) (h2 : b < d) (h3 : 0 < c) :
a * b < c * d :=
calc
a * b ≤ c * b : nat.mul_le_mul_of_nonneg_right h1
... < c * d : nat.mul_lt_mul_of_pos_left h2 h3
-- TODO: there are four variations, depending on which variables we assume to be nonneg
protected lemma mul_le_mul {a b c d : ℕ} (hac : a ≤ c) (hbd : b ≤ d) : a * b ≤ c * d :=
calc
a * b ≤ c * b : nat.mul_le_mul_of_nonneg_right hac
... ≤ c * d : nat.mul_le_mul_of_nonneg_left hbd
lemma div_lt_self {n m : nat} : 0 < n → 1 < m → n / m < n :=
begin
intros h₁ h₂,
have m_pos : 0 < m, { apply lt_trans _ h₂, comp_val },
suffices : 1 * n < m * n, {
rw [nat.one_mul, nat.mul_comm] at this,
exact iff.mpr (nat.div_lt_iff_lt_mul n n m_pos) this
},
exact nat.mul_lt_mul h₂ (le_refl _) h₁
end
end nat
|
914a5885e503cd28efb9b50d8b68cf35fa9049d3 | 957a80ea22c5abb4f4670b250d55534d9db99108 | /tests/lean/io_process_echo.lean | 408a4e662ff9fe1949222b50c48b8fa138fe8555 | [
"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 | 170 | lean | import system.io
variable [io.interface]
def main : io unit := do
out ← io.cmd {cmd := "echo", args := ["Hello World!"]},
io.put_str out,
return ()
#eval main
|
f84991f1ff20099753caf0109005587b03bf0e80 | 9c1ad797ec8a5eddb37d34806c543602d9a6bf70 | /monoidal_categories/drinfeld_centre.1.lean | d7d79813c98a6d4cb288d01b83c62aa3a6c611c6 | [] | no_license | timjb/lean-category-theory | 816eefc3a0582c22c05f4ee1c57ed04e57c0982f | 12916cce261d08bb8740bc85e0175b75fb2a60f4 | refs/heads/master | 1,611,078,926,765 | 1,492,080,000,000 | 1,492,080,000,000 | 88,348,246 | 0 | 0 | null | 1,492,262,499,000 | 1,492,262,498,000 | null | UTF-8 | Lean | false | false | 3,017 | lean | -- Copyright (c) 2017 Scott Morrison. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Stephen Morgan, Scott Morrison
import .drinfeld_centre
open tqft.categories
open tqft.categories.functor
open tqft.categories.products
open tqft.categories.natural_transformation
open tqft.categories.monoidal_category
namespace tqft.categories.drinfeld_centre
local attribute [ematch] MonoidalStructure.interchange_right_identity MonoidalStructure.interchange_left_identity
definition DrinfeldCentreTensorUnit { C : Category } ( m : MonoidalStructure C ) : (DrinfeldCentre m).Obj := {
object := m.tensor_unit,
commutor := vertical_composition_of_NaturalIsomorphisms m.left_unitor m.right_unitor.reverse
}
-- definition DrinfeldCentreTensorProduct { C : Category } ( m : MonoidalStructure C ) : TensorProduct (DrinfeldCentre m) := {
-- onObjects := λ p, {
-- object := m (p.1.object, p.2.object),
-- commutor := {
-- morphism := {
-- components := λ X,
-- C.compose (C.compose (C.compose (C.compose (
-- m.associator p.1.object p.2.object X
-- ) (
-- m.tensorMorphisms (C.identity p.1.object) (p.2.commutor.morphism.components X)
-- )) (
-- m.inverse_associator p.1.object X p.2.object
-- )) (
-- m.tensorMorphisms (p.1.commutor.morphism.components X) (C.identity p.2.object)
-- )) (
-- m.associator X p.1.object p.2.object
-- ),
-- naturality := sorry
-- },
-- inverse := {
-- components := sorry,
-- naturality := sorry
-- },
-- witness_1 := sorry,
-- witness_2 := sorry
-- }
-- },
-- onMorphisms := sorry,
-- identities := sorry,
-- functoriality := sorry
-- }
-- definition DrinfeldCentreAssociator { C : Category } ( m : MonoidalStructure C ) : Associator (DrinfeldCentreTensorProduct m) := {
-- components := sorry, --λ t, ⟨ m.associator_transformation ((t.1.1.object, t.1.2.object), t.2.object), sorry ⟩,
-- naturality := sorry
-- }
-- definition DrinfeldCentreAsMonoidalCategory { C : Category } ( m : MonoidalStructure C ) : MonoidalStructure (DrinfeldCentre m) := {
-- tensor_unit := DrinfeldCentreTensorUnit m,
-- tensor := DrinfeldCentreTensorProduct m,
-- associator_transformation := DrinfeldCentreAssociator m,
-- associator_is_isomorphism := sorry,
-- left_unitor := {
-- components := sorry, --λ X, ⟨ m.left_unitor X.object, sorry ⟩,
-- naturality := sorry
-- },
-- right_unitor := {
-- components := sorry, --λ X, ⟨ m.right_unitor X.object, sorry ⟩,
-- naturality := sorry
-- },
-- left_unitor_is_isomorphism := sorry,
-- right_unitor_is_isomorphism := sorry,
-- pentagon := sorry,
-- triangle := sorry
-- }
-- PROJECT Drinfeld centre as a braided category.
end tqft.categories.drinfeld_centre
|
08b6cf2360ed21f25c5ffb12ce69bafff6d95a3c | e9078bde91465351e1b354b353c9f9d8b8a9c8c2 | /colimit/move_to_lib.hlean | 8709d4209be0047c2bfc6703a0a6168ce0404b6e | [
"Apache-2.0"
] | permissive | EgbertRijke/leansnippets | 09fb7a9813477471532fbdd50c99be8d8fe3e6c4 | 1d9a7059784c92c0281fcc7ce66ac7b3619c8661 | refs/heads/master | 1,610,743,957,626 | 1,442,532,603,000 | 1,442,532,603,000 | 41,563,379 | 0 | 0 | null | 1,440,787,514,000 | 1,440,787,514,000 | null | UTF-8 | Lean | false | false | 2,648 | hlean | /-
Copyright (c) 2015 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn, Egbert Rijke
-/
-- these definitions and theorems should be moved to the HoTT library
import types.nat
open eq nat
namespace my
variables {A A' : Type} {B B' : A → Type} {C : Π⦃a⦄, B a → Type}
{a a₂ a₃ a₄ : A} {p p' : a = a₂} {p₂ : a₂ = a₃} {p₃ : a₃ = a₄}
{b b' : B a} {b₂ b₂' : B a₂} {b₃ : B a₃} {b₄ : B a₄}
{c : C b} {c₂ : C b₂}
definition cast_apo011 {P : Πa, B a → Type} {Ha : a = a₂} (Hb : b =[Ha] b₂) (p : P a b) :
cast (apo011 P Ha Hb) p = Hb ▸o p :=
by induction Hb; reflexivity
definition fn_tro_eq_tro_fn {C' : Π ⦃a : A⦄, B a → Type} (q : b =[p] b₂)
(f : Π⦃a : A⦄ (b : B a), C b → C' b) (c : C b) : f b₂ (q ▸o c) = (q ▸o (f b c)) :=
by induction q;reflexivity
-- TODO: prove for generalized apo
definition apo_tro (C : Π⦃a⦄, B' a → Type) (f : Π⦃a⦄, B a → B' a) (q : b =[p] b₂)
(c : C (f b)) : apo f q ▸o c = q ▸o c :=
by induction q; reflexivity
definition pathover_ap_tro {B' : A' → Type} (C : Π⦃a'⦄, B' a' → Type) (f : A → A')
{b : B' (f a)} {b₂ : B' (f a₂)} (q : b =[p] b₂) (c : C b) : pathover_ap B' f q ▸o c = q ▸o c :=
by induction q; reflexivity
definition pathover_ap_invo_tro {B' : A' → Type} (C : Π⦃a'⦄, B' a' → Type) (f : A → A')
{b : B' (f a)} {b₂ : B' (f a₂)} (q : b =[p] b₂) (c : C b₂)
: (pathover_ap B' f q)⁻¹ᵒ ▸o c = q⁻¹ᵒ ▸o c :=
by induction q; reflexivity
-- TODO: prove for generalized apo
definition apo_invo (f : Πa, B a → B' a) {Ha : a = a₂} (Hb : b =[Ha] b₂)
: (apo f Hb)⁻¹ᵒ = apo f Hb⁻¹ᵒ :=
by induction Hb; reflexivity
--not used
definition pathover_ap_invo {B' : A' → Type} (f : A → A') {p : a = a₂}
{b : B' (f a)} {b₂ : B' (f a₂)} (q : b =[p] b₂)
: pathover_ap B' f q⁻¹ᵒ =[ap_inv f p] (pathover_ap B' f q)⁻¹ᵒ :=
by induction q; exact idpo
definition add_add (n l k : ℕ) : n + l + k = n + (k + l) :=
begin
induction l with l IH,
reflexivity,
exact succ_add (n + l) k ⬝ ap succ IH
end
definition add.comm (n m : ℕ) : n + m = m + n :=
begin
induction n with n IH,
{ apply zero_add},
{ exact !succ_add ⬝ ap succ IH}
end
definition apo011_inv (f : Πa, B a → A') (Ha : a = a₂) (Hb : b =[Ha] b₂)
: (apo011 f Ha Hb)⁻¹ = (apo011 f Ha⁻¹ Hb⁻¹ᵒ) :=
by induction Hb; reflexivity
end my
|
d58ac51449a159455fec42bf1c83b9cee9730c14 | 38ee9024fb5974f555fb578fcf5a5a7b71e669b5 | /Mathlib/Init/Algebra/Functions.lean | 755c88f49ff6501c6ad649e5df6c837b7a9b14ae | [
"Apache-2.0"
] | permissive | denayd/mathlib4 | 750e0dcd106554640a1ac701e51517501a574715 | 7f40a5c514066801ab3c6d431e9f405baa9b9c58 | refs/heads/master | 1,693,743,991,894 | 1,636,618,048,000 | 1,636,618,048,000 | 373,926,241 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,315 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Leonardo de Moura
-/
import Mathlib.Init.Algebra.Order
universe u
section
variable {α : Type u} [LinearOrder α]
lemma min_le_left (a b : α) : min a b ≤ a :=
if h : a ≤ b
then by simp[min, if_pos h, le_refl]
else by simp[min, if_neg h]
exact le_of_not_le h
lemma min_le_right (a b : α) : min a b ≤ b :=
if h : a ≤ b
then by simp[min, if_pos h]; exact h
else by simp[min, if_neg h, le_refl]
lemma le_min {a b c : α} (h₁ : c ≤ a) (h₂ : c ≤ b) : c ≤ min a b :=
if h : a ≤ b
then by simp[min, if_pos h]; exact h₁
else by simp[min, if_neg h]; exact h₂
lemma le_max_left (a b : α) : a ≤ max a b :=
if h : b < a
then by simp[max, if_pos h, le_refl]
else by simp[max, if_neg h]
exact le_of_not_lt h
lemma le_max_right (a b : α) : b ≤ max a b :=
if h : b < a
then by simp[max, if_pos h]; exact le_of_lt h
else by simp[max, if_neg h, le_refl]
lemma max_le {a b c : α} (h₁ : a ≤ c) (h₂ : b ≤ c) : max a b ≤ c :=
if h : b < a
then by simp[max, if_pos h]; exact h₁
else by simp[max, if_neg h]; exact h₂
lemma eq_min {a b c : α} (h₁ : c ≤ a) (h₂ : c ≤ b) (h₃ : ∀{d}, d ≤ a → d ≤ b → d ≤ c) :
c = min a b :=
le_antisymm (le_min h₁ h₂) (h₃ (min_le_left a b) (min_le_right a b))
lemma min_comm (a b : α) : min a b = min b a :=
eq_min (min_le_right a b) (min_le_left a b) (λ {c} h₁ h₂ => le_min h₂ h₁)
lemma min_assoc (a b c : α) : min (min a b) c = min a (min b c) :=
by apply eq_min
. apply le_trans; apply min_le_left; apply min_le_left
. apply le_min; apply le_trans; apply min_le_left; apply min_le_right; apply min_le_right
. intros d h₁ h₂; apply le_min; apply le_min h₁; apply le_trans h₂; apply min_le_left;
apply le_trans h₂; apply min_le_right
lemma min_left_comm : @left_commutative α α min :=
left_comm min (@min_comm α _) (@min_assoc α _)
@[simp]
lemma min_self (a : α) : min a a = a := by simp[min]
lemma min_eq_left {a b : α} (h : a ≤ b) : min a b = a :=
by apply Eq.symm; apply eq_min (le_refl _) h; intros; assumption
lemma min_eq_right {a b : α} (h : b ≤ a) : min a b = b :=
by rw [min_comm]
exact min_eq_left h
lemma eq_max {a b c : α} (h₁ : a ≤ c) (h₂ : b ≤ c) (h₃ : ∀{d}, a ≤ d → b ≤ d → c ≤ d) : c = max a b :=
le_antisymm (h₃ (le_max_left a b) (le_max_right a b)) (max_le h₁ h₂)
lemma max_comm (a b : α) : max a b = max b a :=
eq_max (le_max_right a b) (le_max_left a b) (λ {c} h₁ h₂ => max_le h₂ h₁)
lemma max_assoc (a b c : α) : max (max a b) c = max a (max b c) := by
apply eq_max
· apply le_trans; apply le_max_left a b; apply le_max_left
· apply max_le; apply le_trans; apply le_max_right a b; apply le_max_left; apply le_max_right
· intros d h₁ h₂; apply max_le; apply max_le h₁; apply le_trans (le_max_left _ _) h₂;
apply le_trans (le_max_right _ _) h₂
lemma max_left_comm : ∀ (a b c : α), max a (max b c) = max b (max a c) :=
left_comm max (@max_comm α _) (@max_assoc α _)
@[simp]
lemma max_self (a : α) : max a a = a := by simp[max]
lemma max_eq_left {a b : α} (h : b ≤ a) : max a b = a :=
by apply Eq.symm; apply eq_max (le_refl _) h; intros; assumption
lemma max_eq_right {a b : α} (h : a ≤ b) : max a b = b :=
by rw [←max_comm b a]; exact max_eq_left h
/- these rely on lt_of_lt -/
lemma min_eq_left_of_lt {a b : α} (h : a < b) : min a b = a :=
min_eq_left (le_of_lt h)
lemma min_eq_right_of_lt {a b : α} (h : b < a) : min a b = b :=
min_eq_right (le_of_lt h)
lemma max_eq_left_of_lt {a b : α} (h : b < a) : max a b = a :=
max_eq_left (le_of_lt h)
lemma max_eq_right_of_lt {a b : α} (h : a < b) : max a b = b :=
max_eq_right (le_of_lt h)
/- these use the fact that it is a linear ordering -/
lemma lt_min {a b c : α} (h₁ : a < b) (h₂ : a < c) : a < min b c :=
Or.elim (le_or_gt b c)
(λ h : b ≤ c => by rwa [min_eq_left h])
(λ h : b > c => by rwa [min_eq_right_of_lt h])
lemma max_lt {a b c : α} (h₁ : a < c) (h₂ : b < c) : max a b < c :=
Or.elim (le_or_gt a b)
(λ h : a ≤ b => by rwa [max_eq_right h])
(λ h : a > b => by rwa [max_eq_left_of_lt h])
end
|
e9087944e4cfee0608c491e48578be64c66cdbb3 | 4b846d8dabdc64e7ea03552bad8f7fa74763fc67 | /library/init/propext.lean | 474eb40490efc32bd9a01f981b83bdc334dcdc78 | [
"Apache-2.0"
] | permissive | pacchiano/lean | 9324b33f3ac3b5c5647285160f9f6ea8d0d767dc | fdadada3a970377a6df8afcd629a6f2eab6e84e8 | refs/heads/master | 1,611,357,380,399 | 1,489,870,101,000 | 1,489,870,101,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 924 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
prelude
import init.logic
constant propext {a b : Prop} : (a ↔ b) → a = b
/- Additional congruence lemmas. -/
universes u v
lemma forall_congr_eq {a : Sort u} {p q : a → Prop} (h : ∀ x, p x = q x) : (∀ x, p x) = ∀ x, q x :=
propext (forall_congr (λ a, (h a)^.to_iff))
lemma imp_congr_eq {a b c d : Prop} (h₁ : a = c) (h₂ : b = d) : (a → b) = (c → d) :=
propext (imp_congr h₁^.to_iff h₂^.to_iff)
lemma imp_congr_ctx_eq {a b c d : Prop} (h₁ : a = c) (h₂ : c → (b = d)) : (a → b) = (c → d) :=
propext (imp_congr_ctx h₁^.to_iff (λ hc, (h₂ hc)^.to_iff))
lemma eq_true_intro {a : Prop} (h : a) : a = true :=
propext (iff_true_intro h)
lemma eq_false_intro {a : Prop} (h : ¬a) : a = false :=
propext (iff_false_intro h)
|
9a60346ca81fc8a5b7543848869f5bb8cd831aad | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/induction1.lean | 3a30b1b92f902e3265dde81dfe5b7c3aca95c0f3 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | leanprover/lean4 | 4bdf9790294964627eb9be79f5e8f6157780b4cc | f1f9dc0f2f531af3312398999d8b8303fa5f096b | refs/heads/master | 1,693,360,665,786 | 1,693,350,868,000 | 1,693,350,868,000 | 129,571,436 | 2,827 | 311 | Apache-2.0 | 1,694,716,156,000 | 1,523,760,560,000 | Lean | UTF-8 | Lean | false | false | 2,486 | lean | theorem tst0 {p q : Prop } (h : p ∨ q) : q ∨ p :=
by {
induction h;
{ apply Or.inr; assumption };
{ apply Or.inl; assumption }
}
theorem tst0' {p q : Prop } (h : p ∨ q) : q ∨ p := by
induction h
focus
apply Or.inr
assumption
focus
apply Or.inl
assumption
theorem tst1 {p q : Prop } (h : p ∨ q) : q ∨ p := by
induction h with
| inr h2 => exact Or.inl h2
| inl h1 => exact Or.inr h1
theorem tst6 {p q : Prop } (h : p ∨ q) : q ∨ p :=
by {
cases h with
| inr h2 => exact Or.inl h2
| inl h1 => exact Or.inr h1
}
theorem tst7 {α : Type} (xs : List α) (h : (a : α) → (as : List α) → xs ≠ a :: as) : xs = [] :=
by {
induction xs with
| nil => exact rfl
| cons z zs ih => exact absurd rfl (h z zs)
}
theorem tst8 {α : Type} (xs : List α) (h : (a : α) → (as : List α) → xs ≠ a :: as) : xs = [] := by {
induction xs;
exact rfl;
exact absurd rfl $ h _ _
}
theorem tst9 {α : Type} (xs : List α) (h : (a : α) → (as : List α) → xs ≠ a :: as) : xs = [] := by
cases xs with
| nil => exact rfl
| cons z zs => exact absurd rfl (h z zs)
theorem tst10 {p q : Prop } (h₁ : p ↔ q) (h₂ : p) : q := by
induction h₁ with
| intro h _ => exact h h₂
def Iff2 (m p q : Prop) := p ↔ q
theorem tst11 {p q r : Prop } (h₁ : Iff2 r p q) (h₂ : p) : q := by
induction h₁ using Iff.rec with
| intro h _ => exact h h₂
theorem tst12 {p q : Prop } (h₁ : p ∨ q) (h₂ : p ↔ q) (h₃ : p) : q := by
fail_if_success induction h₁ using Iff.casesOn
induction h₂ using Iff.casesOn with
| intro h _ =>
exact h h₃
inductive Tree
| leaf₁
| leaf₂
| node : Tree → Tree → Tree
def Tree.isLeaf₁ : Tree → Bool
| leaf₁ => true
| _ => false
theorem tst13 (x : Tree) (h : x = Tree.leaf₁) : x.isLeaf₁ = true := by
cases x with
| leaf₁ => rfl
| _ => injection h
theorem tst14 (x : Tree) (h : x = Tree.leaf₁) : x.isLeaf₁ = true := by
induction x with
| leaf₁ => rfl
| _ => injection h
inductive Vec (α : Type) : Nat → Type
| nil : Vec α 0
| cons : (a : α) → {n : Nat} → (as : Vec α n) → Vec α (n+1)
def getHeads {α β} {n} (xs : Vec α (n+1)) (ys : Vec β (n+1)) : α × β := by
cases xs
cases ys
apply Prod.mk
repeat
trace_state
assumption
done
theorem ex1 (n m o : Nat) : n = m + 0 → m = o → m = o := by
intro (h₁ : n = m) h₂
rw [← h₁, ← h₂]
assumption
|
5937d263eb3907fe5ae093888207c475722a892d | 57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d | /src/Lean/Compiler/NameMangling.lean | f2d22b24b771750e0dba06f8fd8e81a4539c1c97 | [
"Apache-2.0"
] | permissive | collares/lean4 | 861a9269c4592bce49b71059e232ff0bfe4594cc | 52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee | refs/heads/master | 1,691,419,031,324 | 1,618,678,138,000 | 1,618,678,138,000 | 358,989,750 | 0 | 0 | Apache-2.0 | 1,618,696,333,000 | 1,618,696,333,000 | null | UTF-8 | Lean | false | false | 1,651 | lean | /-
Copyright (c) 2018 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
import Lean.Data.Name
namespace Lean
private def String.mangleAux : Nat → String.Iterator → String → String
| 0, it, r => r
| i+1, it, r =>
let c := it.curr
if c.isAlpha || c.isDigit then
mangleAux i it.next (r.push c)
else if c = '_' then
mangleAux i it.next (r ++ "__")
else if c.toNat < 255 then
let n := c.toNat
let r := r ++ "_x"
let r := r.push $ Nat.digitChar (n / 16)
let r := r.push $ Nat.digitChar (n % 16)
mangleAux i it.next r
else
let n := c.toNat
let r := r ++ "_u"
let r := r.push $ Nat.digitChar (n / 4096)
let n := n % 4096
let r := r.push $ Nat.digitChar (n / 256)
let n := n % 256
let r := r.push $ Nat.digitChar (n / 16)
let r := r.push $ Nat.digitChar (n % 16)
mangleAux i it.next r
def String.mangle (s : String) : String :=
String.mangleAux s.length s.mkIterator ""
private def Name.mangleAux : Name → String
| Name.anonymous => ""
| Name.str p s _ =>
let m := String.mangle s
match p with
| Name.anonymous => m
| p => mangleAux p ++ "_" ++ m
| Name.num p n _ => mangleAux p ++ "_" ++ toString n ++ "_"
@[export lean_name_mangle]
def Name.mangle (n : Name) (pre : String := "l_") : String :=
pre ++ Name.mangleAux n
@[export lean_mk_module_initialization_function_name]
def mkModuleInitializationFunctionName (moduleName : Name) : String :=
"initialize_" ++ moduleName.mangle ""
end Lean
|
e94267c1262de3320629d143cb7dc180e1418366 | fe84e287c662151bb313504482b218a503b972f3 | /src/undergraduate/MAS114/fib.lean | 3ecac4561c86f225ca9d03f617c9526961668a52 | [] | no_license | NeilStrickland/lean_lib | 91e163f514b829c42fe75636407138b5c75cba83 | 6a9563de93748ace509d9db4302db6cd77d8f92c | refs/heads/master | 1,653,408,198,261 | 1,652,996,419,000 | 1,652,996,419,000 | 181,006,067 | 4 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 377 | lean | import tactic.norm_num
def FP_step' : ℕ × ℕ → ℕ × ℕ :=
λ ⟨a,b⟩, ⟨b,(a + b) % 89⟩
def FP_step : ℕ × ℕ → ℕ × ℕ :=
λ c, ⟨c.snd,(c.fst + c.snd) % 89⟩
def FP : ℕ → ℕ × ℕ
| 0 := ⟨0,1⟩
| (n + 1) := FP_step (FP n)
def F (n : ℕ) : ℕ := (FP n).fst
#eval F 25
lemma L : F 25 = 87 := by { unfold F FP FP_step; norm_num } |
d2448ca37cba763c145111b87a3c9a32c7d33f06 | c777c32c8e484e195053731103c5e52af26a25d1 | /src/algebraic_topology/dold_kan/functor_n.lean | 17a1db8bb19eb278b0084176a8b322c6f61f0420 | [
"Apache-2.0"
] | permissive | kbuzzard/mathlib | 2ff9e85dfe2a46f4b291927f983afec17e946eb8 | 58537299e922f9c77df76cb613910914a479c1f7 | refs/heads/master | 1,685,313,702,744 | 1,683,974,212,000 | 1,683,974,212,000 | 128,185,277 | 1 | 0 | null | 1,522,920,600,000 | 1,522,920,600,000 | null | UTF-8 | Lean | false | false | 2,529 | lean | /-
Copyright (c) 2022 Joël Riou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joël Riou
-/
import algebraic_topology.dold_kan.p_infty
/-!
# Construction of functors N for the Dold-Kan correspondence
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
TODO (@joelriou) continue adding the various files referenced below
In this file, we construct functors `N₁ : simplicial_object C ⥤ karoubi (chain_complex C ℕ)`
and `N₂ : karoubi (simplicial_object C) ⥤ karoubi (chain_complex C ℕ)`
for any preadditive category `C`. (The indices of these functors are the number of occurrences
of `karoubi` at the source or the target.)
In the case `C` is additive, the functor `N₂` shall be the functor of the equivalence
`category_theory.preadditive.dold_kan.equivalence` defined in `equivalence_additive.lean`.
In the case the category `C` is pseudoabelian, the composition of `N₁` with the inverse of the
equivalence `chain_complex C ℕ ⥤ karoubi (chain_complex C ℕ)` will be the functor
`category_theory.idempotents.dold_kan.N` of the equivalence of categories
`category_theory.idempotents.dold_kan.equivalence : simplicial_object C ≌ chain_complex C ℕ`
defined in `equivalence_pseudoabelian.lean`.
When the category `C` is abelian, a relation between `N₁` and the
normalized Moore complex functor shall be obtained in `normalized.lean`.
(See `equivalence.lean` for the general strategy of proof.)
-/
open category_theory
open category_theory.category
open category_theory.idempotents
noncomputable theory
namespace algebraic_topology
namespace dold_kan
variables {C : Type*} [category C] [preadditive C]
/-- The functor `simplicial_object C ⥤ karoubi (chain_complex C ℕ)` which maps
`X` to the formal direct factor of `K[X]` defined by `P_infty`. -/
@[simps]
def N₁ : simplicial_object C ⥤ karoubi (chain_complex C ℕ) :=
{ obj := λ X,
{ X := alternating_face_map_complex.obj X,
p := P_infty,
idem := P_infty_idem, },
map := λ X Y f,
{ f := P_infty ≫ alternating_face_map_complex.map f,
comm := by { ext, simp }, },
map_id' := λ X, by { ext, dsimp, simp },
map_comp' := λ X Y Z f g, by { ext, simp } }
/-- The extension of `N₁` to the Karoubi envelope of `simplicial_object C`. -/
@[simps]
def N₂ : karoubi (simplicial_object C) ⥤ karoubi (chain_complex C ℕ) :=
(functor_extension₁ _ _).obj N₁
end dold_kan
end algebraic_topology
|
99262898738bb658d1bbd4cf90b841a22e91f3ee | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/data/polynomial/degree/definitions.lean | 7bc648e34ead051bec23477d73118b42ae157ba7 | [
"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 | 49,374 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker
-/
import data.fintype.big_operators
import data.nat.with_bot
import data.polynomial.monomial
import data.polynomial.coeff
/-!
# Theory of univariate polynomials
The definitions include
`degree`, `monic`, `leading_coeff`
Results include
- `degree_mul` : The degree of the product is the sum of degrees
- `leading_coeff_add_of_degree_eq` and `leading_coeff_add_of_degree_lt` :
The leading_coefficient of a sum is determined by the leading coefficients and degrees
-/
noncomputable theory
open finsupp finset
open_locale big_operators classical polynomial
namespace polynomial
universes u v
variables {R : Type u} {S : Type v} {a b c d : R} {n m : ℕ}
section semiring
variables [semiring R] {p q r : R[X]}
/-- `degree p` is the degree of the polynomial `p`, i.e. the largest `X`-exponent in `p`.
`degree p = some n` when `p ≠ 0` and `n` is the highest power of `X` that appears in `p`, otherwise
`degree 0 = ⊥`. -/
def degree (p : R[X]) : with_bot ℕ := p.support.max
lemma degree_lt_wf : well_founded (λp q : R[X], degree p < degree q) :=
inv_image.wf degree (with_bot.well_founded_lt nat.lt_wf)
instance : has_well_founded R[X] := ⟨_, degree_lt_wf⟩
/-- `nat_degree p` forces `degree p` to ℕ, by defining nat_degree 0 = 0. -/
def nat_degree (p : R[X]) : ℕ := (degree p).unbot' 0
/-- `leading_coeff p` gives the coefficient of the highest power of `X` in `p`-/
def leading_coeff (p : R[X]) : R := coeff p (nat_degree p)
/-- a polynomial is `monic` if its leading coefficient is 1 -/
def monic (p : R[X]) := leading_coeff p = (1 : R)
@[nontriviality] lemma monic_of_subsingleton [subsingleton R] (p : R[X]) : monic p :=
subsingleton.elim _ _
lemma monic.def : monic p ↔ leading_coeff p = 1 := iff.rfl
instance monic.decidable [decidable_eq R] : decidable (monic p) :=
by unfold monic; apply_instance
@[simp] lemma monic.leading_coeff {p : R[X]} (hp : p.monic) :
leading_coeff p = 1 := hp
lemma monic.coeff_nat_degree {p : R[X]} (hp : p.monic) : p.coeff p.nat_degree = 1 := hp
@[simp] lemma degree_zero : degree (0 : R[X]) = ⊥ := rfl
@[simp] lemma nat_degree_zero : nat_degree (0 : R[X]) = 0 := rfl
@[simp] lemma coeff_nat_degree : coeff p (nat_degree p) = leading_coeff p := rfl
lemma degree_eq_bot : degree p = ⊥ ↔ p = 0 :=
⟨λ h, support_eq_empty.1 (finset.max_eq_bot.1 h),
λ h, h.symm ▸ rfl⟩
@[nontriviality] lemma degree_of_subsingleton [subsingleton R] : degree p = ⊥ :=
by rw [subsingleton.elim p 0, degree_zero]
@[nontriviality] lemma nat_degree_of_subsingleton [subsingleton R] : nat_degree p = 0 :=
by rw [subsingleton.elim p 0, nat_degree_zero]
lemma degree_eq_nat_degree (hp : p ≠ 0) : degree p = (nat_degree p : with_bot ℕ) :=
let ⟨n, hn⟩ :=
not_forall.1 (mt option.eq_none_iff_forall_not_mem.2 (mt degree_eq_bot.1 hp)) in
have hn : degree p = some n := not_not.1 hn,
by rw [nat_degree, hn]; refl
lemma degree_eq_iff_nat_degree_eq {p : R[X]} {n : ℕ} (hp : p ≠ 0) :
p.degree = n ↔ p.nat_degree = n :=
by rw [degree_eq_nat_degree hp, with_bot.coe_eq_coe]
lemma degree_eq_iff_nat_degree_eq_of_pos {p : R[X]} {n : ℕ} (hn : 0 < n) :
p.degree = n ↔ p.nat_degree = n :=
begin
split,
{ intro H, rwa ← degree_eq_iff_nat_degree_eq, rintro rfl,
rw degree_zero at H, exact option.no_confusion H },
{ intro H, rwa degree_eq_iff_nat_degree_eq, rintro rfl,
rw nat_degree_zero at H, rw H at hn, exact lt_irrefl _ hn }
end
lemma nat_degree_eq_of_degree_eq_some {p : R[X]} {n : ℕ}
(h : degree p = n) : nat_degree p = n :=
have hp0 : p ≠ 0, from λ hp0, by rw hp0 at h; exact option.no_confusion h,
option.some_inj.1 $ show (nat_degree p : with_bot ℕ) = n,
by rwa [← degree_eq_nat_degree hp0]
@[simp] lemma degree_le_nat_degree : degree p ≤ nat_degree p :=
with_bot.gi_unbot'_bot.gc.le_u_l _
lemma nat_degree_eq_of_degree_eq [semiring S] {q : S[X]} (h : degree p = degree q) :
nat_degree p = nat_degree q :=
by unfold nat_degree; rw h
lemma le_degree_of_ne_zero (h : coeff p n ≠ 0) : (n : with_bot ℕ) ≤ degree p :=
show @has_le.le (with_bot ℕ) _ (some n : with_bot ℕ) (p.support.sup some : with_bot ℕ),
from finset.le_sup (mem_support_iff.2 h)
lemma le_nat_degree_of_ne_zero (h : coeff p n ≠ 0) : n ≤ nat_degree p :=
begin
rw [← with_bot.coe_le_coe, ← degree_eq_nat_degree],
exact le_degree_of_ne_zero h,
{ assume h, subst h, exact h rfl }
end
lemma le_nat_degree_of_mem_supp (a : ℕ) :
a ∈ p.support → a ≤ nat_degree p:=
le_nat_degree_of_ne_zero ∘ mem_support_iff.mp
lemma degree_eq_of_le_of_coeff_ne_zero (pn : p.degree ≤ n) (p1 : p.coeff n ≠ 0) :
p.degree = n :=
pn.antisymm (le_degree_of_ne_zero p1)
lemma nat_degree_eq_of_le_of_coeff_ne_zero (pn : p.nat_degree ≤ n) (p1 : p.coeff n ≠ 0) :
p.nat_degree = n :=
pn.antisymm (le_nat_degree_of_ne_zero p1)
lemma degree_mono [semiring S] {f : R[X]} {g : S[X]}
(h : f.support ⊆ g.support) : f.degree ≤ g.degree := finset.sup_mono h
lemma supp_subset_range (h : nat_degree p < m) : p.support ⊆ finset.range m :=
λ n hn, mem_range.2 $ (le_nat_degree_of_mem_supp _ hn).trans_lt h
lemma supp_subset_range_nat_degree_succ : p.support ⊆ finset.range (nat_degree p + 1) :=
supp_subset_range (nat.lt_succ_self _)
lemma degree_le_degree (h : coeff q (nat_degree p) ≠ 0) : degree p ≤ degree q :=
begin
by_cases hp : p = 0,
{ rw hp, exact bot_le },
{ rw degree_eq_nat_degree hp, exact le_degree_of_ne_zero h }
end
lemma degree_ne_of_nat_degree_ne {n : ℕ} :
p.nat_degree ≠ n → degree p ≠ n :=
mt $ λ h, by rw [nat_degree, h, with_bot.unbot'_coe]
theorem nat_degree_le_iff_degree_le {n : ℕ} : nat_degree p ≤ n ↔ degree p ≤ n :=
with_bot.unbot'_bot_le_iff
lemma nat_degree_lt_iff_degree_lt (hp : p ≠ 0) :
p.nat_degree < n ↔ p.degree < ↑n :=
with_bot.unbot'_lt_iff $ degree_eq_bot.not.mpr hp
alias nat_degree_le_iff_degree_le ↔ ..
lemma nat_degree_le_nat_degree [semiring S] {q : S[X]} (hpq : p.degree ≤ q.degree) :
p.nat_degree ≤ q.nat_degree :=
with_bot.gi_unbot'_bot.gc.monotone_l hpq
@[simp] lemma degree_C (ha : a ≠ 0) : degree (C a) = (0 : with_bot ℕ) :=
by rw [degree, ← monomial_zero_left, support_monomial 0 ha, max_eq_sup_coe, sup_singleton,
with_bot.coe_zero]
lemma degree_C_le : degree (C a) ≤ 0 :=
begin
by_cases h : a = 0,
{ rw [h, C_0], exact bot_le },
{ rw [degree_C h], exact le_rfl }
end
lemma degree_C_lt : degree (C a) < 1 := degree_C_le.trans_lt $ with_bot.coe_lt_coe.mpr zero_lt_one
lemma degree_one_le : degree (1 : R[X]) ≤ (0 : with_bot ℕ) :=
by rw [← C_1]; exact degree_C_le
@[simp] lemma nat_degree_C (a : R) : nat_degree (C a) = 0 :=
begin
by_cases ha : a = 0,
{ have : C a = 0, { rw [ha, C_0] },
rw [nat_degree, degree_eq_bot.2 this],
refl },
{ rw [nat_degree, degree_C ha], refl }
end
@[simp] lemma nat_degree_one : nat_degree (1 : R[X]) = 0 := nat_degree_C 1
@[simp] lemma nat_degree_nat_cast (n : ℕ) : nat_degree (n : R[X]) = 0 :=
by simp only [←C_eq_nat_cast, nat_degree_C]
@[simp] lemma degree_monomial (n : ℕ) (ha : a ≠ 0) : degree (monomial n a) = n :=
by rw [degree, support_monomial n ha]; refl
@[simp] lemma degree_C_mul_X_pow (n : ℕ) (ha : a ≠ 0) : degree (C a * X ^ n) = n :=
by rw [C_mul_X_pow_eq_monomial, degree_monomial n ha]
lemma degree_C_mul_X (ha : a ≠ 0) : degree (C a * X) = 1 :=
by simpa only [pow_one] using degree_C_mul_X_pow 1 ha
lemma degree_monomial_le (n : ℕ) (a : R) : degree (monomial n a) ≤ n :=
if h : a = 0 then by rw [h, (monomial n).map_zero]; exact bot_le else le_of_eq (degree_monomial n h)
lemma degree_C_mul_X_pow_le (n : ℕ) (a : R) : degree (C a * X ^ n) ≤ n :=
by { rw C_mul_X_pow_eq_monomial, apply degree_monomial_le }
lemma degree_C_mul_X_le (a : R) : degree (C a * X) ≤ 1 :=
by simpa only [pow_one] using degree_C_mul_X_pow_le 1 a
@[simp] lemma nat_degree_C_mul_X_pow (n : ℕ) (a : R) (ha : a ≠ 0) : nat_degree (C a * X ^ n) = n :=
nat_degree_eq_of_degree_eq_some (degree_C_mul_X_pow n ha)
@[simp] lemma nat_degree_C_mul_X (a : R) (ha : a ≠ 0) : nat_degree (C a * X) = 1 :=
by simpa only [pow_one] using nat_degree_C_mul_X_pow 1 a ha
@[simp] lemma nat_degree_monomial [decidable_eq R] (i : ℕ) (r : R) :
nat_degree (monomial i r) = if r = 0 then 0 else i :=
begin
split_ifs with hr,
{ simp [hr] },
{ rw [← C_mul_X_pow_eq_monomial, nat_degree_C_mul_X_pow i r hr] }
end
lemma nat_degree_monomial_le (a : R) {m : ℕ} : (monomial m a).nat_degree ≤ m :=
begin
rw polynomial.nat_degree_monomial,
split_ifs,
exacts [nat.zero_le _, rfl.le],
end
lemma nat_degree_monomial_eq (i : ℕ) {r : R} (r0 : r ≠ 0) :
(monomial i r).nat_degree = i :=
eq.trans (nat_degree_monomial _ _) (if_neg r0)
lemma coeff_eq_zero_of_degree_lt (h : degree p < n) : coeff p n = 0 :=
not_not.1 (mt le_degree_of_ne_zero (not_le_of_gt h))
lemma coeff_eq_zero_of_nat_degree_lt {p : R[X]} {n : ℕ} (h : p.nat_degree < n) :
p.coeff n = 0 :=
begin
apply coeff_eq_zero_of_degree_lt,
by_cases hp : p = 0,
{ subst hp, exact with_bot.bot_lt_coe n },
{ rwa [degree_eq_nat_degree hp, with_bot.coe_lt_coe] }
end
lemma ext_iff_nat_degree_le {p q : R[X]} {n : ℕ} (hp : p.nat_degree ≤ n) (hq : q.nat_degree ≤ n) :
p = q ↔ (∀ i ≤ n, p.coeff i = q.coeff i) :=
begin
refine iff.trans polynomial.ext_iff _,
refine forall_congr (λ i, ⟨λ h _, h, λ h, _⟩),
refine (le_or_lt i n).elim h (λ k, _),
refine (coeff_eq_zero_of_nat_degree_lt (hp.trans_lt k)).trans
(coeff_eq_zero_of_nat_degree_lt (hq.trans_lt k)).symm,
end
lemma ext_iff_degree_le {p q : R[X]} {n : ℕ} (hp : p.degree ≤ n) (hq : q.degree ≤ n) :
p = q ↔ (∀ i ≤ n, p.coeff i = q.coeff i) :=
ext_iff_nat_degree_le (nat_degree_le_of_degree_le hp) (nat_degree_le_of_degree_le hq)
@[simp] lemma coeff_nat_degree_succ_eq_zero {p : R[X]} : p.coeff (p.nat_degree + 1) = 0 :=
coeff_eq_zero_of_nat_degree_lt (lt_add_one _)
-- We need the explicit `decidable` argument here because an exotic one shows up in a moment!
lemma ite_le_nat_degree_coeff (p : R[X]) (n : ℕ) (I : decidable (n < 1 + nat_degree p)) :
@ite _ (n < 1 + nat_degree p) I (coeff p n) 0 = coeff p n :=
begin
split_ifs,
{ refl },
{ exact (coeff_eq_zero_of_nat_degree_lt (not_le.1 (λ w, h (nat.lt_one_add_iff.2 w)))).symm, }
end
lemma as_sum_support (p : R[X]) :
p = ∑ i in p.support, monomial i (p.coeff i) :=
(sum_monomial_eq p).symm
lemma as_sum_support_C_mul_X_pow (p : R[X]) :
p = ∑ i in p.support, C (p.coeff i) * X^i :=
trans p.as_sum_support $ by simp only [C_mul_X_pow_eq_monomial]
/--
We can reexpress a sum over `p.support` as a sum over `range n`,
for any `n` satisfying `p.nat_degree < n`.
-/
lemma sum_over_range' [add_comm_monoid S] (p : R[X]) {f : ℕ → R → S} (h : ∀ n, f n 0 = 0)
(n : ℕ) (w : p.nat_degree < n) :
p.sum f = ∑ (a : ℕ) in range n, f a (coeff p a) :=
begin
rcases p,
have := supp_subset_range w,
simp only [polynomial.sum, support, coeff, nat_degree, degree] at ⊢ this,
exact finsupp.sum_of_support_subset _ this _ (λ n hn, h n)
end
/--
We can reexpress a sum over `p.support` as a sum over `range (p.nat_degree + 1)`.
-/
lemma sum_over_range [add_comm_monoid S] (p : R[X]) {f : ℕ → R → S} (h : ∀ n, f n 0 = 0) :
p.sum f = ∑ (a : ℕ) in range (p.nat_degree + 1), f a (coeff p a) :=
sum_over_range' p h (p.nat_degree + 1) (lt_add_one _)
-- TODO this is essentially a duplicate of `sum_over_range`, and should be removed.
lemma sum_fin [add_comm_monoid S]
(f : ℕ → R → S) (hf : ∀ i, f i 0 = 0) {n : ℕ} {p : R[X]} (hn : p.degree < n) :
∑ (i : fin n), f i (p.coeff i) = p.sum f :=
begin
by_cases hp : p = 0,
{ rw [hp, sum_zero_index, finset.sum_eq_zero], intros i _, exact hf i },
rw [sum_over_range' _ hf n ((nat_degree_lt_iff_degree_lt hp).mpr hn),
fin.sum_univ_eq_sum_range (λ i, f i (p.coeff i))],
end
lemma as_sum_range' (p : R[X]) (n : ℕ) (w : p.nat_degree < n) :
p = ∑ i in range n, monomial i (coeff p i) :=
p.sum_monomial_eq.symm.trans $ p.sum_over_range' monomial_zero_right _ w
lemma as_sum_range (p : R[X]) :
p = ∑ i in range (p.nat_degree + 1), monomial i (coeff p i) :=
p.sum_monomial_eq.symm.trans $ p.sum_over_range $ monomial_zero_right
lemma as_sum_range_C_mul_X_pow (p : R[X]) :
p = ∑ i in range (p.nat_degree + 1), C (coeff p i) * X ^ i :=
p.as_sum_range.trans $ by simp only [C_mul_X_pow_eq_monomial]
lemma coeff_ne_zero_of_eq_degree (hn : degree p = n) :
coeff p n ≠ 0 :=
λ h, mem_support_iff.mp (mem_of_max hn) h
lemma eq_X_add_C_of_degree_le_one (h : degree p ≤ 1) :
p = C (p.coeff 1) * X + C (p.coeff 0) :=
ext (λ n, nat.cases_on n (by simp)
(λ n, nat.cases_on n (by simp [coeff_C])
(λ m, have degree p < m.succ.succ, from lt_of_le_of_lt h dec_trivial,
by simp [coeff_eq_zero_of_degree_lt this, coeff_C, nat.succ_ne_zero, coeff_X,
nat.succ_inj', @eq_comm ℕ 0])))
lemma eq_X_add_C_of_degree_eq_one (h : degree p = 1) :
p = C (p.leading_coeff) * X + C (p.coeff 0) :=
(eq_X_add_C_of_degree_le_one (show degree p ≤ 1, from h ▸ le_rfl)).trans
(by simp [leading_coeff, nat_degree_eq_of_degree_eq_some h])
lemma eq_X_add_C_of_nat_degree_le_one (h : nat_degree p ≤ 1) :
p = C (p.coeff 1) * X + C (p.coeff 0) :=
eq_X_add_C_of_degree_le_one $ degree_le_of_nat_degree_le h
lemma exists_eq_X_add_C_of_nat_degree_le_one (h : nat_degree p ≤ 1) :
∃ a b, p = C a * X + C b :=
⟨p.coeff 1, p.coeff 0, eq_X_add_C_of_nat_degree_le_one h⟩
theorem degree_X_pow_le (n : ℕ) : degree (X^n : R[X]) ≤ n :=
by simpa only [C_1, one_mul] using degree_C_mul_X_pow_le n (1:R)
theorem degree_X_le : degree (X : R[X]) ≤ 1 :=
degree_monomial_le _ _
lemma nat_degree_X_le : (X : R[X]).nat_degree ≤ 1 :=
nat_degree_le_of_degree_le degree_X_le
lemma mem_support_C_mul_X_pow {n a : ℕ} {c : R} (h : a ∈ (C c * X ^ n).support) : a = n :=
mem_singleton.1 $ support_C_mul_X_pow' n c h
lemma card_support_C_mul_X_pow_le_one {c : R} {n : ℕ} : (C c * X ^ n).support.card ≤ 1 :=
begin
rw ← card_singleton n,
apply card_le_of_subset (support_C_mul_X_pow' n c),
end
lemma card_supp_le_succ_nat_degree (p : R[X]) : p.support.card ≤ p.nat_degree + 1 :=
begin
rw ← finset.card_range (p.nat_degree + 1),
exact finset.card_le_of_subset supp_subset_range_nat_degree_succ,
end
lemma le_degree_of_mem_supp (a : ℕ) :
a ∈ p.support → ↑a ≤ degree p :=
le_degree_of_ne_zero ∘ mem_support_iff.mp
lemma nonempty_support_iff : p.support.nonempty ↔ p ≠ 0 :=
by rw [ne.def, nonempty_iff_ne_empty, ne.def, ← support_eq_empty]
end semiring
section nonzero_semiring
variables [semiring R] [nontrivial R] {p q : R[X]}
@[simp] lemma degree_one : degree (1 : R[X]) = (0 : with_bot ℕ) :=
degree_C (show (1 : R) ≠ 0, from zero_ne_one.symm)
@[simp] lemma degree_X : degree (X : R[X]) = 1 :=
degree_monomial _ one_ne_zero
@[simp] lemma nat_degree_X : (X : R[X]).nat_degree = 1 :=
nat_degree_eq_of_degree_eq_some degree_X
end nonzero_semiring
section ring
variables [ring R]
lemma coeff_mul_X_sub_C {p : R[X]} {r : R} {a : ℕ} :
coeff (p * (X - C r)) (a + 1) = coeff p a - coeff p (a + 1) * r :=
by simp [mul_sub]
@[simp] lemma degree_neg (p : R[X]) : degree (-p) = degree p :=
by unfold degree; rw support_neg
@[simp] lemma nat_degree_neg (p : R[X]) : nat_degree (-p) = nat_degree p :=
by simp [nat_degree]
@[simp] lemma nat_degree_int_cast (n : ℤ) : nat_degree (n : R[X]) = 0 :=
by rw [←C_eq_int_cast, nat_degree_C]
@[simp] lemma leading_coeff_neg (p : R[X]) : (-p).leading_coeff = -p.leading_coeff :=
by rw [leading_coeff, leading_coeff, nat_degree_neg, coeff_neg]
end ring
section semiring
variables [semiring R]
/-- The second-highest coefficient, or 0 for constants -/
def next_coeff (p : R[X]) : R :=
if p.nat_degree = 0 then 0 else p.coeff (p.nat_degree - 1)
@[simp]
lemma next_coeff_C_eq_zero (c : R) :
next_coeff (C c) = 0 := by { rw next_coeff, simp }
lemma next_coeff_of_pos_nat_degree (p : R[X]) (hp : 0 < p.nat_degree) :
next_coeff p = p.coeff (p.nat_degree - 1) :=
by { rw [next_coeff, if_neg], contrapose! hp, simpa }
variables {p q : R[X]} {ι : Type*}
lemma coeff_nat_degree_eq_zero_of_degree_lt (h : degree p < degree q) :
coeff p (nat_degree q) = 0 :=
coeff_eq_zero_of_degree_lt (lt_of_lt_of_le h degree_le_nat_degree)
lemma ne_zero_of_degree_gt {n : with_bot ℕ} (h : n < degree p) : p ≠ 0 :=
mt degree_eq_bot.2 (ne.symm (ne_of_lt (lt_of_le_of_lt bot_le h)))
lemma ne_zero_of_degree_ge_degree (hpq : p.degree ≤ q.degree) (hp : p ≠ 0) : q ≠ 0 :=
polynomial.ne_zero_of_degree_gt (lt_of_lt_of_le (bot_lt_iff_ne_bot.mpr
(by rwa [ne.def, polynomial.degree_eq_bot])) hpq : q.degree > ⊥)
lemma ne_zero_of_nat_degree_gt {n : ℕ} (h : n < nat_degree p) : p ≠ 0 :=
λ H, by simpa [H, nat.not_lt_zero] using h
lemma degree_lt_degree (h : nat_degree p < nat_degree q) : degree p < degree q :=
begin
by_cases hp : p = 0,
{ simp [hp],
rw bot_lt_iff_ne_bot,
intro hq,
simpa [hp, degree_eq_bot.mp hq, lt_irrefl] using h },
{ rw [degree_eq_nat_degree hp, degree_eq_nat_degree $ ne_zero_of_nat_degree_gt h],
exact_mod_cast h }
end
lemma nat_degree_lt_nat_degree_iff (hp : p ≠ 0) :
nat_degree p < nat_degree q ↔ degree p < degree q :=
⟨degree_lt_degree, begin
intro h,
have hq : q ≠ 0 := ne_zero_of_degree_gt h,
rw [degree_eq_nat_degree hp, degree_eq_nat_degree hq] at h,
exact_mod_cast h
end⟩
lemma eq_C_of_degree_le_zero (h : degree p ≤ 0) : p = C (coeff p 0) :=
begin
ext (_|n), { simp },
rw [coeff_C, if_neg (nat.succ_ne_zero _), coeff_eq_zero_of_degree_lt],
exact h.trans_lt (with_bot.some_lt_some.2 n.succ_pos),
end
lemma eq_C_of_degree_eq_zero (h : degree p = 0) : p = C (coeff p 0) :=
eq_C_of_degree_le_zero (h ▸ le_rfl)
lemma degree_le_zero_iff : degree p ≤ 0 ↔ p = C (coeff p 0) :=
⟨eq_C_of_degree_le_zero, λ h, h.symm ▸ degree_C_le⟩
lemma degree_add_le (p q : R[X]) : degree (p + q) ≤ max (degree p) (degree q) :=
calc degree (p + q) = ((p + q).support).sup some : rfl
... ≤ (p.support ∪ q.support).sup some : sup_mono support_add
... = p.support.sup some ⊔ q.support.sup some : sup_union
lemma degree_add_le_of_degree_le {p q : R[X]} {n : ℕ} (hp : degree p ≤ n)
(hq : degree q ≤ n) : degree (p + q) ≤ n :=
(degree_add_le p q).trans $ max_le hp hq
lemma nat_degree_add_le (p q : R[X]) :
nat_degree (p + q) ≤ max (nat_degree p) (nat_degree q) :=
begin
cases le_max_iff.1 (degree_add_le p q);
simp [nat_degree_le_nat_degree h]
end
lemma nat_degree_add_le_of_degree_le {p q : R[X]} {n : ℕ} (hp : nat_degree p ≤ n)
(hq : nat_degree q ≤ n) : nat_degree (p + q) ≤ n :=
(nat_degree_add_le p q).trans $ max_le hp hq
@[simp] lemma leading_coeff_zero : leading_coeff (0 : R[X]) = 0 := rfl
@[simp] lemma leading_coeff_eq_zero : leading_coeff p = 0 ↔ p = 0 :=
⟨λ h, by_contradiction $ λ hp, mt mem_support_iff.1
(not_not.2 h) (mem_of_max (degree_eq_nat_degree hp)),
λ h, h.symm ▸ leading_coeff_zero⟩
lemma leading_coeff_ne_zero : leading_coeff p ≠ 0 ↔ p ≠ 0 :=
by rw [ne.def, leading_coeff_eq_zero]
lemma leading_coeff_eq_zero_iff_deg_eq_bot : leading_coeff p = 0 ↔ degree p = ⊥ :=
by rw [leading_coeff_eq_zero, degree_eq_bot]
lemma nat_degree_mem_support_of_nonzero (H : p ≠ 0) : p.nat_degree ∈ p.support :=
by { rw mem_support_iff, exact (not_congr leading_coeff_eq_zero).mpr H }
lemma nat_degree_eq_support_max' (h : p ≠ 0) :
p.nat_degree = p.support.max' (nonempty_support_iff.mpr h) :=
(le_max' _ _ $ nat_degree_mem_support_of_nonzero h).antisymm $
max'_le _ _ _ le_nat_degree_of_mem_supp
lemma nat_degree_C_mul_X_pow_le (a : R) (n : ℕ) : nat_degree (C a * X ^ n) ≤ n :=
nat_degree_le_iff_degree_le.2 $ degree_C_mul_X_pow_le _ _
lemma degree_add_eq_left_of_degree_lt (h : degree q < degree p) : degree (p + q) = degree p :=
le_antisymm (max_eq_left_of_lt h ▸ degree_add_le _ _) $ degree_le_degree $
begin
rw [coeff_add, coeff_nat_degree_eq_zero_of_degree_lt h, add_zero],
exact mt leading_coeff_eq_zero.1 (ne_zero_of_degree_gt h)
end
lemma degree_add_eq_right_of_degree_lt (h : degree p < degree q) : degree (p + q) = degree q :=
by rw [add_comm, degree_add_eq_left_of_degree_lt h]
lemma nat_degree_add_eq_left_of_nat_degree_lt (h : nat_degree q < nat_degree p) :
nat_degree (p + q) = nat_degree p :=
nat_degree_eq_of_degree_eq (degree_add_eq_left_of_degree_lt (degree_lt_degree h))
lemma nat_degree_add_eq_right_of_nat_degree_lt (h : nat_degree p < nat_degree q) :
nat_degree (p + q) = nat_degree q :=
nat_degree_eq_of_degree_eq (degree_add_eq_right_of_degree_lt (degree_lt_degree h))
lemma degree_add_C (hp : 0 < degree p) : degree (p + C a) = degree p :=
add_comm (C a) p ▸ degree_add_eq_right_of_degree_lt $ lt_of_le_of_lt degree_C_le hp
lemma degree_add_eq_of_leading_coeff_add_ne_zero (h : leading_coeff p + leading_coeff q ≠ 0) :
degree (p + q) = max p.degree q.degree :=
le_antisymm (degree_add_le _ _) $
match lt_trichotomy (degree p) (degree q) with
| or.inl hlt :=
by rw [degree_add_eq_right_of_degree_lt hlt, max_eq_right_of_lt hlt]; exact le_rfl
| or.inr (or.inl heq) :=
le_of_not_gt $
assume hlt : max (degree p) (degree q) > degree (p + q),
h $ show leading_coeff p + leading_coeff q = 0,
begin
rw [heq, max_self] at hlt,
rw [leading_coeff, leading_coeff, nat_degree_eq_of_degree_eq heq, ← coeff_add],
exact coeff_nat_degree_eq_zero_of_degree_lt hlt
end
| or.inr (or.inr hlt) :=
by rw [degree_add_eq_left_of_degree_lt hlt, max_eq_left_of_lt hlt]; exact le_rfl
end
lemma degree_erase_le (p : R[X]) (n : ℕ) : degree (p.erase n) ≤ degree p :=
by { rcases p, simp only [erase, degree, coeff, support], convert sup_mono (erase_subset _ _) }
lemma degree_erase_lt (hp : p ≠ 0) : degree (p.erase (nat_degree p)) < degree p :=
begin
apply lt_of_le_of_ne (degree_erase_le _ _),
rw [degree_eq_nat_degree hp, degree, support_erase],
exact λ h, not_mem_erase _ _ (mem_of_max h),
end
lemma degree_update_le (p : R[X]) (n : ℕ) (a : R) :
degree (p.update n a) ≤ max (degree p) n :=
begin
rw [degree, support_update],
split_ifs,
{ exact (finset.max_mono (erase_subset _ _)).trans (le_max_left _ _) },
{ rw [max_insert, max_comm],
exact le_rfl },
end
lemma degree_sum_le (s : finset ι) (f : ι → R[X]) :
degree (∑ i in s, f i) ≤ s.sup (λ b, degree (f b)) :=
finset.induction_on s (by simp only [sum_empty, sup_empty, degree_zero, le_refl]) $
assume a s has ih,
calc degree (∑ i in insert a s, f i) ≤ max (degree (f a)) (degree (∑ i in s, f i)) :
by rw sum_insert has; exact degree_add_le _ _
... ≤ _ : by rw [sup_insert, sup_eq_max]; exact max_le_max le_rfl ih
lemma degree_mul_le (p q : R[X]) : degree (p * q) ≤ degree p + degree q :=
calc degree (p * q) ≤ (p.support).sup (λi, degree (sum q (λj a, C (coeff p i * a) * X ^ (i + j)))) :
begin
simp only [← C_mul_X_pow_eq_monomial.symm],
convert degree_sum_le _ _,
exact mul_eq_sum_sum
end
... ≤ p.support.sup (λi, q.support.sup (λj, degree (C (coeff p i * coeff q j) * X ^ (i + j)))) :
finset.sup_mono_fun (assume i hi, degree_sum_le _ _)
... ≤ degree p + degree q :
begin
refine finset.sup_le (λ a ha, finset.sup_le (λ b hb, le_trans (degree_C_mul_X_pow_le _ _) _)),
rw [with_bot.coe_add],
rw mem_support_iff at ha hb,
exact add_le_add (le_degree_of_ne_zero ha) (le_degree_of_ne_zero hb)
end
lemma degree_pow_le (p : R[X]) : ∀ (n : ℕ), degree (p ^ n) ≤ n • (degree p)
| 0 := by rw [pow_zero, zero_nsmul]; exact degree_one_le
| (n+1) := calc degree (p ^ (n + 1)) ≤ degree p + degree (p ^ n) :
by rw pow_succ; exact degree_mul_le _ _
... ≤ _ : by rw succ_nsmul; exact add_le_add le_rfl (degree_pow_le _)
@[simp] lemma leading_coeff_monomial (a : R) (n : ℕ) : leading_coeff (monomial n a) = a :=
begin
by_cases ha : a = 0,
{ simp only [ha, (monomial n).map_zero, leading_coeff_zero] },
{ rw [leading_coeff, nat_degree_monomial, if_neg ha, coeff_monomial], simp }
end
lemma leading_coeff_C_mul_X_pow (a : R) (n : ℕ) : leading_coeff (C a * X ^ n) = a :=
by rw [C_mul_X_pow_eq_monomial, leading_coeff_monomial]
lemma leading_coeff_C_mul_X (a : R) : leading_coeff (C a * X) = a :=
by simpa only [pow_one] using leading_coeff_C_mul_X_pow a 1
@[simp] lemma leading_coeff_C (a : R) : leading_coeff (C a) = a :=
leading_coeff_monomial a 0
@[simp] lemma leading_coeff_X_pow (n : ℕ) : leading_coeff ((X : R[X]) ^ n) = 1 :=
by simpa only [C_1, one_mul] using leading_coeff_C_mul_X_pow (1 : R) n
@[simp] lemma leading_coeff_X : leading_coeff (X : R[X]) = 1 :=
by simpa only [pow_one] using @leading_coeff_X_pow R _ 1
@[simp] lemma monic_X_pow (n : ℕ) : monic (X ^ n : R[X]) := leading_coeff_X_pow n
@[simp] lemma monic_X : monic (X : R[X]) := leading_coeff_X
@[simp] lemma leading_coeff_one : leading_coeff (1 : R[X]) = 1 :=
leading_coeff_C 1
@[simp] lemma monic_one : monic (1 : R[X]) := leading_coeff_C _
lemma monic.ne_zero {R : Type*} [semiring R] [nontrivial R] {p : R[X]} (hp : p.monic) :
p ≠ 0 :=
by { rintro rfl, simpa [monic] using hp }
lemma monic.ne_zero_of_ne (h : (0:R) ≠ 1) {p : R[X]} (hp : p.monic) :
p ≠ 0 :=
by { nontriviality R, exact hp.ne_zero }
lemma monic_of_nat_degree_le_of_coeff_eq_one (n : ℕ) (pn : p.nat_degree ≤ n) (p1 : p.coeff n = 1) :
monic p :=
begin
nontriviality,
refine (congr_arg _ $ nat_degree_eq_of_le_of_coeff_ne_zero pn _).trans p1,
exact ne_of_eq_of_ne p1 one_ne_zero,
end
lemma monic_of_degree_le_of_coeff_eq_one (n : ℕ) (pn : p.degree ≤ n) (p1 : p.coeff n = 1) :
monic p :=
monic_of_nat_degree_le_of_coeff_eq_one n (nat_degree_le_of_degree_le pn) p1
lemma monic.ne_zero_of_polynomial_ne {r} (hp : monic p) (hne : q ≠ r) : p ≠ 0 :=
by { haveI := nontrivial.of_polynomial_ne hne, exact hp.ne_zero }
lemma leading_coeff_add_of_degree_lt (h : degree p < degree q) :
leading_coeff (p + q) = leading_coeff q :=
have coeff p (nat_degree q) = 0, from coeff_nat_degree_eq_zero_of_degree_lt h,
by simp only [leading_coeff, nat_degree_eq_of_degree_eq (degree_add_eq_right_of_degree_lt h),
this, coeff_add, zero_add]
lemma leading_coeff_add_of_degree_eq (h : degree p = degree q)
(hlc : leading_coeff p + leading_coeff q ≠ 0) :
leading_coeff (p + q) = leading_coeff p + leading_coeff q :=
have nat_degree (p + q) = nat_degree p,
by apply nat_degree_eq_of_degree_eq;
rw [degree_add_eq_of_leading_coeff_add_ne_zero hlc, h, max_self],
by simp only [leading_coeff, this, nat_degree_eq_of_degree_eq h, coeff_add]
@[simp] lemma coeff_mul_degree_add_degree (p q : R[X]) :
coeff (p * q) (nat_degree p + nat_degree q) = leading_coeff p * leading_coeff q :=
calc coeff (p * q) (nat_degree p + nat_degree q) =
∑ x in nat.antidiagonal (nat_degree p + nat_degree q),
coeff p x.1 * coeff q x.2 : coeff_mul _ _ _
... = coeff p (nat_degree p) * coeff q (nat_degree q) :
begin
refine finset.sum_eq_single (nat_degree p, nat_degree q) _ _,
{ rintro ⟨i,j⟩ h₁ h₂, rw nat.mem_antidiagonal at h₁,
by_cases H : nat_degree p < i,
{ rw [coeff_eq_zero_of_degree_lt
(lt_of_le_of_lt degree_le_nat_degree (with_bot.coe_lt_coe.2 H)), zero_mul] },
{ rw not_lt_iff_eq_or_lt at H, cases H,
{ subst H, rw add_left_cancel_iff at h₁, dsimp at h₁, subst h₁, exfalso, exact h₂ rfl },
{ suffices : nat_degree q < j,
{ rw [coeff_eq_zero_of_degree_lt
(lt_of_le_of_lt degree_le_nat_degree (with_bot.coe_lt_coe.2 this)), mul_zero] },
{ by_contra H', rw not_lt at H',
exact ne_of_lt (nat.lt_of_lt_of_le
(nat.add_lt_add_right H j) (nat.add_le_add_left H' _)) h₁ } } } },
{ intro H, exfalso, apply H, rw nat.mem_antidiagonal }
end
lemma degree_mul' (h : leading_coeff p * leading_coeff q ≠ 0) :
degree (p * q) = degree p + degree q :=
have hp : p ≠ 0 := by refine mt _ h; exact λ hp, by rw [hp, leading_coeff_zero, zero_mul],
have hq : q ≠ 0 := by refine mt _ h; exact λ hq, by rw [hq, leading_coeff_zero, mul_zero],
le_antisymm (degree_mul_le _ _)
begin
rw [degree_eq_nat_degree hp, degree_eq_nat_degree hq],
refine le_degree_of_ne_zero _,
rwa coeff_mul_degree_add_degree
end
lemma monic.degree_mul (hq : monic q) : degree (p * q) = degree p + degree q :=
if hp : p = 0 then by simp [hp]
else degree_mul' $ by rwa [hq.leading_coeff, mul_one, ne.def, leading_coeff_eq_zero]
lemma nat_degree_mul' (h : leading_coeff p * leading_coeff q ≠ 0) :
nat_degree (p * q) = nat_degree p + nat_degree q :=
have hp : p ≠ 0 := mt leading_coeff_eq_zero.2 (λ h₁, h $ by rw [h₁, zero_mul]),
have hq : q ≠ 0 := mt leading_coeff_eq_zero.2 (λ h₁, h $ by rw [h₁, mul_zero]),
nat_degree_eq_of_degree_eq_some $
by rw [degree_mul' h, with_bot.coe_add, degree_eq_nat_degree hp, degree_eq_nat_degree hq]
lemma leading_coeff_mul' (h : leading_coeff p * leading_coeff q ≠ 0) :
leading_coeff (p * q) = leading_coeff p * leading_coeff q :=
begin
unfold leading_coeff,
rw [nat_degree_mul' h, coeff_mul_degree_add_degree],
refl
end
lemma monomial_nat_degree_leading_coeff_eq_self (h : p.support.card ≤ 1) :
monomial p.nat_degree p.leading_coeff = p :=
begin
rcases card_support_le_one_iff_monomial.1 h with ⟨n, a, rfl⟩,
by_cases ha : a = 0;
simp [ha]
end
lemma C_mul_X_pow_eq_self (h : p.support.card ≤ 1) :
C p.leading_coeff * X^p.nat_degree = p :=
by rw [C_mul_X_pow_eq_monomial, monomial_nat_degree_leading_coeff_eq_self h]
lemma leading_coeff_pow' : leading_coeff p ^ n ≠ 0 →
leading_coeff (p ^ n) = leading_coeff p ^ n :=
nat.rec_on n (by simp) $
λ n ih h,
have h₁ : leading_coeff p ^ n ≠ 0 :=
λ h₁, h $ by rw [pow_succ, h₁, mul_zero],
have h₂ : leading_coeff p * leading_coeff (p ^ n) ≠ 0 :=
by rwa [pow_succ, ← ih h₁] at h,
by rw [pow_succ, pow_succ, leading_coeff_mul' h₂, ih h₁]
lemma degree_pow' : ∀ {n : ℕ}, leading_coeff p ^ n ≠ 0 →
degree (p ^ n) = n • (degree p)
| 0 := λ h, by rw [pow_zero, ← C_1] at *;
rw [degree_C h, zero_nsmul]
| (n+1) := λ h,
have h₁ : leading_coeff p ^ n ≠ 0 := λ h₁, h $
by rw [pow_succ, h₁, mul_zero],
have h₂ : leading_coeff p * leading_coeff (p ^ n) ≠ 0 :=
by rwa [pow_succ, ← leading_coeff_pow' h₁] at h,
by rw [pow_succ, degree_mul' h₂, succ_nsmul, degree_pow' h₁]
lemma nat_degree_pow' {n : ℕ} (h : leading_coeff p ^ n ≠ 0) :
nat_degree (p ^ n) = n * nat_degree p :=
if hp0 : p = 0 then
if hn0 : n = 0 then by simp *
else by rw [hp0, zero_pow (nat.pos_of_ne_zero hn0)]; simp
else
have hpn : p ^ n ≠ 0, from λ hpn0, have h1 : _ := h,
by rw [← leading_coeff_pow' h1, hpn0, leading_coeff_zero] at h;
exact h rfl,
option.some_inj.1 $ show (nat_degree (p ^ n) : with_bot ℕ) = (n * nat_degree p : ℕ),
by rw [← degree_eq_nat_degree hpn, degree_pow' h, degree_eq_nat_degree hp0,
← with_bot.coe_nsmul]; simp
theorem leading_coeff_monic_mul {p q : R[X]} (hp : monic p) :
leading_coeff (p * q) = leading_coeff q :=
begin
rcases eq_or_ne q 0 with rfl|H,
{ simp },
{ rw [leading_coeff_mul', hp.leading_coeff, one_mul],
rwa [hp.leading_coeff, one_mul, ne.def, leading_coeff_eq_zero] }
end
theorem leading_coeff_mul_monic {p q : R[X]} (hq : monic q) :
leading_coeff (p * q) = leading_coeff p :=
decidable.by_cases
(λ H : leading_coeff p = 0, by rw [H, leading_coeff_eq_zero.1 H, zero_mul, leading_coeff_zero])
(λ H : leading_coeff p ≠ 0,
by rw [leading_coeff_mul', hq.leading_coeff, mul_one];
rwa [hq.leading_coeff, mul_one])
@[simp] theorem leading_coeff_mul_X_pow {p : R[X]} {n : ℕ} :
leading_coeff (p * X ^ n) = leading_coeff p :=
leading_coeff_mul_monic (monic_X_pow n)
@[simp] theorem leading_coeff_mul_X {p : R[X]} :
leading_coeff (p * X) = leading_coeff p :=
leading_coeff_mul_monic monic_X
lemma nat_degree_mul_le {p q : R[X]} : nat_degree (p * q) ≤ nat_degree p + nat_degree q :=
begin
apply nat_degree_le_of_degree_le,
apply le_trans (degree_mul_le p q),
rw with_bot.coe_add,
refine add_le_add _ _; apply degree_le_nat_degree,
end
lemma nat_degree_pow_le {p : R[X]} {n : ℕ} : (p ^ n).nat_degree ≤ n * p.nat_degree :=
begin
induction n with i hi,
{ simp },
{ rw [pow_succ, nat.succ_mul, add_comm],
apply le_trans nat_degree_mul_le,
exact add_le_add_left hi _ }
end
@[simp] lemma coeff_pow_mul_nat_degree (p : R[X]) (n : ℕ) :
(p ^ n).coeff (n * p.nat_degree) = p.leading_coeff ^ n :=
begin
induction n with i hi,
{ simp },
{ rw [pow_succ', pow_succ', nat.succ_mul],
by_cases hp1 : p.leading_coeff ^ i = 0,
{ rw [hp1, zero_mul],
by_cases hp2 : p ^ i = 0,
{ rw [hp2, zero_mul, coeff_zero] },
{ apply coeff_eq_zero_of_nat_degree_lt,
have h1 : (p ^ i).nat_degree < i * p.nat_degree,
{ apply lt_of_le_of_ne nat_degree_pow_le (λ h, hp2 _),
rw [←h, hp1] at hi,
exact leading_coeff_eq_zero.mp hi },
calc (p ^ i * p).nat_degree ≤ (p ^ i).nat_degree + p.nat_degree : nat_degree_mul_le
... < i * p.nat_degree + p.nat_degree : add_lt_add_right h1 _ } },
{ rw [←nat_degree_pow' hp1, ←leading_coeff_pow' hp1],
exact coeff_mul_degree_add_degree _ _ } }
end
lemma zero_le_degree_iff : 0 ≤ degree p ↔ p ≠ 0 :=
by rw [← not_lt, nat.with_bot.lt_zero_iff, degree_eq_bot]
lemma nat_degree_eq_zero_iff_degree_le_zero : p.nat_degree = 0 ↔ p.degree ≤ 0 :=
by rw [← nonpos_iff_eq_zero, nat_degree_le_iff_degree_le, with_bot.coe_zero]
theorem degree_le_iff_coeff_zero (f : R[X]) (n : with_bot ℕ) :
degree f ≤ n ↔ ∀ m : ℕ, n < m → coeff f m = 0 :=
by simp only [degree, finset.max, finset.sup_le_iff, mem_support_iff, ne.def, ← not_le,
not_imp_comm]
theorem degree_lt_iff_coeff_zero (f : R[X]) (n : ℕ) :
degree f < n ↔ ∀ m : ℕ, n ≤ m → coeff f m = 0 :=
begin
refine ⟨λ hf m hm, coeff_eq_zero_of_degree_lt (lt_of_lt_of_le hf (with_bot.coe_le_coe.2 hm)), _⟩,
simp only [degree, finset.sup_lt_iff (with_bot.bot_lt_coe n), mem_support_iff,
with_bot.some_eq_coe, with_bot.coe_lt_coe, ← @not_le ℕ, max_eq_sup_coe],
exact λ h m, mt (h m),
end
lemma degree_smul_le (a : R) (p : R[X]) : degree (a • p) ≤ degree p :=
begin
apply (degree_le_iff_coeff_zero _ _).2 (λ m hm, _),
rw degree_lt_iff_coeff_zero at hm,
simp [hm m le_rfl],
end
lemma nat_degree_smul_le (a : R) (p : R[X]) : nat_degree (a • p) ≤ nat_degree p :=
nat_degree_le_nat_degree (degree_smul_le a p)
lemma degree_lt_degree_mul_X (hp : p ≠ 0) : p.degree < (p * X).degree :=
by haveI := nontrivial.of_polynomial_ne hp; exact
have leading_coeff p * leading_coeff X ≠ 0, by simpa,
by erw [degree_mul' this, degree_eq_nat_degree hp,
degree_X, ← with_bot.coe_one, ← with_bot.coe_add, with_bot.coe_lt_coe];
exact nat.lt_succ_self _
lemma nat_degree_pos_iff_degree_pos :
0 < nat_degree p ↔ 0 < degree p :=
lt_iff_lt_of_le_iff_le nat_degree_le_iff_degree_le
lemma eq_C_of_nat_degree_le_zero (h : nat_degree p ≤ 0) : p = C (coeff p 0) :=
eq_C_of_degree_le_zero $ degree_le_of_nat_degree_le h
lemma eq_C_of_nat_degree_eq_zero (h : nat_degree p = 0) : p = C (coeff p 0) :=
eq_C_of_nat_degree_le_zero h.le
lemma ne_zero_of_coe_le_degree (hdeg : ↑n ≤ p.degree) : p ≠ 0 :=
zero_le_degree_iff.mp $ (with_bot.coe_le_coe.mpr n.zero_le).trans hdeg
lemma le_nat_degree_of_coe_le_degree (hdeg : ↑n ≤ p.degree) :
n ≤ p.nat_degree :=
with_bot.coe_le_coe.mp ((degree_eq_nat_degree $ ne_zero_of_coe_le_degree hdeg) ▸ hdeg)
lemma degree_sum_fin_lt {n : ℕ} (f : fin n → R) :
degree (∑ i : fin n, C (f i) * X ^ (i : ℕ)) < n :=
(degree_sum_le _ _).trans_lt $ (finset.sup_lt_iff $ with_bot.bot_lt_coe n).2 $
λ k hk, (degree_C_mul_X_pow_le _ _).trans_lt $ with_bot.coe_lt_coe.2 k.is_lt
lemma degree_linear_le : degree (C a * X + C b) ≤ 1 :=
degree_add_le_of_degree_le (degree_C_mul_X_le _) $ le_trans degree_C_le nat.with_bot.coe_nonneg
lemma degree_linear_lt : degree (C a * X + C b) < 2 :=
degree_linear_le.trans_lt $ with_bot.coe_lt_coe.mpr one_lt_two
lemma degree_C_lt_degree_C_mul_X (ha : a ≠ 0) : degree (C b) < degree (C a * X) :=
by simpa only [degree_C_mul_X ha] using degree_C_lt
@[simp] lemma degree_linear (ha : a ≠ 0) : degree (C a * X + C b) = 1 :=
by rw [degree_add_eq_left_of_degree_lt $ degree_C_lt_degree_C_mul_X ha, degree_C_mul_X ha]
lemma nat_degree_linear_le : nat_degree (C a * X + C b) ≤ 1 :=
nat_degree_le_of_degree_le degree_linear_le
@[simp] lemma nat_degree_linear (ha : a ≠ 0) : nat_degree (C a * X + C b) = 1 :=
nat_degree_eq_of_degree_eq_some $ degree_linear ha
@[simp] lemma leading_coeff_linear (ha : a ≠ 0): leading_coeff (C a * X + C b) = a :=
by rw [add_comm, leading_coeff_add_of_degree_lt (degree_C_lt_degree_C_mul_X ha),
leading_coeff_C_mul_X]
lemma degree_quadratic_le : degree (C a * X ^ 2 + C b * X + C c) ≤ 2 :=
by simpa only [add_assoc] using degree_add_le_of_degree_le (degree_C_mul_X_pow_le 2 a)
(le_trans degree_linear_le $ with_bot.coe_le_coe.mpr one_le_two)
lemma degree_quadratic_lt : degree (C a * X ^ 2 + C b * X + C c) < 3 :=
degree_quadratic_le.trans_lt $ with_bot.coe_lt_coe.mpr $ lt_add_one 2
lemma degree_linear_lt_degree_C_mul_X_sq (ha : a ≠ 0) :
degree (C b * X + C c) < degree (C a * X ^ 2) :=
by simpa only [degree_C_mul_X_pow 2 ha] using degree_linear_lt
@[simp] lemma degree_quadratic (ha : a ≠ 0) : degree (C a * X ^ 2 + C b * X + C c) = 2 :=
begin
rw [add_assoc, degree_add_eq_left_of_degree_lt $ degree_linear_lt_degree_C_mul_X_sq ha,
degree_C_mul_X_pow 2 ha],
refl
end
lemma nat_degree_quadratic_le : nat_degree (C a * X ^ 2 + C b * X + C c) ≤ 2 :=
nat_degree_le_of_degree_le degree_quadratic_le
@[simp] lemma nat_degree_quadratic (ha : a ≠ 0) : nat_degree (C a * X ^ 2 + C b * X + C c) = 2 :=
nat_degree_eq_of_degree_eq_some $ degree_quadratic ha
@[simp] lemma leading_coeff_quadratic (ha : a ≠ 0) :
leading_coeff (C a * X ^ 2 + C b * X + C c) = a :=
by rw [add_assoc, add_comm, leading_coeff_add_of_degree_lt $
degree_linear_lt_degree_C_mul_X_sq ha, leading_coeff_C_mul_X_pow]
lemma degree_cubic_le : degree (C a * X ^ 3 + C b * X ^ 2 + C c * X + C d) ≤ 3 :=
by simpa only [add_assoc] using degree_add_le_of_degree_le (degree_C_mul_X_pow_le 3 a)
(le_trans degree_quadratic_le $ with_bot.coe_le_coe.mpr $ nat.le_succ 2)
lemma degree_cubic_lt : degree (C a * X ^ 3 + C b * X ^ 2 + C c * X + C d) < 4 :=
degree_cubic_le.trans_lt $ with_bot.coe_lt_coe.mpr $ lt_add_one 3
lemma degree_quadratic_lt_degree_C_mul_X_cb (ha : a ≠ 0) :
degree (C b * X ^ 2 + C c * X + C d) < degree (C a * X ^ 3) :=
by simpa only [degree_C_mul_X_pow 3 ha] using degree_quadratic_lt
@[simp] lemma degree_cubic (ha : a ≠ 0) : degree (C a * X ^ 3 + C b * X ^ 2 + C c * X + C d) = 3 :=
begin
rw [add_assoc, add_assoc, ← add_assoc (C b * X ^ 2), degree_add_eq_left_of_degree_lt $
degree_quadratic_lt_degree_C_mul_X_cb ha, degree_C_mul_X_pow 3 ha],
refl
end
lemma nat_degree_cubic_le : nat_degree (C a * X ^ 3 + C b * X ^ 2 + C c * X + C d) ≤ 3 :=
nat_degree_le_of_degree_le degree_cubic_le
@[simp] lemma nat_degree_cubic (ha : a ≠ 0) :
nat_degree (C a * X ^ 3 + C b * X ^ 2 + C c * X + C d) = 3 :=
nat_degree_eq_of_degree_eq_some $ degree_cubic ha
@[simp] lemma leading_coeff_cubic (ha : a ≠ 0):
leading_coeff (C a * X ^ 3 + C b * X ^ 2 + C c * X + C d) = a :=
by rw [add_assoc, add_assoc, ← add_assoc (C b * X ^ 2), add_comm, leading_coeff_add_of_degree_lt $
degree_quadratic_lt_degree_C_mul_X_cb ha, leading_coeff_C_mul_X_pow]
end semiring
section nontrivial_semiring
variables [semiring R] [nontrivial R] {p q : R[X]}
@[simp] lemma degree_X_pow (n : ℕ) : degree ((X : R[X]) ^ n) = n :=
by rw [X_pow_eq_monomial, degree_monomial _ (one_ne_zero' R)]
@[simp] lemma nat_degree_X_pow (n : ℕ) : nat_degree ((X : R[X]) ^ n) = n :=
nat_degree_eq_of_degree_eq_some (degree_X_pow n)
/- This lemma explicitly does not require the `nontrivial R` assumption. -/
lemma nat_degree_X_pow_le {R : Type*} [semiring R] (n : ℕ) :
(X ^ n : R[X]).nat_degree ≤ n :=
begin
nontriviality R,
rwa polynomial.nat_degree_X_pow,
end
theorem not_is_unit_X : ¬ is_unit (X : R[X]) :=
λ ⟨⟨_, g, hfg, hgf⟩, rfl⟩, zero_ne_one' R $
by { change g * monomial 1 1 = 1 at hgf, rw [← coeff_one_zero, ← hgf], simp }
@[simp] lemma degree_mul_X : degree (p * X) = degree p + 1 := by simp [monic_X.degree_mul]
@[simp] lemma degree_mul_X_pow : degree (p * X ^ n) = degree p + n :=
by simp [(monic_X_pow n).degree_mul]
end nontrivial_semiring
section ring
variables [ring R] {p q : R[X]}
lemma degree_sub_le (p q : R[X]) : degree (p - q) ≤ max (degree p) (degree q) :=
by simpa only [sub_eq_add_neg, degree_neg q] using degree_add_le p (-q)
lemma degree_sub_lt (hd : degree p = degree q)
(hp0 : p ≠ 0) (hlc : leading_coeff p = leading_coeff q) :
degree (p - q) < degree p :=
have hp : monomial (nat_degree p) (leading_coeff p) + p.erase (nat_degree p) = p :=
monomial_add_erase _ _,
have hq : monomial (nat_degree q) (leading_coeff q) + q.erase (nat_degree q) = q :=
monomial_add_erase _ _,
have hd' : nat_degree p = nat_degree q := by unfold nat_degree; rw hd,
have hq0 : q ≠ 0 := mt degree_eq_bot.2 (hd ▸ mt degree_eq_bot.1 hp0),
calc degree (p - q) = degree (erase (nat_degree q) p + -erase (nat_degree q) q) :
by conv { to_lhs, rw [← hp, ← hq, hlc, hd', add_sub_add_left_eq_sub, sub_eq_add_neg] }
... ≤ max (degree (erase (nat_degree q) p)) (degree (erase (nat_degree q) q))
: degree_neg (erase (nat_degree q) q) ▸ degree_add_le _ _
... < degree p : max_lt_iff.2 ⟨hd' ▸ degree_erase_lt hp0, hd.symm ▸ degree_erase_lt hq0⟩
lemma degree_X_sub_C_le (r : R) : (X - C r).degree ≤ 1 :=
(degree_sub_le _ _).trans (max_le degree_X_le (degree_C_le.trans zero_le_one))
lemma nat_degree_X_sub_C_le (r : R) : (X - C r).nat_degree ≤ 1 :=
nat_degree_le_iff_degree_le.2 $ degree_X_sub_C_le r
lemma degree_sub_eq_left_of_degree_lt (h : degree q < degree p) : degree (p - q) = degree p :=
by { rw ← degree_neg q at h, rw [sub_eq_add_neg, degree_add_eq_left_of_degree_lt h] }
lemma degree_sub_eq_right_of_degree_lt (h : degree p < degree q) : degree (p - q) = degree q :=
by { rw ← degree_neg q at h, rw [sub_eq_add_neg, degree_add_eq_right_of_degree_lt h, degree_neg] }
lemma nat_degree_sub_eq_left_of_nat_degree_lt (h : nat_degree q < nat_degree p) :
nat_degree (p - q) = nat_degree p :=
nat_degree_eq_of_degree_eq (degree_sub_eq_left_of_degree_lt (degree_lt_degree h))
lemma nat_degree_sub_eq_right_of_nat_degree_lt (h : nat_degree p < nat_degree q) :
nat_degree (p - q) = nat_degree q :=
nat_degree_eq_of_degree_eq (degree_sub_eq_right_of_degree_lt (degree_lt_degree h))
end ring
section nonzero_ring
variables [nontrivial R]
section semiring
variable [semiring R]
@[simp] lemma degree_X_add_C (a : R) : degree (X + C a) = 1 :=
have degree (C a) < degree (X : R[X]),
from calc degree (C a) ≤ 0 : degree_C_le
... < 1 : with_bot.some_lt_some.mpr zero_lt_one
... = degree X : degree_X.symm,
by rw [degree_add_eq_left_of_degree_lt this, degree_X]
@[simp] lemma nat_degree_X_add_C (x : R) : (X + C x).nat_degree = 1 :=
nat_degree_eq_of_degree_eq_some $ degree_X_add_C x
@[simp]
lemma next_coeff_X_add_C [semiring S] (c : S) : next_coeff (X + C c) = c :=
begin
nontriviality S,
simp [next_coeff_of_pos_nat_degree]
end
lemma degree_X_pow_add_C {n : ℕ} (hn : 0 < n) (a : R) :
degree ((X : R[X]) ^ n + C a) = n :=
have degree (C a) < degree ((X : R[X]) ^ n),
from degree_C_le.trans_lt $ by rwa [degree_X_pow, with_bot.coe_pos],
by rw [degree_add_eq_left_of_degree_lt this, degree_X_pow]
lemma X_pow_add_C_ne_zero {n : ℕ} (hn : 0 < n) (a : R) :
(X : R[X]) ^ n + C a ≠ 0 :=
mt degree_eq_bot.2 (show degree ((X : R[X]) ^ n + C a) ≠ ⊥,
by rw degree_X_pow_add_C hn a; exact dec_trivial)
theorem X_add_C_ne_zero (r : R) : X + C r ≠ 0 :=
pow_one (X : R[X]) ▸ X_pow_add_C_ne_zero zero_lt_one r
theorem zero_nmem_multiset_map_X_add_C {α : Type*} (m : multiset α) (f : α → R) :
(0 : R[X]) ∉ m.map (λ a, X + C (f a)) :=
λ mem, let ⟨a, _, ha⟩ := multiset.mem_map.mp mem in X_add_C_ne_zero _ ha
lemma nat_degree_X_pow_add_C {n : ℕ} {r : R} :
(X ^ n + C r).nat_degree = n :=
begin
by_cases hn : n = 0,
{ rw [hn, pow_zero, ←C_1, ←ring_hom.map_add, nat_degree_C] },
{ exact nat_degree_eq_of_degree_eq_some (degree_X_pow_add_C (pos_iff_ne_zero.mpr hn) r) },
end
end semiring
end nonzero_ring
section semiring
variable [semiring R]
@[simp] lemma leading_coeff_X_pow_add_C {n : ℕ} (hn : 0 < n) {r : R} :
(X ^ n + C r).leading_coeff = 1 :=
begin
nontriviality R,
rw [leading_coeff, nat_degree_X_pow_add_C, coeff_add, coeff_X_pow_self,
coeff_C, if_neg (pos_iff_ne_zero.mp hn), add_zero]
end
@[simp] lemma leading_coeff_X_add_C [semiring S] (r : S) :
(X + C r).leading_coeff = 1 :=
by rw [←pow_one (X : S[X]), leading_coeff_X_pow_add_C zero_lt_one]
@[simp] lemma leading_coeff_X_pow_add_one {n : ℕ} (hn : 0 < n) :
(X ^ n + 1 : R[X]).leading_coeff = 1 :=
leading_coeff_X_pow_add_C hn
@[simp] lemma leading_coeff_pow_X_add_C (r : R) (i : ℕ) :
leading_coeff ((X + C r) ^ i) = 1 :=
by { nontriviality, rw leading_coeff_pow'; simp }
end semiring
section ring
variable [ring R]
@[simp] lemma leading_coeff_X_pow_sub_C {n : ℕ} (hn : 0 < n) {r : R} :
(X ^ n - C r).leading_coeff = 1 :=
by rw [sub_eq_add_neg, ←map_neg C r, leading_coeff_X_pow_add_C hn]; apply_instance
@[simp] lemma leading_coeff_X_pow_sub_one {n : ℕ} (hn : 0 < n) :
(X ^ n - 1 : R[X]).leading_coeff = 1 :=
leading_coeff_X_pow_sub_C hn
variables [nontrivial R]
@[simp] lemma degree_X_sub_C (a : R) : degree (X - C a) = 1 :=
by rw [sub_eq_add_neg, ←map_neg C a, degree_X_add_C]
@[simp] lemma nat_degree_X_sub_C (x : R) : (X - C x).nat_degree = 1 :=
nat_degree_eq_of_degree_eq_some $ degree_X_sub_C x
@[simp]
lemma next_coeff_X_sub_C [ring S] (c : S) : next_coeff (X - C c) = - c :=
by rw [sub_eq_add_neg, ←map_neg C c, next_coeff_X_add_C]
lemma degree_X_pow_sub_C {n : ℕ} (hn : 0 < n) (a : R) :
degree ((X : R[X]) ^ n - C a) = n :=
by rw [sub_eq_add_neg, ←map_neg C a, degree_X_pow_add_C hn]; apply_instance
lemma X_pow_sub_C_ne_zero {n : ℕ} (hn : 0 < n) (a : R) :
(X : R[X]) ^ n - C a ≠ 0 :=
by { rw [sub_eq_add_neg, ←map_neg C a], exact X_pow_add_C_ne_zero hn _ }
theorem X_sub_C_ne_zero (r : R) : X - C r ≠ 0 :=
pow_one (X : R[X]) ▸ X_pow_sub_C_ne_zero zero_lt_one r
theorem zero_nmem_multiset_map_X_sub_C {α : Type*} (m : multiset α) (f : α → R) :
(0 : R[X]) ∉ m.map (λ a, X - C (f a)) :=
λ mem, let ⟨a, _, ha⟩ := multiset.mem_map.mp mem in X_sub_C_ne_zero _ ha
lemma nat_degree_X_pow_sub_C {n : ℕ} {r : R} :
(X ^ n - C r).nat_degree = n :=
by rw [sub_eq_add_neg, ←map_neg C r, nat_degree_X_pow_add_C]
@[simp] lemma leading_coeff_X_sub_C [ring S] (r : S) :
(X - C r).leading_coeff = 1 :=
by rw [sub_eq_add_neg, ←map_neg C r, leading_coeff_X_add_C]
end ring
section no_zero_divisors
variables [semiring R] [no_zero_divisors R] {p q : R[X]}
@[simp] lemma degree_mul : degree (p * q) = degree p + degree q :=
if hp0 : p = 0 then by simp only [hp0, degree_zero, zero_mul, with_bot.bot_add]
else if hq0 : q = 0 then by simp only [hq0, degree_zero, mul_zero, with_bot.add_bot]
else degree_mul' $ mul_ne_zero (mt leading_coeff_eq_zero.1 hp0)
(mt leading_coeff_eq_zero.1 hq0)
/-- `degree` as a monoid homomorphism between `R[X]` and `multiplicative (with_bot ℕ)`.
This is useful to prove results about multiplication and degree. -/
def degree_monoid_hom [nontrivial R] : R[X] →* multiplicative (with_bot ℕ) :=
{ to_fun := degree,
map_one' := degree_one,
map_mul' := λ _ _, degree_mul }
@[simp] lemma degree_pow [nontrivial R] (p : R[X]) (n : ℕ) :
degree (p ^ n) = n • (degree p) :=
map_pow (@degree_monoid_hom R _ _ _) _ _
@[simp] lemma leading_coeff_mul (p q : R[X]) : leading_coeff (p * q) =
leading_coeff p * leading_coeff q :=
begin
by_cases hp : p = 0,
{ simp only [hp, zero_mul, leading_coeff_zero] },
{ by_cases hq : q = 0,
{ simp only [hq, mul_zero, leading_coeff_zero] },
{ rw [leading_coeff_mul'],
exact mul_ne_zero (mt leading_coeff_eq_zero.1 hp) (mt leading_coeff_eq_zero.1 hq) } }
end
/-- `polynomial.leading_coeff` bundled as a `monoid_hom` when `R` has `no_zero_divisors`, and thus
`leading_coeff` is multiplicative -/
def leading_coeff_hom : R[X] →* R :=
{ to_fun := leading_coeff,
map_one' := by simp,
map_mul' := leading_coeff_mul }
@[simp] lemma leading_coeff_hom_apply (p : R[X]) :
leading_coeff_hom p = leading_coeff p := rfl
@[simp] lemma leading_coeff_pow (p : R[X]) (n : ℕ) :
leading_coeff (p ^ n) = leading_coeff p ^ n :=
(leading_coeff_hom : R[X] →* R).map_pow p n
end no_zero_divisors
end polynomial
|
46f662e5f77895183f87df78a4d09b03e52d7923 | 94637389e03c919023691dcd05bd4411b1034aa5 | /src/inClassNotes/final/var.lean | 9d5ffbce50ad59921571859ba6ef9cf5b93bb621 | [] | no_license | kevinsullivan/complogic-s21 | 7c4eef2105abad899e46502270d9829d913e8afc | 99039501b770248c8ceb39890be5dfe129dc1082 | refs/heads/master | 1,682,985,669,944 | 1,621,126,241,000 | 1,621,126,241,000 | 335,706,272 | 0 | 38 | null | 1,618,325,669,000 | 1,612,374,118,000 | Lean | UTF-8 | Lean | false | false | 836 | lean | /-
Implement a programmer-friendly interface
for looking up the value of variables with
values of different types: a typeclasses,
has_vars (T : Type) := (init : var T -> T).
In other words, each type contributes an
instance, and thus a definition what what
environment to use as the init environment
for that type.
-/
universe u
/-
Variables for values of type α, indexed by nat
-/
structure var (α : Type u) : Type u :=
(n : nat)
-- This work?
def var_eq {α : Type} : var α → var α → bool
| (var.mk n1) (var.mk n2) := n1 = n2
/-
The type of our state function for α-valued variables
-/
def var_state (α : Type u) :=
var α → α
/-
An initial state value for each var-supporting type
Implement to enable eval evalation for values of var α
-/
class has_var (α : Type u) :=
(init : var_state α)
|
53eb34ce472eb566cdea7089686fba55d1be289a | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/control/traversable/default.lean | 435a73942d41ef98dab3b478c376bbacdfccdec4 | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 191 | lean | import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.control.traversable.instances
import Mathlib.control.traversable.lemmas
import Mathlib.PostPort
namespace Mathlib
|
fc1636d0a4952314a0c52dd2049a4b0f0fb3918a | 0003047346476c031128723dfd16fe273c6bc605 | /src/data/padics/padic_integers.lean | 8eb9c3d280d01ad5bbedb86c054b4406659ef6c5 | [
"Apache-2.0"
] | permissive | ChandanKSingh/mathlib | d2bf4724ccc670bf24915c12c475748281d3fb73 | d60d1616958787ccb9842dc943534f90ea0bab64 | refs/heads/master | 1,588,238,823,679 | 1,552,867,469,000 | 1,552,867,469,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 9,316 | lean | /-
Copyright (c) 2018 Robert Y. Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Robert Y. Lewis, Mario Carneiro
Define the p-adic integers ℤ_p as a subtype of ℚ_p. Construct algebraic structures on ℤ_p.
-/
import data.padics.padic_numbers ring_theory.ideals data.int.modeq
import tactic.linarith
open nat padic metric
noncomputable theory
local attribute [instance] classical.prop_decidable
def padic_int (p : ℕ) [p.prime] := {x : ℚ_[p] // ∥x∥ ≤ 1}
notation `ℤ_[`p`]` := padic_int p
namespace padic_int
variables {p : ℕ} [nat.prime p]
def add : ℤ_[p] → ℤ_[p] → ℤ_[p]
| ⟨x, hx⟩ ⟨y, hy⟩ := ⟨x+y,
le_trans (padic_norm_e.nonarchimedean _ _) (max_le_iff.2 ⟨hx,hy⟩)⟩
def mul : ℤ_[p] → ℤ_[p] → ℤ_[p]
| ⟨x, hx⟩ ⟨y, hy⟩ := ⟨x*y,
begin rw padic_norm_e.mul, apply mul_le_one; {assumption <|> apply norm_nonneg} end⟩
def neg : ℤ_[p] → ℤ_[p]
| ⟨x, hx⟩ := ⟨-x, by simpa⟩
instance : ring ℤ_[p] :=
begin
refine { add := add,
mul := mul,
neg := neg,
zero := ⟨0, by simp [zero_le_one]⟩,
one := ⟨1, by simp⟩,
.. };
{repeat {rintro ⟨_, _⟩}, simp [mul_assoc, left_distrib, right_distrib, add, mul, neg]}
end
lemma zero_def : ∀ x : ℤ_[p], x = 0 ↔ x.val = 0
| ⟨x, _⟩ := ⟨subtype.mk.inj, λ h, by simp at h; simp only [h]; refl⟩
@[simp] lemma add_def : ∀ (x y : ℤ_[p]), (x+y).val = x.val + y.val
| ⟨x, hx⟩ ⟨y, hy⟩ := rfl
@[simp] lemma mul_def : ∀ (x y : ℤ_[p]), (x*y).val = x.val * y.val
| ⟨x, hx⟩ ⟨y, hy⟩ := rfl
@[simp] lemma mk_zero {h} : (⟨0, h⟩ : ℤ_[p]) = (0 : ℤ_[p]) := rfl
instance : has_coe ℤ_[p] ℚ_[p] := ⟨subtype.val⟩
@[simp] lemma val_eq_coe (z : ℤ_[p]) : z.val = ↑z := rfl
@[simp] lemma coe_add : ∀ (z1 z2 : ℤ_[p]), (↑(z1 + z2) : ℚ_[p]) = ↑z1 + ↑z2
| ⟨_, _⟩ ⟨_, _⟩ := rfl
@[simp] lemma coe_mul : ∀ (z1 z2 : ℤ_[p]), (↑(z1 * z2) : ℚ_[p]) = ↑z1 * ↑z2
| ⟨_, _⟩ ⟨_, _⟩ := rfl
@[simp] lemma coe_neg : ∀ (z1 : ℤ_[p]), (↑(-z1) : ℚ_[p]) = -↑z1
| ⟨_, _⟩ := rfl
@[simp] lemma coe_sub : ∀ (z1 z2 : ℤ_[p]), (↑(z1 - z2) : ℚ_[p]) = ↑z1 - ↑z2
| ⟨_, _⟩ ⟨_, _⟩ := rfl
@[simp] lemma coe_one : (↑(1 : ℤ_[p]) : ℚ_[p]) = 1 := rfl
@[simp] lemma coe_coe : ∀ n : ℕ, (↑(↑n : ℤ_[p]) : ℚ_[p]) = (↑n : ℚ_[p])
| 0 := rfl
| (k+1) := by simp [coe_coe]
@[simp] lemma coe_zero : (↑(0 : ℤ_[p]) : ℚ_[p]) = 0 := rfl
@[simp] lemma cast_pow (x : ℤ_[p]) : ∀ (n : ℕ), (↑(x^n) : ℚ_[p]) = (↑x : ℚ_[p])^n
| 0 := by simp
| (k+1) := by simp [monoid.pow, pow]; congr; apply cast_pow
lemma mk_coe : ∀ (k : ℤ_[p]), (⟨↑k, k.2⟩ : ℤ_[p]) = k
| ⟨_, _⟩ := rfl
def inv : ℤ_[p] → ℤ_[p]
| ⟨k, _⟩ := if h : ∥k∥ = 1 then ⟨1/k, by simp [h]⟩ else 0
end padic_int
section instances
variables {p : ℕ} [nat.prime p]
@[reducible] def padic_norm_z (z : ℤ_[p]) : ℝ := ∥z.val∥
instance : metric_space ℤ_[p] := subtype.metric_space
instance : has_norm ℤ_[p] := ⟨padic_norm_z⟩
instance : normed_ring ℤ_[p] :=
{ dist_eq := λ ⟨_, _⟩ ⟨_, _⟩, rfl,
norm_mul := λ ⟨_, _⟩ ⟨_, _⟩, norm_mul _ _ }
instance padic_norm_z.is_absolute_value : is_absolute_value (λ z : ℤ_[p], ∥z∥) :=
{ abv_nonneg := norm_nonneg,
abv_eq_zero := λ ⟨_, _⟩, by simp [norm_eq_zero, padic_int.zero_def],
abv_add := λ ⟨_,_⟩ ⟨_, _⟩, norm_triangle _ _,
abv_mul := λ _ _, by unfold norm; simp [padic_norm_z] }
protected lemma padic_int.pmul_comm : ∀ z1 z2 : ℤ_[p], z1*z2 = z2*z1
| ⟨q1, h1⟩ ⟨q2, h2⟩ := show (⟨q1*q2, _⟩ : ℤ_[p]) = ⟨q2*q1, _⟩, by simp [mul_comm]
instance : comm_ring ℤ_[p] :=
{ mul_comm := padic_int.pmul_comm,
..padic_int.ring }
protected lemma padic_int.zero_ne_one : (0 : ℤ_[p]) ≠ 1 :=
show (⟨(0 : ℚ_[p]), _⟩ : ℤ_[p]) ≠ ⟨(1 : ℚ_[p]), _⟩, from mt subtype.ext.1 zero_ne_one
protected lemma padic_int.eq_zero_or_eq_zero_of_mul_eq_zero :
∀ (a b : ℤ_[p]), a * b = 0 → a = 0 ∨ b = 0
| ⟨a, ha⟩ ⟨b, hb⟩ := λ h : (⟨a * b, _⟩ : ℤ_[p]) = ⟨0, _⟩,
have a * b = 0, from subtype.ext.1 h,
(mul_eq_zero_iff_eq_zero_or_eq_zero.1 this).elim
(λ h1, or.inl (by simp [h1]; refl))
(λ h2, or.inr (by simp [h2]; refl))
instance : integral_domain ℤ_[p] :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := padic_int.eq_zero_or_eq_zero_of_mul_eq_zero,
zero_ne_one := padic_int.zero_ne_one,
..padic_int.comm_ring }
end instances
namespace padic_norm_z
variables {p : ℕ} [nat.prime p]
lemma le_one : ∀ z : ℤ_[p], ∥z∥ ≤ 1
| ⟨_, h⟩ := h
@[simp] lemma one : ∥(1 : ℤ_[p])∥ = 1 := by simp [norm, padic_norm_z]
@[simp] lemma mul (z1 z2 : ℤ_[p]) : ∥z1 * z2∥ = ∥z1∥ * ∥z2∥ :=
by unfold norm; simp [padic_norm_z]
@[simp] lemma pow (z : ℤ_[p]) : ∀ n : ℕ, ∥z^n∥ = ∥z∥^n
| 0 := by simp
| (k+1) := show ∥z*z^k∥ = ∥z∥*∥z∥^k, by {rw mul, congr, apply pow}
theorem nonarchimedean : ∀ (q r : ℤ_[p]), ∥q + r∥ ≤ max (∥q∥) (∥r∥)
| ⟨_, _⟩ ⟨_, _⟩ := padic_norm_e.nonarchimedean _ _
theorem add_eq_max_of_ne : ∀ {q r : ℤ_[p]}, ∥q∥ ≠ ∥r∥ → ∥q+r∥ = max (∥q∥) (∥r∥)
| ⟨_, _⟩ ⟨_, _⟩ := padic_norm_e.add_eq_max_of_ne
@[simp] lemma norm_one : ∥(1 : ℤ_[p])∥ = 1 := norm_one
lemma eq_of_norm_add_lt_right {z1 z2 : ℤ_[p]}
(h : ∥z1 + z2∥ < ∥z2∥) : ∥z1∥ = ∥z2∥ :=
by_contradiction $ λ hne,
not_lt_of_ge (by rw padic_norm_z.add_eq_max_of_ne hne; apply le_max_right) h
lemma eq_of_norm_add_lt_left {z1 z2 : ℤ_[p]}
(h : ∥z1 + z2∥ < ∥z1∥) : ∥z1∥ = ∥z2∥ :=
by_contradiction $ λ hne,
not_lt_of_ge (by rw padic_norm_z.add_eq_max_of_ne hne; apply le_max_left) h
@[simp] lemma padic_norm_e_of_padic_int (z : ℤ_[p]) : ∥(↑z : ℚ_[p])∥ = ∥z∥ :=
by simp [norm, padic_norm_z]
@[simp] lemma padic_norm_z_eq_padic_norm_e {q : ℚ_[p]} (hq : ∥q∥ ≤ 1) :
@norm ℤ_[p] _ ⟨q, hq⟩ = ∥q∥ := rfl
end padic_norm_z
private lemma mul_lt_one {α} [decidable_linear_ordered_comm_ring α] {a b : α} (hbz : 0 < b)
(ha : a < 1) (hb : b < 1) : a * b < 1 :=
suffices a*b < 1*1, by simpa,
mul_lt_mul ha (le_of_lt hb) hbz zero_le_one
private lemma mul_lt_one_of_le_of_lt {α} [decidable_linear_ordered_comm_ring α] {a b : α} (ha : a ≤ 1)
(hbz : 0 ≤ b) (hb : b < 1) : a * b < 1 :=
if hb' : b = 0 then by simpa [hb'] using zero_lt_one
else if ha' : a = 1 then by simpa [ha']
else mul_lt_one (lt_of_le_of_ne hbz (ne.symm hb')) (lt_of_le_of_ne ha ha') hb
namespace padic_int
variables {p : ℕ} [nat.prime p]
local attribute [reducible] padic_int
lemma mul_inv : ∀ {z : ℤ_[p]}, ∥z∥ = 1 → z * z.inv = 1
| ⟨k, _⟩ h :=
begin
have hk : k ≠ 0, from λ h', @zero_ne_one ℚ_[p] _ (by simpa [h'] using h),
unfold padic_int.inv, split_ifs,
{ change (⟨k * (1/k), _⟩ : ℤ_[p]) = 1,
simp [hk], refl },
{ apply subtype.ext.2, simp [mul_inv_cancel hk] }
end
lemma inv_mul {z : ℤ_[p]} (hz : ∥z∥ = 1) : z.inv * z = 1 :=
by rw [mul_comm, mul_inv hz]
lemma is_unit_iff {z : ℤ_[p]} : is_unit z ↔ ∥z∥ = 1 :=
⟨λ h, begin
rcases is_unit_iff_dvd_one.1 h with ⟨w, eq⟩,
refine le_antisymm (padic_norm_z.le_one _) _,
have := mul_le_mul_of_nonneg_left (padic_norm_z.le_one w) (norm_nonneg z),
rwa [mul_one, ← padic_norm_z.mul, ← eq, padic_norm_z.one] at this
end, λ h, ⟨⟨z, z.inv, mul_inv h, inv_mul h⟩, rfl⟩⟩
lemma norm_lt_one_add {z1 z2 : ℤ_[p]} (hz1 : ∥z1∥ < 1) (hz2 : ∥z2∥ < 1) : ∥z1 + z2∥ < 1 :=
lt_of_le_of_lt (padic_norm_z.nonarchimedean _ _) (max_lt hz1 hz2)
lemma norm_lt_one_mul {z1 z2 : ℤ_[p]} (hz2 : ∥z2∥ < 1) : ∥z1 * z2∥ < 1 :=
calc ∥z1 * z2∥ = ∥z1∥ * ∥z2∥ : by simp
... < 1 : mul_lt_one_of_le_of_lt (padic_norm_z.le_one _) (norm_nonneg _) hz2
@[simp] lemma mem_nonunits {z : ℤ_[p]} : z ∈ nonunits ℤ_[p] ↔ ∥z∥ < 1 :=
by rw lt_iff_le_and_ne; simp [padic_norm_z.le_one z, nonunits, is_unit_iff]
instance : is_local_ring ℤ_[p] :=
local_of_nonunits_ideal zero_ne_one $ λ x y, by simp; exact norm_lt_one_add
private def cau_seq_to_rat_cau_seq (f : cau_seq ℤ_[p] norm) :
cau_seq ℚ_[p] (λ a, ∥a∥) :=
⟨ λ n, f n,
λ _ hε, by simpa [norm, padic_norm_z] using f.cauchy hε ⟩
instance complete : cau_seq.is_complete ℤ_[p] norm :=
⟨ λ f,
have hqn : ∥cau_seq.lim (cau_seq_to_rat_cau_seq f)∥ ≤ 1,
from padic_norm_e_lim_le zero_lt_one (λ _, padic_norm_z.le_one _),
⟨ ⟨_, hqn⟩,
λ ε, by simpa [norm, padic_norm_z] using cau_seq.equiv_lim (cau_seq_to_rat_cau_seq f) ε⟩⟩
end padic_int
namespace padic_norm_z
variables {p : ℕ} [nat.prime p]
lemma padic_val_of_cong_pow_p {z1 z2 : ℤ} {n : ℕ} (hz : z1 ≡ z2 [ZMOD ↑(p^n)]) :
∥(z1 - z2 : ℚ_[p])∥ ≤ ↑(↑p ^ (-n : ℤ) : ℚ) :=
have hdvd : ↑(p^n) ∣ z2 - z1, from int.modeq.modeq_iff_dvd.1 hz,
have (↑(z2 - z1) : ℚ_[p]) = padic.of_rat p ↑(z2 - z1), by simp,
begin
rw [norm_sub_rev, ←int.cast_sub, this, padic_norm_e.eq_padic_norm],
simpa using padic_norm.le_of_dvd p hdvd
end
end padic_norm_z
|
1dc292f4858356684ce9e6e96a8ac8f8976ede40 | 43390109ab88557e6090f3245c47479c123ee500 | /src/inner_product_spaces/subfield.lean | b3cf78edfedbd7ad02ab87c94a3f6a5d5f5e4499 | [
"Apache-2.0"
] | permissive | Ja1941/xena-UROP-2018 | 41f0956519f94d56b8bf6834a8d39473f4923200 | b111fb87f343cf79eca3b886f99ee15c1dd9884b | refs/heads/master | 1,662,355,955,139 | 1,590,577,325,000 | 1,590,577,325,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,872 | lean | import group_theory.subgroup for_mathlib.subring
variables {F : Type*}
class is_subfield [field F] (s : set F) extends is_subring s :=
(inv_mem : ∀ {x : F}, x ∈ s → x⁻¹ ∈ s)
open is_subfield is_submonoid is_add_submonoid
instance subtype.field [field F] (s : set F) [is_subfield s] : field s :=
{
add := λ (a b : s), ⟨a.val + b.val, add_mem a.property b.property⟩,
add_assoc := assume ⟨a, _⟩ ⟨b, _⟩ ⟨c, _⟩, subtype.eq (add_assoc a b c),
zero := ⟨0, zero_mem s⟩,
zero_add := assume ⟨a, _⟩, subtype.eq (zero_add a),
add_zero := assume ⟨a, _⟩, subtype.eq (add_zero a),
neg := λ (a : s), ⟨ -a.val, is_add_subgroup.neg_mem a.property⟩ ,
add_left_neg := assume ⟨a, _⟩, subtype.eq (add_left_neg a),
add_comm := assume ⟨a, _⟩ ⟨b, _⟩, subtype.eq (add_comm a b),
mul := λ (a b : s), ⟨a.val * b.val, mul_mem a.property b.property⟩,
mul_assoc := assume ⟨a, _⟩ ⟨b, _⟩ ⟨c, _⟩, subtype.eq (mul_assoc a b c),
one := ⟨1, one_mem s⟩,
one_mul := assume ⟨a, _⟩, subtype.eq (one_mul a),
mul_one := assume ⟨a, _⟩, subtype.eq (mul_one a),
left_distrib := assume ⟨a, _⟩ ⟨b, _⟩ ⟨c, _⟩, subtype.eq (left_distrib a b c),
right_distrib := assume ⟨a, _⟩ ⟨b, _⟩ ⟨c, _⟩, subtype.eq (right_distrib a b c),
inv := λ (a : s), ⟨a.val⁻¹, inv_mem a.property⟩,
zero_ne_one := begin apply (iff_false_left zero_ne_one).mp, simp, exact F, apply_instance, end,
mul_inv_cancel := assume ⟨a, _⟩, λ h, subtype.eq (mul_inv_cancel ((iff_false_left (not_not_intro h)).mp (begin dunfold ne, rw auto.not_not_eq, apply subtype.ext, end))),
inv_mul_cancel := assume ⟨a, _⟩, λ h, subtype.eq (inv_mul_cancel ((iff_false_left (not_not_intro h)).mp (begin dunfold ne, rw auto.not_not_eq, apply subtype.ext, end))),
mul_comm := assume ⟨a, _⟩ ⟨b, _⟩, subtype.eq (mul_comm a b),
}
|
ce6e93d68c32df70c4d562aa945b93c264084c01 | a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940 | /stage0/src/Lean/Meta/Tactic/Assumption.lean | cb331dd47ed39b1efa1c06c208ec6278494b401e | [
"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,041 | 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.Meta.ExprDefEq
import Lean.Meta.Tactic.Util
namespace Lean.Meta
/-- Return a local declaration whose type is definitionally equal to `type`. -/
def findLocalDeclWithType? (type : Expr) : MetaM (Option FVarId) := do
(← getLCtx).findDeclRevM? fun localDecl => do
if localDecl.isAuxDecl then
return none
else if (← isDefEq type localDecl.type) then
return some localDecl.fvarId
else
return none
def assumptionCore (mvarId : MVarId) : MetaM Bool :=
withMVarContext mvarId do
checkNotAssigned mvarId `assumption
match (← findLocalDeclWithType? (← getMVarType mvarId)) with
| none => return false
| some fvarId => assignExprMVar mvarId (mkFVar fvarId); return true
def assumption (mvarId : MVarId) : MetaM Unit :=
unless (← assumptionCore mvarId) do
throwTacticEx `assumption mvarId ""
end Lean.Meta
|
c647228d1e8e7c65cf71f4e9e16f3feb9495a7ee | 302c785c90d40ad3d6be43d33bc6a558354cc2cf | /src/data/multiset/basic.lean | 1f9216bc290dd90c72df3312b3188b23bde2005a | [
"Apache-2.0"
] | permissive | ilitzroth/mathlib | ea647e67f1fdfd19a0f7bdc5504e8acec6180011 | 5254ef14e3465f6504306132fe3ba9cec9ffff16 | refs/heads/master | 1,680,086,661,182 | 1,617,715,647,000 | 1,617,715,647,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 93,237 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import data.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 : 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⟩
lemma induction_on' {p : multiset α → Prop} (S : multiset α)
(h₁ : p ∅) (h₂ : ∀ {a s}, a ∈ S → s ⊆ S → p s → p (insert a s)) : p S :=
@multiset.induction_on α (λ T, T ⊆ S → p T) S (λ _, h₁) (λ a s hps hs,
let ⟨hS, sS⟩ := cons_subset.1 hs in h₂ hS sS (hps sS)) (subset.refl S)
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_nsmul (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
lemma foldr_induction' (f : α → β → β) (H : left_commutative f) (x : β) (q : α → Prop)
(p : β → Prop) (s : multiset α) (hpqf : ∀ a b, q a → p b → p (f a b)) (px : p x)
(q_s : ∀ a ∈ s, q a) :
p (foldr f H x s) :=
begin
revert s,
refine multiset.induction (by simp [px]) _,
intros a s hs hsa,
rw foldr_cons,
have hps : ∀ (x : α), x ∈ s → q x, from λ x hxs, hsa x (mem_cons_of_mem hxs),
exact hpqf a (foldr f H x s) (hsa a (mem_cons_self a s)) (hs hps),
end
lemma foldr_induction (f : α → α → α) (H : left_commutative f) (x : α) (p : α → Prop)
(s : multiset α) (p_f : ∀ a b, p a → p b → p (f a b)) (px : p x) (p_s : ∀ a ∈ s, p a) :
p (foldr f H x s) :=
foldr_induction' f H x p p s p_f px p_s
lemma foldl_induction' (f : β → α → β) (H : right_commutative f) (x : β) (q : α → Prop)
(p : β → Prop) (s : multiset α) (hpqf : ∀ a b, q a → p b → p (f b a)) (px : p x)
(q_s : ∀ a ∈ s, q a) :
p (foldl f H x s) :=
begin
rw foldl_swap,
exact foldr_induction' (λ x y, f y x) (λ x y z, (H _ _ _).symm) x q p s hpqf px q_s,
end
lemma foldl_induction (f : α → α → α) (H : right_commutative f) (x : α) (p : α → Prop)
(s : multiset α) (p_f : ∀ a b, p a → p b → p (f b a)) (px : p x) (p_s : ∀ a ∈ s, p a) :
p (foldl f H x s) :=
foldl_induction' f H x p p s p_f px p_s
/-- 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_nsmul {α : 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_nsmul 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])
lemma prod_eq_zero {M₀ : Type*} [comm_monoid_with_zero M₀] {s : multiset M₀} (h : (0 : M₀) ∈ s) :
multiset.prod s = 0 :=
begin
rcases multiset.exists_cons_of_mem h with ⟨s', hs'⟩,
simp [hs', multiset.prod_cons]
end
lemma prod_eq_zero_iff {M₀ : Type*} [comm_monoid_with_zero M₀] [no_zero_divisors M₀] [nontrivial M₀]
{s : multiset M₀} :
multiset.prod s = 0 ↔ (0 : M₀) ∈ s :=
by { rcases s with ⟨l⟩, simp }
theorem prod_ne_zero {M₀ : Type*} [comm_monoid_with_zero M₀] [no_zero_divisors M₀] [nontrivial M₀]
{m : multiset M₀} (h : (0 : M₀) ∉ m) : m.prod ≠ 0 :=
mt prod_eq_zero_iff.1 h
@[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
@[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
@[to_additive]
lemma prod_induction {M : Type*} [comm_monoid M] (p : M → Prop) (s : multiset M)
(p_mul : ∀ a b, p a → p b → p (a * b)) (p_one : p 1) (p_s : ∀ a ∈ s, p a) :
p s.prod :=
begin
rw prod_eq_foldr,
exact foldr_induction (*) (λ x y z, by simp [mul_left_comm]) 1 p s p_mul p_one p_s,
end
@[to_additive le_sum_of_subadditive_on_pred]
lemma le_prod_of_submultiplicative_on_pred [comm_monoid α] [ordered_comm_monoid β]
(f : α → β) (p : α → Prop) (h_one : f 1 = 1) (hp_one : p 1)
(h_mul : ∀ a b, p a → p b → f (a * b) ≤ f a * f b)
(hp_mul : ∀ a b, p a → p b → p (a * b)) (s : multiset α) (hps : ∀ a, a ∈ s → p a) :
f s.prod ≤ (s.map f).prod :=
begin
revert s,
refine multiset.induction _ _,
{ simp [le_of_eq h_one], },
intros a s hs hpsa,
have hps : ∀ x, x ∈ s → p x, from λ x hx, hpsa x (mem_cons_of_mem hx),
have hp_prod : p s.prod, from prod_induction p s hp_mul hp_one hps,
rw [prod_cons, map_cons, prod_cons],
exact (h_mul a s.prod (hpsa a (mem_cons_self a s)) hp_prod).trans (mul_le_mul_left' (hs hps) _),
end
@[to_additive le_sum_of_subadditive]
lemma le_prod_of_submultiplicative [comm_monoid α] [ordered_comm_monoid β]
(f : α → β) (h_one : f 1 = 1) (h_mul : ∀ a b, f (a * b) ≤ f a * f b) (s : multiset α) :
f s.prod ≤ (s.map f).prod :=
le_prod_of_submultiplicative_on_pred f (λ i, true) h_one trivial (λ x y _ _ , h_mul x y) (by simp)
s (by simp)
@[to_additive]
lemma prod_induction_nonempty {M : Type*} [comm_monoid M] (p : M → Prop)
(p_mul : ∀ a b, p a → p b → p (a * b)) {s : multiset M} (hs_nonempty : s ≠ ∅)
(p_s : ∀ a ∈ s, p a) :
p s.prod :=
begin
revert s,
refine multiset.induction _ _,
{ intro h,
exfalso,
simpa using h, },
intros a s hs hsa hpsa,
rw prod_cons,
by_cases hs_empty : s = ∅,
{ simp [hs_empty, hpsa a], },
have hps : ∀ (x : M), x ∈ s → p x, from λ x hxs, hpsa x (mem_cons_of_mem hxs),
exact p_mul a s.prod (hpsa a (mem_cons_self a s)) (hs hs_empty hps),
end
@[to_additive le_sum_nonempty_of_subadditive_on_pred]
lemma le_prod_nonempty_of_submultiplicative_on_pred [comm_monoid α] [ordered_comm_monoid β]
(f : α → β) (p : α → Prop) (h_mul : ∀ a b, p a → p b → f (a * b) ≤ f a * f b)
(hp_mul : ∀ a b, p a → p b → p (a * b)) (s : multiset α) (hs_nonempty : s ≠ ∅)
(hs : ∀ a, a ∈ s → p a) :
f s.prod ≤ (s.map f).prod :=
begin
revert s,
refine multiset.induction _ _,
{ intro h,
exfalso,
exact h rfl, },
rintros a s hs hsa_nonempty hsa_prop,
rw [prod_cons, map_cons, prod_cons],
by_cases hs_empty : s = ∅,
{ simp [hs_empty], },
have hsa_restrict : (∀ x, x ∈ s → p x), from λ x hx, hsa_prop x (mem_cons_of_mem hx),
have hp_sup : p s.prod,
from prod_induction_nonempty p hp_mul hs_empty hsa_restrict,
have hp_a : p a, from hsa_prop a (mem_cons_self a s),
exact (h_mul a _ hp_a hp_sup).trans (mul_le_mul_left' (hs hs_empty hsa_restrict) _),
end
@[to_additive le_sum_nonempty_of_subadditive]
lemma le_prod_nonempty_of_submultiplicative [comm_monoid α] [ordered_comm_monoid β]
(f : α → β) (h_mul : ∀ a b, f (a * b) ≤ f a * f b) (s : multiset α) (hs_nonempty : s ≠ ∅) :
f s.prod ≤ (s.map f).prod :=
le_prod_nonempty_of_submultiplicative_on_pred f (λ i, true) (by simp [h_mul]) (by simp) s
hs_nonempty (by simp)
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]
theorem map_filter (f : β → α) (s : multiset β) :
filter p (map f s) = map f (filter (p ∘ f) s) :=
quot.induction_on s (λ l, by simp [map_filter])
/-! ### 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_nsmul (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 {r p : α → β → Prop} {s t} (hst : rel r s t) (h : ∀(a ∈ s) (b ∈ t), r a b → p a b) :
rel p s t :=
begin
induction hst,
case rel.zero { exact rel.zero },
case rel.cons : a b s t hab hst ih {
apply rel.cons (h a (mem_cons_self _ _) b (mem_cons_self _ _) hab),
exact ih (λ a' ha' b' hb' h', h a' (mem_cons_of_mem ha') b' (mem_cons_of_mem hb') h') }
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 {s : multiset α} {t : multiset β} {f : α → γ} {g : β → δ} :
rel p (s.map f) (t.map g) ↔ rel (λa b, p (f a) (g b)) s t :=
rel_map_left.trans rel_map_right
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, rw rel_map, exact hst.mono (λ a ha b hb hr, h hr) }
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], simp only [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 }
variable {α}
@[simp]
lemma coe_subsingleton_equiv [subsingleton α] :
(subsingleton_equiv α : list α → multiset α) = coe :=
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
|
f831efc4541c33bc81bc453f5136e6c98b14171b | 271e26e338b0c14544a889c31c30b39c989f2e0f | /tests/lean/mvar2.lean | 77a6bdbd1be14d3ef70635b49a525cdafe5612cd | [
"Apache-2.0"
] | permissive | dgorokho/lean4 | 805f99b0b60c545b64ac34ab8237a8504f89d7d4 | e949a052bad59b1c7b54a82d24d516a656487d8a | refs/heads/master | 1,607,061,363,851 | 1,578,006,086,000 | 1,578,006,086,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,420 | lean | import Init.Lean.MetavarContext
open Lean
def check (b : Bool) : IO Unit :=
unless b (throw "error")
def f := mkConst `f []
def g := mkConst `g []
def a := mkConst `a []
def b := mkConst `b []
def c := mkConst `c []
def b0 := mkBVar 0
def b1 := mkBVar 1
def b2 := mkBVar 2
def u := mkLevelParam `u
def typeE := mkSort levelOne
def natE := mkConst `Nat []
def boolE := mkConst `Bool []
def vecE := mkConst `Vec [levelZero]
def α := mkFVar `α
def x := mkFVar `x
def y := mkFVar `y
def z := mkFVar `z
def w := mkFVar `w
def m1 := mkMVar `m1
def m2 := mkMVar `m2
def m3 := mkMVar `m3
def bi := BinderInfo.default
def arrow (d b : Expr) := mkForall `_ bi d b
def lctx1 : LocalContext := {}
def lctx2 := lctx1.mkLocalDecl `α `α typeE
def lctx3 := lctx2.mkLocalDecl `x `x m1
def lctx4 := lctx3.mkLocalDecl `y `y (arrow natE (mkAppN m3 #[α, x]))
def mctx1 : MetavarContext := {}
def mctx2 := mctx1.addExprMVarDecl `m1 `m1 lctx1 #[] typeE
def mctx3 := mctx2.addExprMVarDecl `m2 `m2 lctx3 #[] natE
def mctx4 := mctx3.addExprMVarDecl `m3 `m3 lctx1 #[] (arrow typeE (arrow natE natE))
def mctx5 := mctx4.assignDelayed `m3 lctx3 #[α, x] m2
def mctx6 := mctx5.assignExpr `m2 (arrow α α)
def mctx7 := mctx6.assignExpr `m1 natE
def t2 := lctx4.mkLambda #[α, x, y] $ mkAppN f #[mkAppN m3 #[α, x], x]
#eval check (!t2.hasFVar)
#eval t2
#eval (mctx6.instantiateMVars t2).1
#eval (mctx7.instantiateMVars t2).1
|
94740c5cfcb31fd6845fbec1da83c0922a7bb9b0 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/category_theory/category/preorder.lean | 49aa0ce90c95bf3d468474e572c6ab344250dabd | [
"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 | 5,396 | lean | /-
Copyright (c) 2017 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Stephen Morgan, Scott Morrison, Johannes Hölzl, Reid Barton
-/
import category_theory.adjunction.basic
import order.galois_connection
/-!
# Preorders as categories
We install a category instance on any preorder. This is not to be confused with the category _of_
preorders, defined in `order/category/Preorder`.
We show that monotone functions between preorders correspond to functors of the associated
categories. Furthermore, galois connections correspond to adjoint functors.
## Main definitions
* `hom_of_le` and `le_of_hom` provide translations between inequalities in the preorder, and
morphisms in the associated category.
* `monotone.functor` is the functor associated to a monotone function.
* `galois_connection.adjunction` is the adjunction associated to a galois connection.
* `Preorder_to_Cat` is the functor embedding the category of preorders into `Cat`.
-/
universes u v
namespace preorder
open category_theory
/--
The category structure coming from a preorder. There is a morphism `X ⟶ Y` if and only if `X ≤ Y`.
Because we don't allow morphisms to live in `Prop`,
we have to define `X ⟶ Y` as `ulift (plift (X ≤ Y))`.
See `category_theory.hom_of_le` and `category_theory.le_of_hom`.
See <https://stacks.math.columbia.edu/tag/00D3>.
-/
@[priority 100] -- see Note [lower instance priority]
instance small_category (α : Type u) [preorder α] : small_category α :=
{ hom := λ U V, ulift (plift (U ≤ V)),
id := λ X, ⟨ ⟨ le_refl X ⟩ ⟩,
comp := λ X Y Z f g, ⟨ ⟨ le_trans _ _ _ f.down.down g.down.down ⟩ ⟩ }
end preorder
namespace category_theory
open opposite
variables {X : Type u} [preorder X]
/--
Express an inequality as a morphism in the corresponding preorder category.
-/
def hom_of_le {x y : X} (h : x ≤ y) : x ⟶ y := ulift.up (plift.up h)
alias hom_of_le ← _root_.has_le.le.hom
@[simp] lemma hom_of_le_refl {x : X} : (le_refl x).hom = 𝟙 x := rfl
@[simp] lemma hom_of_le_comp {x y z : X} (h : x ≤ y) (k : y ≤ z) :
h.hom ≫ k.hom = (h.trans k).hom := rfl
/--
Extract the underlying inequality from a morphism in a preorder category.
-/
lemma le_of_hom {x y : X} (h : x ⟶ y) : x ≤ y := h.down.down
alias le_of_hom ← _root_.quiver.hom.le
@[simp] lemma le_of_hom_hom_of_le {x y : X} (h : x ≤ y) : h.hom.le = h := rfl
@[simp] lemma hom_of_le_le_of_hom {x y : X} (h : x ⟶ y) : h.le.hom = h :=
by { cases h, cases h, refl, }
/-- Construct a morphism in the opposite of a preorder category from an inequality. -/
def op_hom_of_le {x y : Xᵒᵖ} (h : unop x ≤ unop y) : y ⟶ x := h.hom.op
lemma le_of_op_hom {x y : Xᵒᵖ} (h : x ⟶ y) : unop y ≤ unop x := h.unop.le
instance unique_to_top [order_top X] {x : X} : unique (x ⟶ ⊤) := by tidy
instance unique_from_bot [order_bot X] {x : X} : unique (⊥ ⟶ x) := by tidy
end category_theory
section
variables {X : Type u} {Y : Type v} [preorder X] [preorder Y]
/--
A monotone function between preorders induces a functor between the associated categories.
-/
def monotone.functor {f : X → Y} (h : monotone f) : X ⥤ Y :=
{ obj := f,
map := λ x₁ x₂ g, (h g.le).hom }
@[simp] lemma monotone.functor_obj {f : X → Y} (h : monotone f) : h.functor.obj = f := rfl
/--
A galois connection between preorders induces an adjunction between the associated categories.
-/
def galois_connection.adjunction {l : X → Y} {u : Y → X} (gc : galois_connection l u) :
gc.monotone_l.functor ⊣ gc.monotone_u.functor :=
category_theory.adjunction.mk_of_hom_equiv
{ hom_equiv := λ X Y, ⟨λ f, (gc.le_u f.le).hom, λ f, (gc.l_le f.le).hom, by tidy, by tidy⟩ }
end
namespace category_theory
section preorder
variables {X : Type u} {Y : Type v} [preorder X] [preorder Y]
/--
A functor between preorder categories is monotone.
-/
@[mono] lemma functor.monotone (f : X ⥤ Y) : monotone f.obj :=
λ x y hxy, (f.map hxy.hom).le
/--
An adjunction between preorder categories induces a galois connection.
-/
lemma adjunction.gc {L : X ⥤ Y} {R : Y ⥤ X} (adj : L ⊣ R) :
galois_connection L.obj R.obj :=
λ x y, ⟨λ h, ((adj.hom_equiv x y).to_fun h.hom).le, λ h, ((adj.hom_equiv x y).inv_fun h.hom).le⟩
end preorder
section partial_order
variables {X : Type u} {Y : Type v} [partial_order X] [partial_order Y]
lemma iso.to_eq {x y : X} (f : x ≅ y) : x = y := le_antisymm f.hom.le f.inv.le
/--
A categorical equivalence between partial orders is just an order isomorphism.
-/
def equivalence.to_order_iso (e : X ≌ Y) : X ≃o Y :=
{ to_fun := e.functor.obj,
inv_fun := e.inverse.obj,
left_inv := λ a, (e.unit_iso.app a).to_eq.symm,
right_inv := λ b, (e.counit_iso.app b).to_eq,
map_rel_iff' := λ a a',
⟨λ h, ((equivalence.unit e).app a ≫ e.inverse.map h.hom ≫ (equivalence.unit_inv e).app a').le,
λ (h : a ≤ a'), (e.functor.map h.hom).le⟩, }
-- `@[simps]` on `equivalence.to_order_iso` produces lemmas that fail the `simp_nf` linter,
-- so we provide them by hand:
@[simp]
lemma equivalence.to_order_iso_apply (e : X ≌ Y) (x : X) :
e.to_order_iso x = e.functor.obj x := rfl
@[simp]
lemma equivalence.to_order_iso_symm_apply (e : X ≌ Y) (y : Y) :
e.to_order_iso.symm y = e.inverse.obj y := rfl
end partial_order
end category_theory
|
988dfd44247e80c3f72c39eb04a4cfdf1725c6f0 | 90edd5cdcf93124fe15627f7304069fdce3442dd | /tests/lean/run/aesop_mathlib4.lean | c0030ed4f63767a0ba9fe11643fc1afa48f3adc5 | [
"Apache-2.0"
] | permissive | JLimperg/lean4-aesop | 8a9d9cd3ee484a8e67fda2dd9822d76708098712 | 5c4b9a3e05c32f69a4357c3047c274f4b94f9c71 | refs/heads/master | 1,689,415,944,104 | 1,627,383,284,000 | 1,627,383,284,000 | 377,536,770 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 15,980 | lean | import Lean.Aesop
theorem EqIffBeqTrue [DecidableEq α] {a b : α} : a = b ↔ ((a == b) = true) :=
⟨decideEqTrue, ofDecideEqTrue⟩
theorem NeqIffBeqFalse [DecidableEq α] {a b : α} : a ≠ b ↔ ((a == b) = false) :=
⟨decideEqFalse, ofDecideEqFalse⟩
theorem decide_eq_true_iff (p : Prop) [Decidable p] : (decide p = true) ↔ p :=
⟨ofDecideEqTrue, decideEqTrue⟩
theorem decide_eq_false_iff_not (p : Prop) [Decidable p] : (decide p = false) ↔ ¬ p :=
⟨ofDecideEqFalse, decideEqFalse⟩
theorem optParam_eq (α : Sort u) (default : α) : optParam α default = α := rfl
def not_false := notFalse
def proof_irrel := @proofIrrel
def congr_fun := @congrFun
def congr_arg := @congrArg
def of_eq_true := @ofEqTrue
-- TODO subst builder
theorem not_of_eq_false {p : Prop} (h : p = False) : ¬p := fun hp => h ▸ hp
-- TODO reflexivity default tactic
-- TODO How to use a lemma like this? Imo this is a nice example of e-matching.
theorem cast_proof_irrel (h₁ h₂ : α = β) (a : α) : cast h₁ a = cast h₂ a := rfl
def cast_eq := @castEq
-- TODO make this a norm lemma?
theorem Ne.def (a b : α) : (a ≠ b) = ¬ (a = b) := rfl
def false_of_ne := @falseOfNe
def ne_false_of_self := @neFalseOfSelf
def ne_true_of_not := @neTrueOfNot
def true_ne_false := trueNeFalse
def eq_of_heq := @eqOfHEq
def heq_of_eq := @heqOfEq
def heq_of_heq_of_eq := @heqOfHEqOfEq
def heq_of_eq_of_heq := @heqOfEqOfHEq
def type_eq_of_heq := @typeEqOfHEq
def eq_rec_heq := @eqRecHEq
-- TODO heq refl default tactic
theorem heq_of_eq_rec_left {φ : α → Sort v} {a a' : α} {p₁ : φ a} {p₂ : φ a'} :
(e : a = a') → (h₂ : Eq.rec (motive := fun a _ => φ a) p₁ e = p₂) → p₁ ≅ p₂
| rfl, rfl => HEq.rfl
theorem heq_of_eq_rec_right {φ : α → Sort v} {a a' : α} {p₁ : φ a} {p₂ : φ a'} :
(e : a' = a) → (h₂ : p₁ = Eq.rec (motive := fun a _ => φ a) p₂ e) → p₁ ≅ p₂
| rfl, rfl => HEq.rfl
theorem of_heq_true (h : a ≅ True) : a := of_eq_true (eq_of_heq h)
def cast_heq := @castHEq
-- TODO use applicable hyps by default
def And.elim (f : a → b → α) (h : a ∧ b) : α := by aesop (safe [f])
theorem And.symm : a ∧ b → b ∧ a := by aesop
-- TODO automatic cases on or in hyp (needs per-hyp rules)
-- TODO cases builder
theorem Or.elim {a b c : Prop} (h₁ : a → c) (h₂ : b → c) (h : a ∨ b) : c := by
cases h <;> aesop
-- TODO make normalisation a fixpoint loop?
-- TODO deal with negation
-- TODO use hyps in the context by default
theorem not_not_em (a : Prop) : ¬¬(a ∨ ¬a) := by
show ((a ∨ (a → False)) → False) → False
exact fun H => H (Or.inr fun h => H (Or.inl h))
theorem Or.symm (h : a ∨ b) : b ∨ a := by
cases h <;> aesop
-- TODO use iff in the context as norm rule?
-- TODO allow local hyps to be added as norm simp rules
def Iff.elim (f : (a → b) → (b → a) → c) (h : a ↔ b) : c := by
admit
-- aesop (norm [h (builder simp)])
-- TODO add Iff.intro as default rule
theorem iff_comm : (a ↔ b) ↔ (b ↔ a) := by
aesop (safe [Iff.intro])
theorem iff_iff_implies_and_implies : (a ↔ b) ↔ (a → b) ∧ (b → a) :=
⟨fun ⟨ha, hb⟩ => ⟨ha, hb⟩, fun ⟨ha, hb⟩ => ⟨ha, hb⟩⟩
-- TODO don't do contextual simp for all hyps by default (so this should fail)
theorem Eq.to_iff : a = b → (a ↔ b) := by
aesop
theorem neq_of_not_iff : ¬(a ↔ b) → a ≠ b := mt Eq.to_iff
theorem of_iff_true (h : a ↔ True) : a := by aesop
theorem not_of_iff_false : (a ↔ False) → ¬a := Iff.mp
theorem not_not_intro : a → ¬¬a := fun a h => h a
theorem iff_true_intro (h : a) : a ↔ True := by aesop
theorem iff_false_intro (h : ¬a) : a ↔ False := by aesop
theorem not_iff_false_intro (h : a) : ¬a ↔ False := by aesop
theorem not_not_not : ¬¬¬a ↔ ¬a := ⟨mt not_not_intro, not_not_intro⟩
theorem imp_congr_left (h : a ↔ b) : (a → c) ↔ (b → c) := by aesop
-- TODO Iff elim
theorem imp_congr_right (h : a → (b ↔ c)) : (a → b) ↔ (a → c) :=
⟨fun hab ha => (h ha).1 (hab ha), fun hcd ha => (h ha).2 (hcd ha)⟩
theorem imp_congr_ctx (h₁ : a ↔ c) (h₂ : c → (b ↔ d)) : (a → b) ↔ (c → d) :=
(imp_congr_left h₁).trans (imp_congr_right h₂)
theorem imp_congr (h₁ : a ↔ c) (h₂ : b ↔ d) : (a → b) ↔ (c → d) := by
aesop (safe [imp_congr_ctx])
-- imp_congr_ctx h₁ fun _ => h₂
theorem Not.intro {a : Prop} (h : a → False) : ¬a := by aesop
-- TODO try False-elim with low priority if we have a hyp X → False in the
-- context.
def Not.elim (h : ¬a) (ha : a) : α := by aesop
theorem not_true : ¬True ↔ False := by aesop
theorem not_false_iff : ¬False ↔ True := by aesop
theorem not_congr (h : a ↔ b) : ¬a ↔ ¬b := by aesop
theorem ne_self_iff_false (a : α) : a ≠ a ↔ False := by aesop
theorem eq_self_iff_true (a : α) : a = a ↔ True := by aesop
theorem heq_self_iff_true (a : α) : a ≅ a ↔ True := iff_true_intro HEq.rfl
theorem iff_not_self : ¬(a ↔ ¬a) | H => let f h := H.1 h h; f (H.2 f)
theorem not_iff_self : ¬(¬a ↔ a) | H => iff_not_self H.symm
theorem eq_comm {a b : α} : a = b ↔ b = a := ⟨Eq.symm, Eq.symm⟩
theorem And.imp (f : a → c) (g : b → d) (h : a ∧ b) : c ∧ d := ⟨f h.1, g h.2⟩
theorem and_congr (h₁ : a ↔ c) (h₂ : b ↔ d) : a ∧ b ↔ c ∧ d := ⟨And.imp h₁.1 h₂.1, And.imp h₁.2 h₂.2⟩
theorem and_congr_right (h : a → (b ↔ c)) : (a ∧ b) ↔ (a ∧ c) :=
⟨fun ⟨ha, hb⟩ => ⟨ha, (h ha).1 hb⟩, fun ⟨ha, hb⟩ => ⟨ha, (h ha).2 hb⟩⟩
theorem and_comm : a ∧ b ↔ b ∧ a := ⟨And.symm, And.symm⟩
theorem and_assoc : (a ∧ b) ∧ c ↔ a ∧ (b ∧ c) :=
⟨fun ⟨⟨ha, hb⟩, hc⟩ => ⟨ha, hb, hc⟩, fun ⟨ha, hb, hc⟩ => ⟨⟨ha, hb⟩, hc⟩⟩
theorem and_left_comm : a ∧ (b ∧ c) ↔ b ∧ (a ∧ c) := by
rw [← and_assoc, ← and_assoc, @and_comm a b]
exact Iff.rfl
theorem and_iff_left (hb : b) : a ∧ b ↔ a := ⟨And.left, fun ha => ⟨ha, hb⟩⟩
theorem and_iff_right (ha : a) : a ∧ b ↔ b := ⟨And.right, fun hb => ⟨ha, hb⟩⟩
theorem and_true : a ∧ True ↔ a := and_iff_left ⟨⟩
theorem true_and : True ∧ a ↔ a := and_iff_right ⟨⟩
theorem and_false : a ∧ False ↔ False := iff_false_intro And.right
theorem false_and : False ∧ a ↔ False := iff_false_intro And.left
theorem and_not_self : ¬(a ∧ ¬a) | ⟨ha, hn⟩ => hn ha
theorem not_and_self : ¬(¬a ∧ a) | ⟨hn, ha⟩ => hn ha
theorem and_self : a ∧ a ↔ a := ⟨And.left, fun h => ⟨h, h⟩⟩
theorem Or.imp (f : a → c) (g : b → d) (h : a ∨ b) : c ∨ d := h.elim (inl ∘ f) (inr ∘ g)
theorem Or.imp_left (f : a → b) : a ∨ c → b ∨ c := Or.imp f id
theorem Or.imp_right (f : b → c) : a ∨ b → a ∨ c := Or.imp id f
theorem or_congr (h₁ : a ↔ c) (h₂ : b ↔ d) : (a ∨ b) ↔ (c ∨ d) :=
⟨Or.imp h₁.1 h₂.1, Or.imp h₁.2 h₂.2⟩
theorem or_comm : a ∨ b ↔ b ∨ a := ⟨Or.symm, Or.symm⟩
theorem Or.resolve_left (h : a ∨ b) (na : ¬a) : b := h.elim na.elim id
theorem Or.neg_resolve_left (h : ¬a ∨ b) (ha : a) : b := h.elim (absurd ha) id
theorem Or.resolve_right (h : a ∨ b) (nb : ¬b) : a := h.elim id nb.elim
theorem Or.neg_resolve_right (h : a ∨ ¬b) (nb : b) : a := h.elim id (absurd nb)
open Or in
theorem or_assoc {a b c} : (a ∨ b) ∨ c ↔ a ∨ (b ∨ c) :=
⟨fun | inl (inl h) => inl h
| inl (inr h) => inr (inl h)
| inr h => inr (inr h),
fun | inl h => inl (inl h)
| inr (inl h) => inl (inr h)
| inr (inr h) => inr h⟩
theorem or_left_comm : a ∨ (b ∨ c) ↔ b ∨ (a ∨ c) := by
rw [← or_assoc, ← or_assoc, @or_comm a b]
exact Iff.rfl
theorem or_true : a ∨ True ↔ True := iff_true_intro (Or.inr ⟨⟩)
theorem true_or : True ∨ a ↔ True := iff_true_intro (Or.inl ⟨⟩)
theorem or_false : a ∨ False ↔ a := ⟨fun h => h.resolve_right id, Or.inl⟩
theorem false_or : False ∨ a ↔ a := ⟨fun h => h.resolve_left id, Or.inr⟩
theorem or_self : a ∨ a ↔ a := ⟨fun h => h.elim id id, Or.inl⟩
theorem not_or_intro : (na : ¬a) → (nb : ¬b) → ¬(a ∨ b) := Or.elim
theorem not_or (p q) : ¬ (p ∨ q) ↔ ¬ p ∧ ¬ q :=
⟨fun H => ⟨mt Or.inl H, mt Or.inr H⟩, fun ⟨hp, hq⟩ pq => pq.elim hp hq⟩
@[simp] theorem iff_true : (a ↔ True) ↔ a := ⟨fun h => h.2 ⟨⟩, iff_true_intro⟩
@[simp] theorem true_iff : (True ↔ a) ↔ a := iff_comm.trans iff_true
@[simp] theorem iff_false : (a ↔ False) ↔ ¬a := ⟨Iff.mp, iff_false_intro⟩
@[simp] theorem false_iff : (False ↔ a) ↔ ¬a := iff_comm.trans iff_false
@[simp] theorem iff_self : (a ↔ a) ↔ True := iff_true_intro Iff.rfl
theorem iff_congr (h₁ : a ↔ c) (h₂ : b ↔ d) : (a ↔ b) ↔ (c ↔ d) :=
⟨fun h => h₁.symm.trans $ h.trans h₂, fun h => h₁.trans $ h.trans h₂.symm⟩
@[simp] theorem imp_true_iff : (α → True) ↔ True := iff_true_intro fun _ => ⟨⟩
@[simp] theorem false_imp_iff : (False → a) ↔ True := iff_true_intro False.elim
def ExistsUnique (p : α → Prop) := ∃ x, p x ∧ ∀ y, p y → y = x
open Lean in
macro "∃! " xs:explicitBinders ", " b:term : term => expandExplicitBinders ``ExistsUnique xs b
theorem ExistsUnique.intro {p : α → Prop} (w : α)
(h₁ : p w) (h₂ : ∀ y, p y → y = w) : ∃! x, p x := ⟨w, h₁, h₂⟩
theorem ExistsUnique.exists {p : α → Prop} : (∃! x, p x) → ∃ x, p x | ⟨x, h, _⟩ => ⟨x, h⟩
theorem ExistsUnique.unique {p : α → Prop} (h : ∃! x, p x)
{y₁ y₂ : α} (py₁ : p y₁) (py₂ : p y₂) : y₁ = y₂ :=
let ⟨x, hx, hy⟩ := h; (hy _ py₁).trans (hy _ py₂).symm
theorem forall_congr {p q : α → Prop} (h : ∀ a, p a ↔ q a) : (∀ a, p a) ↔ ∀ a, q a :=
⟨fun H a => (h a).1 (H a), fun H a => (h a).2 (H a)⟩
theorem Exists.imp {p q : α → Prop} (h : ∀ a, p a → q a) : (∃ a, p a) → ∃ a, q a
| ⟨a, ha⟩ => ⟨a, h a ha⟩
theorem exists_congr {p q : α → Prop} (h : ∀ a, p a ↔ q a) : (∃ a, p a) ↔ ∃ a, q a :=
⟨Exists.imp fun x => (h x).1, Exists.imp fun x => (h x).2⟩
theorem exists_unique_congr {p q : α → Prop} (h : ∀ a, p a ↔ q a) : (∃! a, p a) ↔ ∃! a, q a :=
exists_congr fun x => and_congr (h _) $ forall_congr fun y => imp_congr_left (h _)
theorem forall_not_of_not_exists {p : α → Prop} (hne : ¬∃ x, p x) (x) : ¬p x | hp => hne ⟨x, hp⟩
instance forall_prop_decidable {p} (P : p → Prop)
[Dp : Decidable p] [DP : ∀ h, Decidable (P h)] : Decidable (∀ h, P h) :=
if h : p
then decidableOfDecidableOfIff (DP h) ⟨λ h2 _ => h2, λ al => al h⟩
else isTrue (λ h2 => absurd h2 h)
@[simp] theorem forall_eq {p : α → Prop} {a' : α} : (∀a, a = a' → p a) ↔ p a' :=
⟨λ h => h a' rfl, λ h a e => e.symm ▸ h⟩
theorem forall_and_distrib {p q : α → Prop} : (∀ x, p x ∧ q x) ↔ (∀ x, p x) ∧ (∀ x, q x) :=
⟨λ h => ⟨λ x => (h x).left, λ x => (h x).right⟩, λ ⟨h₁, h₂⟩ x => ⟨h₁ x, h₂ x⟩⟩
def Decidable.by_cases := @byCases
def Decidable.by_contradiction := @byContradiction
def Decidable.of_not_not := @ofNotNot
theorem Decidable.not_and [Decidable p] [Decidable q] : ¬ (p ∧ q) ↔ ¬ p ∨ ¬ q := notAndIffOrNot _ _
@[inline] def Or.by_cases [Decidable p] (h : p ∨ q) (h₁ : p → α) (h₂ : q → α) : α :=
if hp : p then h₁ hp else h₂ (h.resolve_left hp)
@[inline] def Or.by_cases' [Decidable q] (h : p ∨ q) (h₁ : p → α) (h₂ : q → α) : α :=
if hq : q then h₂ hq else h₁ (h.resolve_right hq)
theorem Exists.nonempty {p : α → Prop} : (∃ x, p x) → Nonempty α | ⟨x, _⟩ => ⟨x⟩
@[simp] def if_pos := @ifPos
@[simp] def if_neg := @ifNeg
@[simp] def dif_pos := @difPos
@[simp] def dif_neg := @difNeg
theorem ite_id [h : Decidable c] {α} (t : α) : (if c then t else t) = t := by cases h <;> rfl
@[simp] theorem if_true {h : Decidable True} (t e : α) : (@ite α True h t e) = t :=
if_pos trivial
@[simp] theorem if_false {h : Decidable False} (t e : α) : (@ite α False h t e) = e :=
if_neg not_false
theorem dif_eq_if [h : Decidable c] {α} (t : α) (e : α) : (if h : c then t else e) = ite c t e :=
by cases h <;> rfl
/-- Universe lifting operation -/
structure ulift.{r, s} (α : Type s) : Type (max s r) :=
up :: (down : α)
namespace ulift
/- Bijection between α and ulift.{v} α -/
theorem up_down {α : Type u} : ∀ (b : ulift.{v} α), up (down b) = b
| up a => rfl
theorem down_up {α : Type u} (a : α) : down (up.{v} a) = a := rfl
end ulift
/-- Universe lifting operation from Sort to Type -/
structure plift (α : Sort u) : Type u :=
up :: (down : α)
namespace plift
/- Bijection between α and plift α -/
theorem up_down : ∀ (b : plift α), up (down b) = b
| (up a) => rfl
theorem down_up (a : α) : down (up a) = a := rfl
end plift
namespace WellFounded
variable {α : Sort u} {C : α → Sort v} {r : α → α → Prop}
unsafe def fix'.impl (hwf : WellFounded r) (F : ∀ x, (∀ y, r y x → C y) → C x) (x : α) : C x :=
F x fun y _ => impl hwf F y
set_option codegen false in
@[implementedBy fix'.impl]
def fix' (hwf : WellFounded r) (F : ∀ x, (∀ y, r y x → C y) → C x) (x : α) : C x := hwf.fix F x
end WellFounded
-- Below are items ported from mathlib/src/logic/basic.lean
theorem iff_of_eq (e : a = b) : a ↔ b := e ▸ Iff.rfl
def decidable_of_iff (a : Prop) (h : a ↔ b) [D : Decidable a] : Decidable b :=
decidableOfDecidableOfIff D h
/-
Stuff from mathlib's logic/basic.lean.
TODO: import the whole thing.
-/
theorem or_imp_distrib : (a ∨ b → c) ↔ (a → c) ∧ (b → c) :=
⟨fun h => ⟨fun ha => h (Or.inl ha), fun hb => h (Or.inr hb)⟩,
fun ⟨ha, hb⟩ => Or.rec ha hb⟩
@[simp] theorem and_imp : (a ∧ b → c) ↔ (a → b → c) :=
Iff.intro (λ h ha hb => h ⟨ha, hb⟩) (λ h ⟨ha, hb⟩ => h ha hb)
@[simp] theorem not_and : ¬ (a ∧ b) ↔ (a → ¬ b) := and_imp
@[simp] theorem exists_imp_distrib {p : α → Prop} : ((∃ x, p x) → b) ↔ ∀ x, p x → b :=
⟨λ h x hpx => h ⟨x, hpx⟩, λ h ⟨x, hpx⟩ => h x hpx⟩
@[simp] theorem exists_false : ¬ (∃a:α, False) := fun ⟨a, h⟩ => h
@[simp] theorem exists_and_distrib_left {q : Prop} {p : α → Prop} :
(∃x, q ∧ p x) ↔ q ∧ (∃x, p x) :=
⟨λ ⟨x, hq, hp⟩ => ⟨hq, x, hp⟩, λ ⟨hq, x, hp⟩ => ⟨x, hq, hp⟩⟩
@[simp] theorem exists_and_distrib_right {q : Prop} {p : α → Prop} :
(∃x, p x ∧ q) ↔ (∃x, p x) ∧ q :=
by simp [and_comm]
@[simp] theorem exists_eq {a' : α} : ∃ a, a = a' := ⟨_, rfl⟩
@[simp] theorem exists_eq' {a' : α} : ∃ a, a' = a := ⟨_, rfl⟩
@[simp] theorem exists_eq_left {p : α → Prop} {a' : α} : (∃ a, a = a' ∧ p a) ↔ p a' :=
⟨λ ⟨a, e, h⟩ => e ▸ h, λ h => ⟨_, rfl, h⟩⟩
@[simp] theorem exists_eq_right {p : α → Prop} {a' : α} : (∃ a, p a ∧ a = a') ↔ p a' :=
(exists_congr $ by exact λ a => and_comm).trans exists_eq_left
@[simp] theorem exists_eq_left' {p : α → Prop} {a' : α} : (∃ a, a' = a ∧ p a) ↔ p a' :=
by simp [@eq_comm _ a']
protected theorem decidable.not_imp_symm [Decidable a] (h : ¬a → b) (hb : ¬b) : a :=
Decidable.by_contradiction $ hb ∘ h
theorem not.decidable_imp_symm [Decidable a] : (¬a → b) → ¬b → a := decidable.not_imp_symm
theorem not_forall_of_exists_not {p : α → Prop} : (∃ x, ¬ p x) → ¬ ∀ x, p x
| ⟨x, hn⟩, h => hn (h x)
protected theorem Decidable.not_forall {p : α → Prop}
[Decidable (∃ x, ¬ p x)] [∀ x, Decidable (p x)] : (¬ ∀ x, p x) ↔ ∃ x, ¬ p x :=
⟨not.decidable_imp_symm $ λ nx x => not.decidable_imp_symm (λ h => ⟨x, h⟩) nx,
not_forall_of_exists_not⟩
@[simp] theorem not_exists {p : α → Prop} : (¬ ∃ x, p x) ↔ ∀ x, ¬ p x :=
exists_imp_distrib
open Classical
@[simp] theorem not_forall {p : α → Prop} : (¬ ∀ x, p x) ↔ ∃ x, ¬ p x := Decidable.not_forall
|
cd8c8d960b41dff9450e01a111883c45e035b505 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/algebra/module/submodule/lattice.lean | 8c1c341c0a73b3f44020fdeec6e39237a1e41654 | [
"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 | 11,902 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro, Kevin Buzzard, Yury Kudryashov
-/
import algebra.module.submodule.basic
import algebra.punit_instances
/-!
# The lattice structure on `submodule`s
This file defines the lattice structure on submodules, `submodule.complete_lattice`, with `⊥`
defined as `{0}` and `⊓` defined as intersection of the underlying carrier.
If `p` and `q` are submodules of a module, `p ≤ q` means that `p ⊆ q`.
Many results about operations on this lattice structure are defined in `linear_algebra/basic.lean`,
most notably those which use `span`.
## Implementation notes
This structure should match the `add_submonoid.complete_lattice` structure, and we should try
to unify the APIs where possible.
-/
variables {R S M : Type*}
section add_comm_monoid
variables [semiring R] [semiring S] [add_comm_monoid M] [module R M] [module S M]
variables [has_smul S R] [is_scalar_tower S R M]
variables {p q : submodule R M}
namespace submodule
/-- The set `{0}` is the bottom element of the lattice of submodules. -/
instance : has_bot (submodule R M) :=
⟨{ carrier := {0}, smul_mem' := by simp { contextual := tt }, .. (⊥ : add_submonoid M)}⟩
instance inhabited' : inhabited (submodule R M) := ⟨⊥⟩
@[simp] lemma bot_coe : ((⊥ : submodule R M) : set M) = {0} := rfl
@[simp] lemma bot_to_add_submonoid : (⊥ : submodule R M).to_add_submonoid = ⊥ := rfl
section
variables (R)
@[simp] lemma restrict_scalars_bot : restrict_scalars S (⊥ : submodule R M) = ⊥ := rfl
@[simp] lemma mem_bot {x : M} : x ∈ (⊥ : submodule R M) ↔ x = 0 := set.mem_singleton_iff
end
@[simp] lemma restrict_scalars_eq_bot_iff {p : submodule R M} :
restrict_scalars S p = ⊥ ↔ p = ⊥ :=
by simp [set_like.ext_iff]
instance unique_bot : unique (⊥ : submodule R M) :=
⟨infer_instance, λ x, subtype.ext $ (mem_bot R).1 x.mem⟩
instance : order_bot (submodule R M) :=
{ bot := ⊥,
bot_le := λ p x, by simp [zero_mem] {contextual := tt} }
protected lemma eq_bot_iff (p : submodule R M) : p = ⊥ ↔ ∀ x ∈ p, x = (0 : M) :=
⟨ λ h, h.symm ▸ λ x hx, (mem_bot R).mp hx,
λ h, eq_bot_iff.mpr (λ x hx, (mem_bot R).mpr (h x hx)) ⟩
@[ext] protected lemma bot_ext (x y : (⊥ : submodule R M)) : x = y :=
begin
rcases x with ⟨x, xm⟩, rcases y with ⟨y, ym⟩, congr,
rw (submodule.eq_bot_iff _).mp rfl x xm,
rw (submodule.eq_bot_iff _).mp rfl y ym,
end
protected lemma ne_bot_iff (p : submodule R M) : p ≠ ⊥ ↔ ∃ x ∈ p, x ≠ (0 : M) :=
by { haveI := classical.prop_decidable, simp_rw [ne.def, p.eq_bot_iff, not_forall] }
lemma nonzero_mem_of_bot_lt {p : submodule R M} (bot_lt : ⊥ < p) : ∃ a : p, a ≠ 0 :=
let ⟨b, hb₁, hb₂⟩ := p.ne_bot_iff.mp bot_lt.ne' in ⟨⟨b, hb₁⟩, hb₂ ∘ (congr_arg coe)⟩
lemma exists_mem_ne_zero_of_ne_bot {p : submodule R M} (h : p ≠ ⊥) : ∃ b : M, b ∈ p ∧ b ≠ 0 :=
let ⟨b, hb₁, hb₂⟩ := p.ne_bot_iff.mp h in ⟨b, hb₁, hb₂⟩
/-- The bottom submodule is linearly equivalent to punit as an `R`-module. -/
@[simps] def bot_equiv_punit : (⊥ : submodule R M) ≃ₗ[R] punit :=
{ to_fun := λ x, punit.star,
inv_fun := λ x, 0,
map_add' := by { intros, ext, },
map_smul' := by { intros, ext, },
left_inv := by { intro x, ext, },
right_inv := by { intro x, ext, }, }
lemma eq_bot_of_subsingleton (p : submodule R M) [subsingleton p] : p = ⊥ :=
begin
rw eq_bot_iff,
intros v hv,
exact congr_arg coe (subsingleton.elim (⟨v, hv⟩ : p) 0)
end
/-- The universal set is the top element of the lattice of submodules. -/
instance : has_top (submodule R M) :=
⟨{ carrier := set.univ, smul_mem' := λ _ _ _, trivial, .. (⊤ : add_submonoid M)}⟩
@[simp] lemma top_coe : ((⊤ : submodule R M) : set M) = set.univ := rfl
@[simp] lemma top_to_add_submonoid : (⊤ : submodule R M).to_add_submonoid = ⊤ := rfl
@[simp] lemma mem_top {x : M} : x ∈ (⊤ : submodule R M) := trivial
section
variables (R)
@[simp] lemma restrict_scalars_top : restrict_scalars S (⊤ : submodule R M) = ⊤ := rfl
end
@[simp] lemma restrict_scalars_eq_top_iff {p : submodule R M} :
restrict_scalars S p = ⊤ ↔ p = ⊤ :=
by simp [set_like.ext_iff]
instance : order_top (submodule R M) :=
{ top := ⊤,
le_top := λ p x _, trivial }
lemma eq_top_iff' {p : submodule R M} : p = ⊤ ↔ ∀ x, x ∈ p :=
eq_top_iff.trans ⟨λ h x, h trivial, λ h x _, h x⟩
/-- The top submodule is linearly equivalent to the module.
This is the module version of `add_submonoid.top_equiv`. -/
@[simps] def top_equiv : (⊤ : submodule R M) ≃ₗ[R] M :=
{ to_fun := λ x, x,
inv_fun := λ x, ⟨x, by simp⟩,
map_add' := by { intros, refl, },
map_smul' := by { intros, refl, },
left_inv := by { intro x, ext, refl, },
right_inv := by { intro x, refl, }, }
instance : has_Inf (submodule R M) :=
⟨λ S,
{ carrier := ⋂ s ∈ S, (s : set M),
zero_mem' := by simp [zero_mem],
add_mem' := by simp [add_mem] {contextual := tt},
smul_mem' := by simp [smul_mem] {contextual := tt} }⟩
private lemma Inf_le' {S : set (submodule R M)} {p} : p ∈ S → Inf S ≤ p :=
set.bInter_subset_of_mem
private lemma le_Inf' {S : set (submodule R M)} {p} : (∀q ∈ S, p ≤ q) → p ≤ Inf S :=
set.subset_Inter₂
instance : has_inf (submodule R M) :=
⟨λ p q,
{ carrier := p ∩ q,
zero_mem' := by simp [zero_mem],
add_mem' := by simp [add_mem] {contextual := tt},
smul_mem' := by simp [smul_mem] {contextual := tt} }⟩
instance : complete_lattice (submodule R M) :=
{ sup := λ a b, Inf {x | a ≤ x ∧ b ≤ x},
le_sup_left := λ a b, le_Inf' $ λ x ⟨ha, hb⟩, ha,
le_sup_right := λ a b, le_Inf' $ λ x ⟨ha, hb⟩, hb,
sup_le := λ a b c h₁ h₂, Inf_le' ⟨h₁, h₂⟩,
inf := (⊓),
le_inf := λ a b c, set.subset_inter,
inf_le_left := λ a b, set.inter_subset_left _ _,
inf_le_right := λ a b, set.inter_subset_right _ _,
Sup := λtt, Inf {t | ∀t'∈tt, t' ≤ t},
le_Sup := λ s p hs, le_Inf' $ λ q hq, hq _ hs,
Sup_le := λ s p hs, Inf_le' hs,
Inf := Inf,
le_Inf := λ s a, le_Inf',
Inf_le := λ s a, Inf_le',
..submodule.order_top,
..submodule.order_bot,
..set_like.partial_order }
@[simp] theorem inf_coe : ↑(p ⊓ q) = (p ∩ q : set M) := rfl
@[simp] theorem mem_inf {p q : submodule R M} {x : M} :
x ∈ p ⊓ q ↔ x ∈ p ∧ x ∈ q := iff.rfl
@[simp] theorem Inf_coe (P : set (submodule R M)) : (↑(Inf P) : set M) = ⋂ p ∈ P, ↑p := rfl
@[simp] theorem finset_inf_coe {ι} (s : finset ι) (p : ι → submodule R M) :
(↑(s.inf p) : set M) = ⋂ i ∈ s, ↑(p i) :=
begin
letI := classical.dec_eq ι,
refine s.induction_on _ (λ i s hi ih, _),
{ simp },
{ rw [finset.inf_insert, inf_coe, ih],
simp },
end
@[simp] theorem infi_coe {ι} (p : ι → submodule R M) :
(↑⨅ i, p i : set M) = ⋂ i, ↑(p i) :=
by rw [infi, Inf_coe]; ext a; simp; exact
⟨λ h i, h _ i rfl, λ h i x e, e ▸ h _⟩
@[simp] lemma mem_Inf {S : set (submodule R M)} {x : M} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p :=
set.mem_Inter₂
@[simp] theorem mem_infi {ι} (p : ι → submodule R M) {x} :
x ∈ (⨅ i, p i) ↔ ∀ i, x ∈ p i :=
by rw [← set_like.mem_coe, infi_coe, set.mem_Inter]; refl
@[simp] theorem mem_finset_inf {ι} {s : finset ι} {p : ι → submodule R M} {x : M} :
x ∈ s.inf p ↔ ∀ i ∈ s, x ∈ p i :=
by simp only [← set_like.mem_coe, finset_inf_coe, set.mem_Inter]
lemma mem_sup_left {S T : submodule R M} : ∀ {x : M}, x ∈ S → x ∈ S ⊔ T :=
show S ≤ S ⊔ T, from le_sup_left
lemma mem_sup_right {S T : submodule R M} : ∀ {x : M}, x ∈ T → x ∈ S ⊔ T :=
show T ≤ S ⊔ T, from le_sup_right
lemma add_mem_sup {S T : submodule R M} {s t : M} (hs : s ∈ S) (ht : t ∈ T) : s + t ∈ S ⊔ T :=
add_mem (mem_sup_left hs) (mem_sup_right ht)
lemma sub_mem_sup {R' M' : Type*} [ring R'] [add_comm_group M'] [module R' M']
{S T : submodule R' M'} {s t : M'} (hs : s ∈ S) (ht : t ∈ T) :
s - t ∈ S ⊔ T :=
begin
rw sub_eq_add_neg,
exact add_mem_sup hs (neg_mem ht),
end
lemma mem_supr_of_mem {ι : Sort*} {b : M} {p : ι → submodule R M} (i : ι) (h : b ∈ p i) :
b ∈ (⨆i, p i) :=
have p i ≤ (⨆i, p i) := le_supr p i,
@this b h
open_locale big_operators
lemma sum_mem_supr {ι : Type*} [fintype ι] {f : ι → M} {p : ι → submodule R M}
(h : ∀ i, f i ∈ p i) :
∑ i, f i ∈ ⨆ i, p i :=
sum_mem $ λ i hi, mem_supr_of_mem i (h i)
lemma sum_mem_bsupr {ι : Type*} {s : finset ι} {f : ι → M} {p : ι → submodule R M}
(h : ∀ i ∈ s, f i ∈ p i) :
∑ i in s, f i ∈ ⨆ i ∈ s, p i :=
sum_mem $ λ i hi, mem_supr_of_mem i $ mem_supr_of_mem hi (h i hi)
/-! Note that `submodule.mem_supr` is provided in `linear_algebra/basic.lean`. -/
lemma mem_Sup_of_mem {S : set (submodule R M)} {s : submodule R M}
(hs : s ∈ S) : ∀ {x : M}, x ∈ s → x ∈ Sup S :=
show s ≤ Sup S, from le_Sup hs
theorem disjoint_def {p p' : submodule R M} :
disjoint p p' ↔ ∀ x ∈ p, x ∈ p' → x = (0:M) :=
disjoint_iff_inf_le.trans $ show (∀ x, x ∈ p ∧ x ∈ p' → x ∈ ({0} : set M)) ↔ _, by simp
theorem disjoint_def' {p p' : submodule R M} :
disjoint p p' ↔ ∀ (x ∈ p) (y ∈ p'), x = y → x = (0:M) :=
disjoint_def.trans ⟨λ h x hx y hy hxy, h x hx $ hxy.symm ▸ hy,
λ h x hx hx', h _ hx x hx' rfl⟩
lemma eq_zero_of_coe_mem_of_disjoint (hpq : disjoint p q) {a : p} (ha : (a : M) ∈ q) :
a = 0 :=
by exact_mod_cast disjoint_def.mp hpq a (coe_mem a) ha
end submodule
section nat_submodule
/-- An additive submonoid is equivalent to a ℕ-submodule. -/
def add_submonoid.to_nat_submodule : add_submonoid M ≃o submodule ℕ M :=
{ to_fun := λ S,
{ smul_mem' := λ r s hs, show r • s ∈ S, from nsmul_mem hs _, ..S },
inv_fun := submodule.to_add_submonoid,
left_inv := λ ⟨S, _, _⟩, rfl,
right_inv := λ ⟨S, _, _, _⟩, rfl,
map_rel_iff' := λ a b, iff.rfl }
@[simp]
lemma add_submonoid.to_nat_submodule_symm :
⇑(add_submonoid.to_nat_submodule.symm : _ ≃o add_submonoid M) = submodule.to_add_submonoid := rfl
@[simp]
lemma add_submonoid.coe_to_nat_submodule (S : add_submonoid M) :
(S.to_nat_submodule : set M) = S := rfl
@[simp]
lemma add_submonoid.to_nat_submodule_to_add_submonoid (S : add_submonoid M) :
S.to_nat_submodule.to_add_submonoid = S :=
add_submonoid.to_nat_submodule.symm_apply_apply S
@[simp]
lemma submodule.to_add_submonoid_to_nat_submodule (S : submodule ℕ M) :
S.to_add_submonoid.to_nat_submodule = S :=
add_submonoid.to_nat_submodule.apply_symm_apply S
end nat_submodule
end add_comm_monoid
section int_submodule
variables [add_comm_group M]
/-- An additive subgroup is equivalent to a ℤ-submodule. -/
def add_subgroup.to_int_submodule : add_subgroup M ≃o submodule ℤ M :=
{ to_fun := λ S,
{ smul_mem' := λ r s hs, S.zsmul_mem hs _, ..S},
inv_fun := submodule.to_add_subgroup,
left_inv := λ ⟨S, _, _, _⟩, rfl,
right_inv := λ ⟨S, _, _, _⟩, rfl,
map_rel_iff' := λ a b, iff.rfl }
@[simp]
lemma add_subgroup.to_int_submodule_symm :
⇑(add_subgroup.to_int_submodule.symm : _ ≃o add_subgroup M) = submodule.to_add_subgroup := rfl
@[simp]
lemma add_subgroup.coe_to_int_submodule (S : add_subgroup M) :
(S.to_int_submodule : set M) = S := rfl
@[simp]
lemma add_subgroup.to_int_submodule_to_add_subgroup (S : add_subgroup M) :
S.to_int_submodule.to_add_subgroup = S :=
add_subgroup.to_int_submodule.symm_apply_apply S
@[simp]
lemma submodule.to_add_subgroup_to_int_submodule (S : submodule ℤ M) :
S.to_add_subgroup.to_int_submodule = S :=
add_subgroup.to_int_submodule.apply_symm_apply S
end int_submodule
|
4f3d80139e1a7dd18990ac2b25d53b0951271032 | 8930e38ac0fae2e5e55c28d0577a8e44e2639a6d | /tests/examples.lean | a106f1e044928a96d7d99f156a2456f216f36a4e | [
"Apache-2.0"
] | permissive | SG4316/mathlib | 3d64035d02a97f8556ad9ff249a81a0a51a3321a | a7846022507b531a8ab53b8af8a91953fceafd3a | refs/heads/master | 1,584,869,960,527 | 1,530,718,645,000 | 1,530,724,110,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,759 | lean | import tactic data.stream.basic data.set.basic data.finset data.multiset
open tactic
universe u
variable {α : Type}
example (s t u : set ℕ) (h : s ⊆ t ∩ u) (h' : u ⊆ s) : u ⊆ s → true :=
begin
dunfold has_subset.subset has_inter.inter at *,
-- trace_state,
intro1, triv
end
example (s t u : set ℕ) (h : s ⊆ t ∩ u) (h' : u ⊆ s) : u ⊆ s → true :=
begin
delta has_subset.subset has_inter.inter at *,
-- trace_state,
intro1, triv
end
example (x y z : ℕ) (h'' : true) (h : 0 + y = x) (h' : 0 + y = z) : x = z + 0 :=
begin
simp at *,
-- trace_state,
rw [←h, ←h']
end
example (x y z : ℕ) (h'' : true) (h : 0 + y = x) (h' : 0 + y = z) : x = z + 0 :=
begin
simp at *,
simp [h] at h',
simp [*]
end
def my_id (x : α) := x
def my_id_def (x : α) : my_id x = x := rfl
example (x y z : ℕ) (h'' : true) (h : 0 + my_id y = x) (h' : 0 + y = z) : x = z + 0 :=
begin
simp [my_id_def] at *, simp [h] at h', simp [*]
end
@[simp] theorem mem_set_of {a : α} {p : α → Prop} : a ∈ {a | p a} = p a := rfl
-- TODO: write a tactic to unfold specific instances of generic notation?
theorem subset_def {s t : set α} : (s ⊆ t) = ∀ x, x ∈ s → x ∈ t := rfl
theorem union_def {s₁ s₂ : set α} : s₁ ∪ s₂ = {a | a ∈ s₁ ∨ a ∈ s₂} := rfl
theorem inter_def {s₁ s₂ : set α} : s₁ ∩ s₂ = {a | a ∈ s₁ ∧ a ∈ s₂} := rfl
theorem union_subset {s t r : set α} (sr : s ⊆ r) (tr : t ⊆ r) : s ∪ t ⊆ r :=
begin
dsimp [subset_def, union_def] at *,
intros x h,
cases h; back_chaining_using_hs
end
theorem subset_inter {s t r : set α} (rs : r ⊆ s) (rt : r ⊆ t) : r ⊆ s ∩ t :=
begin
dsimp [subset_def, inter_def] at *,
intros x h,
split; back_chaining_using_hs
end
/- extensionality -/
example : true :=
begin
have : ∀ (s₀ s₁ : set ℕ), s₀ = s₁,
{ intros, ext1,
guard_target x ∈ s₀ ↔ x ∈ s₁,
admit },
have : ∀ (s₀ s₁ : finset ℕ), s₀ = s₁,
{ intros, ext1,
guard_target a ∈ s₀ ↔ a ∈ s₁,
admit },
have : ∀ (s₀ s₁ : multiset ℕ), s₀ = s₁,
{ intros, ext1,
guard_target multiset.count a s₀ = multiset.count a s₁,
admit },
have : ∀ (s₀ s₁ : list ℕ), s₀ = s₁,
{ intros, ext1,
guard_target list.nth s₀ n = list.nth s₁ n,
admit },
have : ∀ (s₀ s₁ : stream ℕ), s₀ = s₁,
{ intros, ext1,
guard_target stream.nth n s₀ = stream.nth n s₁,
admit },
have : ∀ n (s₀ s₁ : array n ℕ), s₀ = s₁,
{ intros, ext1,
guard_target array.read s₀ i = array.read s₁ i,
admit },
trivial
end
/- tauto -/
example (p : Prop) : p ∧ true ↔ p := by tauto
example (p : Prop) : p ∨ false → p := by tauto
|
b8379622a2ff2c932fcc98ebc823aabbc0ba6fb8 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/inout_level.lean | 2a88929b68bcd529ea13d66b8084bf603716a2f5 | [
"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 | 224 | lean | section bug
variables (x y z : Type)
variables (f : x → y) (g : y → z)
variables (xy : set (x → y)) (yz : set (y → z)) (xz : set (x → z))
--#check f ∈ xy
--#check g ∈ yz
#check (g ∘ f) ∈ xz --error
end bug
|
fb41300fa39a8513d41ec748b28a8a8366fc162d | 35677d2df3f081738fa6b08138e03ee36bc33cad | /src/set_theory/ordinal_notation.lean | 8d6e57e9a7ee29c599574a3ae436a148d0506f44 | [
"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 | 35,833 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
Ordinal notations (constructive ordinal arithmetic for ordinals < ε₀).
-/
import set_theory.ordinal data.pnat.basic
open ordinal
open_locale ordinal -- get notation for `ω`
/-- Recursive definition of an ordinal notation. `zero` denotes the
ordinal 0, and `oadd e n a` is intended to refer to `ω^e * n + a`.
For this to be valid Cantor normal form, we must have the exponents
decrease to the right, but we can't state this condition until we've
defined `repr`, so it is a separate definition `NF`. -/
@[derive decidable_eq]
inductive onote : Type
| zero : onote
| oadd : onote → ℕ+ → onote → onote
namespace onote
/-- Notation for 0 -/
instance : has_zero onote := ⟨zero⟩
@[simp] theorem zero_def : zero = 0 := rfl
instance : inhabited onote := ⟨0⟩
/-- Notation for 1 -/
instance : has_one onote := ⟨oadd 0 1 0⟩
/-- Notation for ω -/
def omega : onote := oadd 1 1 0
/-- The ordinal denoted by a notation -/
@[simp] noncomputable def repr : onote → ordinal.{0}
| 0 := 0
| (oadd e n a) := ω ^ repr e * n + repr a
def to_string_aux1 (e : onote) (n : ℕ) (s : string) : string :=
if e = 0 then _root_.to_string n else
(if e = 1 then "ω" else "ω^(" ++ s ++ ")") ++
if n = 1 then "" else "*" ++ _root_.to_string n
/-- Print an ordinal notation -/
def to_string : onote → string
| zero := "0"
| (oadd e n 0) := to_string_aux1 e n (to_string e)
| (oadd e n a) := to_string_aux1 e n (to_string e) ++ " + " ++ to_string a
/-- Print an ordinal notation -/
def repr' : onote → string
| zero := "0"
| (oadd e n a) := "(oadd " ++ repr' e ++ " " ++ _root_.to_string (n:ℕ) ++ " " ++ repr' a ++ ")"
instance : has_to_string onote := ⟨to_string⟩
instance : has_repr onote := ⟨repr'⟩
instance : preorder onote :=
{ le := λ x y, repr x ≤ repr y,
lt := λ x y, repr x < repr y,
le_refl := λ a, @le_refl ordinal _ _,
le_trans := λ a b c, @le_trans ordinal _ _ _ _,
lt_iff_le_not_le := λ a b, @lt_iff_le_not_le ordinal _ _ _ }
theorem lt_def {x y : onote} : x < y ↔ repr x < repr y := iff.rfl
theorem le_def {x y : onote} : x ≤ y ↔ repr x ≤ repr y := iff.rfl
/-- Convert a `nat` into an ordinal -/
@[simp] def of_nat : ℕ → onote
| 0 := 0
| (nat.succ n) := oadd 0 n.succ_pnat 0
@[simp] theorem of_nat_one : of_nat 1 = 1 := rfl
@[simp] theorem repr_of_nat (n : ℕ) : repr (of_nat n) = n :=
by cases n; simp
@[simp] theorem repr_one : repr 1 = 1 :=
by simpa using repr_of_nat 1
theorem omega_le_oadd (e n a) : ω ^ repr e ≤ repr (oadd e n a) :=
begin
unfold repr,
refine le_trans _ (le_add_right _ _),
simpa using (mul_le_mul_iff_left $ power_pos (repr e) omega_pos).2 (nat_cast_le.2 n.2)
end
theorem oadd_pos (e n a) : 0 < oadd e n a :=
@lt_of_lt_of_le _ _ _ _ _ (power_pos _ omega_pos)
(omega_le_oadd _ _ _)
/-- Compare ordinal notations -/
def cmp : onote → onote → ordering
| 0 0 := ordering.eq
| _ 0 := ordering.gt
| 0 _ := ordering.lt
| o₁@(oadd e₁ n₁ a₁) o₂@(oadd e₂ n₂ a₂) :=
(cmp e₁ e₂).or_else $ (_root_.cmp (n₁:ℕ) n₂).or_else (cmp a₁ a₂)
theorem eq_of_cmp_eq : ∀ {o₁ o₂}, cmp o₁ o₂ = ordering.eq → o₁ = o₂
| 0 0 h := rfl
| (oadd e n a) 0 h := by injection h
| 0 (oadd e n a) h := by injection h
| o₁@(oadd e₁ n₁ a₁) o₂@(oadd e₂ n₂ a₂) h := begin
revert h, simp [cmp],
cases h₁ : cmp e₁ e₂; intro h; try {cases h},
have := eq_of_cmp_eq h₁, subst e₂,
revert h, cases h₂ : _root_.cmp (n₁:ℕ) n₂; intro h; try {cases h},
have := eq_of_cmp_eq h, subst a₂,
rw [_root_.cmp, cmp_using_eq_eq] at h₂,
have := subtype.eq (eq_of_incomp h₂), subst n₂, simp
end
theorem zero_lt_one : (0 : onote) < 1 :=
by rw [lt_def, repr, repr_one]; exact zero_lt_one
/-- `NF_below o b` says that `o` is a normal form ordinal notation
satisfying `repr o < ω ^ b`. -/
inductive NF_below : onote → ordinal.{0} → Prop
| zero {b} : NF_below 0 b
| oadd' {e n a eb b} : NF_below e eb →
NF_below a (repr e) → repr e < b → NF_below (oadd e n a) b
/-- A normal form ordinal notation has the form
ω ^ a₁ * n₁ + ω ^ a₂ * n₂ + ... ω ^ aₖ * nₖ
where `a₁ > a₂ > ... > aₖ` and all the `aᵢ` are
also in normal form.
We will essentially only be interested in normal form
ordinal notations, but to avoid complicating the algorithms
we define everything over general ordinal notations and
only prove correctness with normal form as an invariant. -/
@[class] def NF (o : onote) := Exists (NF_below o)
instance NF.zero : NF 0 := ⟨0, NF_below.zero⟩
theorem NF_below.oadd {e n a b} : NF e →
NF_below a (repr e) → repr e < b → NF_below (oadd e n a) b
| ⟨eb, h⟩ := NF_below.oadd' h
theorem NF_below.fst {e n a b} (h : NF_below (oadd e n a) b) : NF e :=
by cases h with _ _ _ _ eb _ h₁ h₂ h₃; exact ⟨_, h₁⟩
theorem NF.fst {e n a} : NF (oadd e n a) → NF e
| ⟨b, h⟩ := h.fst
theorem NF_below.snd {e n a b} (h : NF_below (oadd e n a) b) : NF_below a (repr e) :=
by cases h with _ _ _ _ eb _ h₁ h₂ h₃; exact h₂
theorem NF.snd' {e n a} : NF (oadd e n a) → NF_below a (repr e)
| ⟨b, h⟩ := h.snd
theorem NF.snd {e n a} (h : NF (oadd e n a)) : NF a :=
⟨_, h.snd'⟩
theorem NF.oadd {e a} (h₁ : NF e) (n)
(h₂ : NF_below a (repr e)) : NF (oadd e n a) :=
⟨_, NF_below.oadd h₁ h₂ (ordinal.lt_succ_self _)⟩
instance NF.oadd_zero (e n) [h : NF e] : NF (oadd e n 0) :=
h.oadd _ NF_below.zero
theorem NF_below.lt {e n a b} (h : NF_below (oadd e n a) b) : repr e < b :=
by cases h with _ _ _ _ eb _ h₁ h₂ h₃; exact h₃
theorem NF_below_zero : ∀ {o}, NF_below o 0 ↔ o = 0
| 0 := ⟨λ _, rfl, λ _, NF_below.zero⟩
| (oadd e n a) := ⟨λ h, (not_le_of_lt h.lt).elim (zero_le _),
λ e, e.symm ▸ NF_below.zero⟩
theorem NF.zero_of_zero {e n a} (h : NF (oadd e n a)) (e0 : e = 0) : a = 0 :=
by simpa [e0, NF_below_zero] using h.snd'
theorem NF_below.repr_lt {o b} (h : NF_below o b) : repr o < ω ^ b :=
begin
induction h with _ e n a eb b h₁ h₂ h₃ _ IH,
{ exact power_pos _ omega_pos },
{ rw repr,
refine lt_of_lt_of_le ((ordinal.add_lt_add_iff_left _).2 IH) _,
rw ← mul_succ,
refine le_trans (mul_le_mul_left _ $ ordinal.succ_le.2 $ nat_lt_omega _) _,
rw ← power_succ,
exact power_le_power_right omega_pos (ordinal.succ_le.2 h₃) }
end
theorem NF_below.mono {o b₁ b₂} (bb : b₁ ≤ b₂) (h : NF_below o b₁) : NF_below o b₂ :=
begin
induction h with _ e n a eb b h₁ h₂ h₃ _ IH; constructor,
exacts [h₁, h₂, lt_of_lt_of_le h₃ bb]
end
theorem NF.below_of_lt {e n a b} (H : repr e < b) : NF (oadd e n a) → NF_below (oadd e n a) b
| ⟨b', h⟩ := by cases h with _ _ _ _ eb _ h₁ h₂ h₃;
exact NF_below.oadd' h₁ h₂ H
theorem NF.below_of_lt' : ∀ {o b}, repr o < ω ^ b → NF o → NF_below o b
| 0 b H _ := NF_below.zero
| (oadd e n a) b H h := h.below_of_lt $ (power_lt_power_iff_right one_lt_omega).1 $
(lt_of_le_of_lt (omega_le_oadd _ _ _) H)
theorem NF_below_of_nat : ∀ n, NF_below (of_nat n) 1
| 0 := NF_below.zero
| (nat.succ n) := NF_below.oadd NF.zero NF_below.zero ordinal.zero_lt_one
instance NF_of_nat (n) : NF (of_nat n) := ⟨_, NF_below_of_nat n⟩
instance NF_one : NF 1 := by rw ← of_nat_one; apply_instance
theorem oadd_lt_oadd_1 {e₁ n₁ o₁ e₂ n₂ o₂}
(h₁ : NF (oadd e₁ n₁ o₁)) (h₂ : NF (oadd e₂ n₂ o₂))
(h : e₁ < e₂) : oadd e₁ n₁ o₁ < oadd e₂ n₂ o₂ :=
@lt_of_lt_of_le _ _ _ _ _ ((h₁.below_of_lt h).repr_lt) (omega_le_oadd _ _ _)
theorem oadd_lt_oadd_2 {e n₁ o₁ n₂ o₂}
(h₁ : NF (oadd e n₁ o₁)) (h₂ : NF (oadd e n₂ o₂))
(h : (n₁:ℕ) < n₂) : oadd e n₁ o₁ < oadd e n₂ o₂ :=
begin
simp [lt_def],
refine lt_of_lt_of_le ((ordinal.add_lt_add_iff_left _).2 h₁.snd'.repr_lt)
(le_trans _ (le_add_right _ _)),
rwa [← mul_succ, mul_le_mul_iff_left (power_pos _ omega_pos),
ordinal.succ_le, nat_cast_lt]
end
theorem oadd_lt_oadd_3 {e n a₁ a₂}
(h₁ : NF (oadd e n a₁)) (h₂ : NF (oadd e n a₂))
(h : a₁ < a₂) : oadd e n a₁ < oadd e n a₂ :=
begin
rw lt_def, unfold repr,
exact (ordinal.add_lt_add_iff_left _).2 h
end
theorem cmp_compares : ∀ (a b : onote) [NF a] [NF b], (cmp a b).compares a b
| 0 0 h₁ h₂ := rfl
| (oadd e n a) 0 h₁ h₂ := oadd_pos _ _ _
| 0 (oadd e n a) h₁ h₂ := oadd_pos _ _ _
| o₁@(oadd e₁ n₁ a₁) o₂@(oadd e₂ n₂ a₂) h₁ h₂ := begin
rw cmp,
have IHe := @cmp_compares _ _ h₁.fst h₂.fst,
cases cmp e₁ e₂,
case ordering.lt { exact oadd_lt_oadd_1 h₁ h₂ IHe },
case ordering.gt { exact oadd_lt_oadd_1 h₂ h₁ IHe },
change e₁ = e₂ at IHe, subst IHe,
unfold _root_.cmp, cases nh : cmp_using (<) (n₁:ℕ) n₂,
case ordering.lt {
rw cmp_using_eq_lt at nh, exact oadd_lt_oadd_2 h₁ h₂ nh },
case ordering.gt {
rw cmp_using_eq_gt at nh, exact oadd_lt_oadd_2 h₂ h₁ nh },
rw cmp_using_eq_eq at nh,
have := subtype.eq (eq_of_incomp nh), subst n₂,
have IHa := @cmp_compares _ _ h₁.snd h₂.snd,
cases cmp a₁ a₂,
case ordering.lt { exact oadd_lt_oadd_3 h₁ h₂ IHa },
case ordering.gt { exact oadd_lt_oadd_3 h₂ h₁ IHa },
change a₁ = a₂ at IHa, subst IHa, exact rfl
end
theorem repr_inj {a b} [NF a] [NF b] : repr a = repr b ↔ a = b :=
⟨match cmp a b, cmp_compares a b with
| ordering.lt, (h : repr a < repr b), e := (ne_of_lt h e).elim
| ordering.gt, (h : repr a > repr b), e := (ne_of_gt h e).elim
| ordering.eq, h, e := h
end, congr_arg _⟩
theorem NF.of_dvd_omega_power {b e n a} (h : NF (oadd e n a)) (d : ω ^ b ∣ repr (oadd e n a)) :
b ≤ repr e ∧ ω ^ b ∣ repr a :=
begin
have := mt repr_inj.1 (λ h, by injection h : oadd e n a ≠ 0),
have L := le_of_not_lt (λ l, not_le_of_lt (h.below_of_lt l).repr_lt (le_of_dvd this d)),
simp at d,
exact ⟨L, (dvd_add_iff $ dvd_mul_of_dvd _ $ power_dvd_power _ L).1 d⟩
end
theorem NF.of_dvd_omega {e n a} (h : NF (oadd e n a)) :
ω ∣ repr (oadd e n a) → repr e ≠ 0 ∧ ω ∣ repr a :=
by rw [← power_one ω, ← one_le_iff_ne_zero]; exact h.of_dvd_omega_power
/-- `top_below b o` asserts that the largest exponent in `o`, if
it exists, is less than `b`. This is an auxiliary definition
for decidability of `NF`. -/
def top_below (b) : onote → Prop
| 0 := true
| (oadd e n a) := cmp e b = ordering.lt
instance decidable_top_below : decidable_rel top_below :=
by intros b o; cases o; delta top_below; apply_instance
theorem NF_below_iff_top_below {b} [NF b] : ∀ {o},
NF_below o (repr b) ↔ NF o ∧ top_below b o
| 0 := ⟨λ h, ⟨⟨_, h⟩, trivial⟩, λ _, NF_below.zero⟩
| (oadd e n a) :=
⟨λ h, ⟨⟨_, h⟩, (@cmp_compares _ b h.fst _).eq_lt.2 h.lt⟩,
λ ⟨h₁, h₂⟩, h₁.below_of_lt $ (@cmp_compares _ b h₁.fst _).eq_lt.1 h₂⟩
instance decidable_NF : decidable_pred NF
| 0 := is_true NF.zero
| (oadd e n a) := begin
have := decidable_NF e,
have := decidable_NF a, resetI,
apply decidable_of_iff (NF e ∧ NF a ∧ top_below e a),
abstract {
rw ← and_congr_right (λ h, @NF_below_iff_top_below _ h _),
exact ⟨λ ⟨h₁, h₂⟩, NF.oadd h₁ n h₂, λ h, ⟨h.fst, h.snd'⟩⟩ },
end
/-- Addition of ordinal notations (correct only for normal input) -/
def add : onote → onote → onote
| 0 o := o
| (oadd e n a) o := match add a o with
| 0 := oadd e n 0
| o'@(oadd e' n' a') := match cmp e e' with
| ordering.lt := o'
| ordering.eq := oadd e (n + n') a'
| ordering.gt := oadd e n o'
end
end
instance : has_add onote := ⟨add⟩
@[simp] theorem zero_add (o : onote) : 0 + o = o := rfl
theorem oadd_add (e n a o) : oadd e n a + o = add._match_1 e n (a + o) := rfl
/-- Subtraction of ordinal notations (correct only for normal input) -/
def sub : onote → onote → onote
| 0 o := 0
| o 0 := o
| o₁@(oadd e₁ n₁ a₁) (oadd e₂ n₂ a₂) := match cmp e₁ e₂ with
| ordering.lt := 0
| ordering.gt := o₁
| ordering.eq := match (n₁:ℕ) - n₂ with
| 0 := if n₁ = n₂ then sub a₁ a₂ else 0
| (nat.succ k) := oadd e₁ k.succ_pnat a₁
end
end
instance : has_sub onote := ⟨sub⟩
theorem add_NF_below {b} : ∀ {o₁ o₂}, NF_below o₁ b → NF_below o₂ b → NF_below (o₁ + o₂) b
| 0 o h₁ h₂ := h₂
| (oadd e n a) o h₁ h₂ := begin
have h' := add_NF_below (h₁.snd.mono $ le_of_lt h₁.lt) h₂,
simp [oadd_add], cases a + o with e' n' a',
{ exact NF_below.oadd h₁.fst NF_below.zero h₁.lt },
simp [add], have := @cmp_compares _ _ h₁.fst h'.fst,
cases cmp e e'; simp [add],
{ exact h' },
{ simp at this, subst e',
exact NF_below.oadd h'.fst h'.snd h'.lt },
{ exact NF_below.oadd h₁.fst (NF.below_of_lt this ⟨_, h'⟩) h₁.lt }
end
instance add_NF (o₁ o₂) : ∀ [NF o₁] [NF o₂], NF (o₁ + o₂)
| ⟨b₁, h₁⟩ ⟨b₂, h₂⟩ := (b₁.le_total b₂).elim
(λ h, ⟨b₂, add_NF_below (h₁.mono h) h₂⟩)
(λ h, ⟨b₁, add_NF_below h₁ (h₂.mono h)⟩)
@[simp] theorem repr_add : ∀ o₁ o₂ [NF o₁] [NF o₂], repr (o₁ + o₂) = repr o₁ + repr o₂
| 0 o h₁ h₂ := by simp
| (oadd e n a) o h₁ h₂ := begin
haveI := h₁.snd, have h' := repr_add a o,
conv at h' in (_+o) {simp [(+)]},
have nf := onote.add_NF a o,
conv at nf in (_+o) {simp [(+)]},
conv in (_+o) {simp [(+), add]},
cases add a o with e' n' a'; simp [add, h'.symm],
have := h₁.fst, have := nf.fst, have ee := cmp_compares e e',
cases cmp e e'; simp [add],
{ rw [← add_assoc, @add_absorp _ (repr e') (ω ^ repr e' * (n':ℕ))],
{ have := (h₁.below_of_lt ee).repr_lt, unfold repr at this,
exact lt_of_le_of_lt (le_add_right _ _) this },
{ simpa using (mul_le_mul_iff_left $
power_pos (repr e') omega_pos).2 (nat_cast_le.2 n'.pos) } },
{ change e = e' at ee, subst e',
rw [← add_assoc, ← ordinal.mul_add, ← nat.cast_add] }
end
theorem sub_NF_below : ∀ {o₁ o₂ b}, NF_below o₁ b → NF o₂ → NF_below (o₁ - o₂) b
| 0 o b h₁ h₂ := by cases o; exact NF_below.zero
| (oadd e n a) 0 b h₁ h₂ := h₁
| (oadd e₁ n₁ a₁) (oadd e₂ n₂ a₂) b h₁ h₂ := begin
have h' := sub_NF_below h₁.snd h₂.snd,
simp [has_sub.sub, sub] at h' ⊢,
have := @cmp_compares _ _ h₁.fst h₂.fst,
cases cmp e₁ e₂; simp [sub],
{ apply NF_below.zero },
{ simp at this, subst e₂,
cases mn : (n₁:ℕ) - n₂; simp [sub],
{ by_cases en : n₁ = n₂; simp [en],
{ exact h'.mono (le_of_lt h₁.lt) },
{ exact NF_below.zero } },
{ exact NF_below.oadd h₁.fst h₁.snd h₁.lt } },
{ exact h₁ }
end
instance sub_NF (o₁ o₂) : ∀ [NF o₁] [NF o₂], NF (o₁ - o₂)
| ⟨b₁, h₁⟩ h₂ := ⟨b₁, sub_NF_below h₁ h₂⟩
@[simp] theorem repr_sub : ∀ o₁ o₂ [NF o₁] [NF o₂], repr (o₁ - o₂) = repr o₁ - repr o₂
| 0 o h₁ h₂ := by cases o; exact (ordinal.zero_sub _).symm
| (oadd e n a) 0 h₁ h₂ := (ordinal.sub_zero _).symm
| (oadd e₁ n₁ a₁) (oadd e₂ n₂ a₂) h₁ h₂ := begin
haveI := h₁.snd, haveI := h₂.snd, have h' := repr_sub a₁ a₂,
conv at h' in (a₁-a₂) {simp [has_sub.sub]},
have nf := onote.sub_NF a₁ a₂,
conv at nf in (a₁-a₂) {simp [has_sub.sub]},
conv in (_-oadd _ _ _) {simp [has_sub.sub, sub]},
have ee := @cmp_compares _ _ h₁.fst h₂.fst,
cases cmp e₁ e₂,
{ rw [sub_eq_zero_iff_le.2], {refl},
exact le_of_lt (oadd_lt_oadd_1 h₁ h₂ ee) },
{ change e₁ = e₂ at ee, subst e₂, unfold sub._match_1,
cases mn : (n₁:ℕ) - n₂; dsimp only [sub._match_2],
{ by_cases en : n₁ = n₂,
{ simp [en], rwa [add_sub_add_cancel] },
{ simp [en, -repr],
exact (sub_eq_zero_iff_le.2 $ le_of_lt $ oadd_lt_oadd_2 h₁ h₂ $
lt_of_le_of_ne (nat.sub_eq_zero_iff_le.1 mn) (mt pnat.eq en)).symm } },
{ simp [nat.succ_pnat, -nat.cast_succ],
rw [(nat.sub_eq_iff_eq_add $ le_of_lt $ nat.lt_of_sub_eq_succ mn).1 mn,
add_comm, nat.cast_add, ordinal.mul_add, add_assoc, add_sub_add_cancel],
refine (ordinal.sub_eq_of_add_eq $ add_absorp h₂.snd'.repr_lt $
le_trans _ (le_add_right _ _)).symm,
simpa using mul_le_mul_left _ (nat_cast_le.2 $ nat.succ_pos _) } },
{ exact (ordinal.sub_eq_of_add_eq $ add_absorp (h₂.below_of_lt ee).repr_lt $
omega_le_oadd _ _ _).symm }
end
/-- Multiplication of ordinal notations (correct only for normal input) -/
def mul : onote → onote → onote
| 0 _ := 0
| _ 0 := 0
| o₁@(oadd e₁ n₁ a₁) (oadd e₂ n₂ a₂) :=
if e₂ = 0 then oadd e₁ (n₁ * n₂) a₁ else
oadd (e₁ + e₂) n₂ (mul o₁ a₂)
instance : has_mul onote := ⟨mul⟩
@[simp] theorem zero_mul (o : onote) : 0 * o = 0 := by cases o; refl
@[simp] theorem mul_zero (o : onote) : o * 0 = 0 := by cases o; refl
theorem oadd_mul (e₁ n₁ a₁ e₂ n₂ a₂) : oadd e₁ n₁ a₁ * oadd e₂ n₂ a₂ =
if e₂ = 0 then oadd e₁ (n₁ * n₂) a₁ else
oadd (e₁ + e₂) n₂ (oadd e₁ n₁ a₁ * a₂) := rfl
theorem oadd_mul_NF_below {e₁ n₁ a₁ b₁} (h₁ : NF_below (oadd e₁ n₁ a₁) b₁) :
∀ {o₂ b₂}, NF_below o₂ b₂ → NF_below (oadd e₁ n₁ a₁ * o₂) (repr e₁ + b₂)
| 0 b₂ h₂ := NF_below.zero
| (oadd e₂ n₂ a₂) b₂ h₂ := begin
have IH := oadd_mul_NF_below h₂.snd,
by_cases e0 : e₂ = 0; simp [e0, oadd_mul],
{ apply NF_below.oadd h₁.fst h₁.snd,
simpa using (add_lt_add_iff_left (repr e₁)).2
(lt_of_le_of_lt (ordinal.zero_le _) h₂.lt) },
{ haveI := h₁.fst, haveI := h₂.fst,
apply NF_below.oadd, apply_instance,
{ rwa repr_add },
{ rw [repr_add, ordinal.add_lt_add_iff_left], exact h₂.lt } }
end
instance mul_NF : ∀ o₁ o₂ [NF o₁] [NF o₂], NF (o₁ * o₂)
| 0 o h₁ h₂ := by cases o; exact NF.zero
| (oadd e n a) o ⟨b₁, hb₁⟩ ⟨b₂, hb₂⟩ :=
⟨_, oadd_mul_NF_below hb₁ hb₂⟩
@[simp] theorem repr_mul : ∀ o₁ o₂ [NF o₁] [NF o₂], repr (o₁ * o₂) = repr o₁ * repr o₂
| 0 o h₁ h₂ := by cases o; exact (ordinal.zero_mul _).symm
| (oadd e₁ n₁ a₁) 0 h₁ h₂ := (ordinal.mul_zero _).symm
| (oadd e₁ n₁ a₁) (oadd e₂ n₂ a₂) h₁ h₂ := begin
have IH : repr (mul _ _) = _ := @repr_mul _ _ h₁ h₂.snd,
conv {to_lhs, simp [(*)]},
have ao : repr a₁ + ω ^ repr e₁ * (n₁:ℕ) = ω ^ repr e₁ * (n₁:ℕ),
{ apply add_absorp h₁.snd'.repr_lt,
simpa using (mul_le_mul_iff_left $ power_pos _ omega_pos).2
(nat_cast_le.2 n₁.2) },
by_cases e0 : e₂ = 0; simp [e0, mul],
{ cases nat.exists_eq_succ_of_ne_zero n₂.ne_zero with x xe,
simp [h₂.zero_of_zero e0, xe, -nat.cast_succ],
rw [← nat_cast_succ x, add_mul_succ _ ao, mul_assoc] },
{ haveI := h₁.fst, haveI := h₂.fst,
simp [IH, repr_add, power_add, ordinal.mul_add],
rw ← mul_assoc, congr' 2,
have := mt repr_inj.1 e0,
rw [add_mul_limit ao (power_is_limit_left omega_is_limit this),
mul_assoc, mul_omega_dvd (nat_cast_pos.2 n₁.pos) (nat_lt_omega _)],
simpa using power_dvd_power ω (one_le_iff_ne_zero.2 this) },
end
/-- Calculate division and remainder of `o` mod ω.
`split' o = (a, n)` means `o = ω * a + n`. -/
def split' : onote → onote × ℕ
| 0 := (0, 0)
| (oadd e n a) := if e = 0 then (0, n) else
let (a', m) := split' a in (oadd (e - 1) n a', m)
/-- Calculate division and remainder of `o` mod ω.
`split o = (a, n)` means `o = a + n`, where `ω ∣ a`. -/
def split : onote → onote × ℕ
| 0 := (0, 0)
| (oadd e n a) := if e = 0 then (0, n) else
let (a', m) := split a in (oadd e n a', m)
/-- `scale x o` is the ordinal notation for `ω ^ x * o`. -/
def scale (x : onote) : onote → onote
| 0 := 0
| (oadd e n a) := oadd (x + e) n (scale a)
/-- `mul_nat o n` is the ordinal notation for `o * n`. -/
def mul_nat : onote → ℕ → onote
| 0 m := 0
| _ 0 := 0
| (oadd e n a) (m+1) := oadd e (n * m.succ_pnat) a
def power_aux (e a0 a : onote) : ℕ → ℕ → onote
| _ 0 := 0
| 0 (m+1) := oadd e m.succ_pnat 0
| (k+1) m := scale (e + mul_nat a0 k) a + power_aux k m
/-- `power o₁ o₂` calculates the ordinal notation for
the ordinal exponential `o₁ ^ o₂`. -/
def power (o₁ o₂ : onote) : onote :=
match split o₁ with
| (0, 0) := if o₂ = 0 then 1 else 0
| (0, 1) := 1
| (0, m+1) := let (b', k) := split' o₂ in
oadd b' (@has_pow.pow ℕ+ _ _ m.succ_pnat k) 0
| (a@(oadd a0 _ _), m) := match split o₂ with
| (b, 0) := oadd (a0 * b) 1 0
| (b, k+1) := let eb := a0*b in
scale (eb + mul_nat a0 k) a + power_aux eb a0 (mul_nat a m) k m
end
end
instance : has_pow onote onote := ⟨power⟩
theorem power_def (o₁ o₂ : onote) : o₁ ^ o₂ = power._match_1 o₂ (split o₁) := rfl
theorem split_eq_scale_split' : ∀ {o o' m} [NF o], split' o = (o', m) → split o = (scale 1 o', m)
| 0 o' m h p := by injection p; substs o' m; refl
| (oadd e n a) o' m h p := begin
by_cases e0 : e = 0; simp [e0, split, split'] at p ⊢,
{ rcases p with ⟨rfl, rfl⟩, exact ⟨rfl, rfl⟩ },
{ revert p, cases h' : split' a with a' m',
haveI := h.fst, haveI := h.snd,
simp [split_eq_scale_split' h', split, split'],
have : 1 + (e - 1) = e,
{ refine repr_inj.1 _, simp,
have := mt repr_inj.1 e0,
exact add_sub_cancel_of_le (one_le_iff_ne_zero.2 this) },
intros, substs o' m, simp [scale, this] }
end
theorem NF_repr_split' : ∀ {o o' m} [NF o], split' o = (o', m) → NF o' ∧ repr o = ω * repr o' + m
| 0 o' m h p := by injection p; substs o' m; simp [NF.zero]
| (oadd e n a) o' m h p := begin
by_cases e0 : e = 0; simp [e0, split, split'] at p ⊢,
{ rcases p with ⟨rfl, rfl⟩,
simp [h.zero_of_zero e0, NF.zero] },
{ revert p, cases h' : split' a with a' m',
haveI := h.fst, haveI := h.snd,
cases NF_repr_split' h' with IH₁ IH₂,
simp [IH₂, split'],
intros, substs o' m,
have : ω ^ repr e = ω ^ (1 : ordinal.{0}) * ω ^ (repr e - 1),
{ have := mt repr_inj.1 e0,
rw [← power_add, add_sub_cancel_of_le (one_le_iff_ne_zero.2 this)] },
refine ⟨NF.oadd (by apply_instance) _ _, _⟩,
{ simp at this ⊢,
refine IH₁.below_of_lt' ((mul_lt_mul_iff_left omega_pos).1 $
lt_of_le_of_lt (le_add_right _ m') _),
rw [← this, ← IH₂], exact h.snd'.repr_lt },
{ rw this, simp [ordinal.mul_add, mul_assoc] } }
end
theorem scale_eq_mul (x) [NF x] : ∀ o [NF o], scale x o = oadd x 1 0 * o
| 0 h := rfl
| (oadd e n a) h := begin
simp [(*)], simp [mul, scale],
haveI := h.snd,
by_cases e0 : e = 0,
{ rw scale_eq_mul, simp [e0, h.zero_of_zero, show x + 0 = x, from repr_inj.1 (by simp)] },
{ simp [e0, scale_eq_mul, (*)] }
end
instance NF_scale (x) [NF x] (o) [NF o] : NF (scale x o) :=
by rw scale_eq_mul; apply_instance
@[simp] theorem repr_scale (x) [NF x] (o) [NF o] : repr (scale x o) = ω ^ repr x * repr o :=
by simp [scale_eq_mul]
theorem NF_repr_split {o o' m} [NF o] (h : split o = (o', m)) : NF o' ∧ repr o = repr o' + m :=
begin
cases e : split' o with a n,
cases NF_repr_split' e with s₁ s₂, resetI,
rw split_eq_scale_split' e at h,
injection h, substs o' n,
simp [repr_scale, s₂.symm],
apply_instance
end
theorem split_dvd {o o' m} [NF o] (h : split o = (o', m)) : ω ∣ repr o' :=
begin
cases e : split' o with a n,
rw split_eq_scale_split' e at h,
injection h, subst o',
cases NF_repr_split' e, resetI, simp [dvd_mul]
end
theorem split_add_lt {o e n a m} [NF o] (h : split o = (oadd e n a, m)) : repr a + m < ω ^ repr e :=
begin
cases NF_repr_split h with h₁ h₂,
cases h₁.of_dvd_omega (split_dvd h) with e0 d,
have := h₁.fst, have := h₁.snd,
refine add_lt_omega_power h₁.snd'.repr_lt (lt_of_lt_of_le (nat_lt_omega _) _),
simpa using power_le_power_right omega_pos (one_le_iff_ne_zero.2 e0),
end
@[simp] theorem mul_nat_eq_mul (n o) : mul_nat o n = o * of_nat n :=
by cases o; cases n; refl
instance NF_mul_nat (o) [NF o] (n) : NF (mul_nat o n) :=
by simp; apply_instance
instance NF_power_aux (e a0 a) [NF e] [NF a0] [NF a] : ∀ k m, NF (power_aux e a0 a k m)
| k 0 := by cases k; exact NF.zero
| 0 (m+1) := NF.oadd_zero _ _
| (k+1) (m+1) := by haveI := NF_power_aux k;
simp [power_aux, nat.succ_ne_zero]; apply_instance
instance NF_power (o₁ o₂) [NF o₁] [NF o₂] : NF (o₁ ^ o₂) :=
begin
cases e₁ : split o₁ with a m,
have na := (NF_repr_split e₁).1,
cases e₂ : split' o₂ with b' k,
haveI := (NF_repr_split' e₂).1,
cases a with a0 n a',
{ cases m with m,
{ by_cases o₂ = 0; simp [pow, power, e₁, h]; apply_instance },
{ by_cases m = 0; simp [pow, power, e₁, e₂, h]; apply_instance } },
{ simp [pow, power, e₁, e₂, split_eq_scale_split' e₂],
have := na.fst,
cases k with k; simp [succ_eq_add_one, power]; apply_instance }
end
theorem scale_power_aux (e a0 a : onote) [NF e] [NF a0] [NF a] :
∀ k m, repr (power_aux e a0 a k m) = ω ^ repr e * repr (power_aux 0 a0 a k m)
| 0 m := by cases m; simp [power_aux]
| (k+1) m := by by_cases m = 0; simp [h, power_aux,
ordinal.mul_add, power_add, mul_assoc, scale_power_aux]
theorem repr_power_aux₁ {e a} [Ne : NF e] [Na : NF a] {a' : ordinal}
(e0 : repr e ≠ 0) (h : a' < ω ^ repr e) (aa : repr a = a') (n : ℕ+) :
(ω ^ repr e * (n:ℕ) + a') ^ ω = (ω ^ repr e) ^ ω :=
begin
subst aa,
have No := Ne.oadd n (Na.below_of_lt' h),
have := omega_le_oadd e n a, unfold repr at this,
refine le_antisymm _ (power_le_power_left _ this),
apply (power_le_of_limit
(ne_of_gt $ lt_of_lt_of_le (power_pos _ omega_pos) this) omega_is_limit).2,
intros b l,
have := (No.below_of_lt (lt_succ_self _)).repr_lt, unfold repr at this,
apply le_trans (power_le_power_left b $ le_of_lt this),
rw [← power_mul, ← power_mul],
apply power_le_power_right omega_pos,
cases le_or_lt ω (repr e) with h h,
{ apply le_trans (mul_le_mul_left _ $ le_of_lt $ lt_succ_self _),
rw [succ, add_mul_succ _ (one_add_of_omega_le h), ← succ,
succ_le, mul_lt_mul_iff_left (pos_iff_ne_zero.2 e0)],
exact omega_is_limit.2 _ l },
{ refine le_trans (le_of_lt $ mul_lt_omega (omega_is_limit.2 _ h) l) _,
simpa using mul_le_mul_right ω (one_le_iff_ne_zero.2 e0) }
end
section
local infixr ^ := @pow ordinal.{0} ordinal ordinal.has_pow
theorem repr_power_aux₂ {a0 a'} [N0 : NF a0] [Na' : NF a'] (m : ℕ)
(d : ω ∣ repr a')
(e0 : repr a0 ≠ 0) (h : repr a' + m < ω ^ repr a0) (n : ℕ+) (k : ℕ) :
let R := repr (power_aux 0 a0 (oadd a0 n a' * of_nat m) k m) in
(k ≠ 0 → R < (ω ^ repr a0) ^ succ k) ∧
(ω ^ repr a0) ^ k * (ω ^ repr a0 * (n:ℕ) + repr a') + R =
(ω ^ repr a0 * (n:ℕ) + repr a' + m) ^ succ k :=
begin
intro,
haveI No : NF (oadd a0 n a') :=
N0.oadd n (Na'.below_of_lt' $ lt_of_le_of_lt (le_add_right _ _) h),
induction k with k IH, {cases m; simp [power_aux, R]},
rename R R', let R := repr (power_aux 0 a0 (oadd a0 n a' * of_nat m) k m),
let ω0 := ω ^ repr a0, let α' := ω0 * n + repr a',
change (k ≠ 0 → R < ω0 ^ succ k) ∧ ω0 ^ k * α' + R = (α' + m) ^ succ k at IH,
have RR : R' = ω0 ^ k * (α' * m) + R,
{ by_cases m = 0; simp [h, R', power_aux, R, power_mul],
{ cases k; simp [power_aux] }, { refl } },
have α0 : 0 < α', {simpa [α', lt_def, repr] using oadd_pos a0 n a'},
have ω00 : 0 < ω0 ^ k := power_pos _ (power_pos _ omega_pos),
have Rl : R < ω ^ (repr a0 * succ ↑k),
{ by_cases k0 : k = 0,
{ simp [k0],
refine lt_of_lt_of_le _ (power_le_power_right omega_pos (one_le_iff_ne_zero.2 e0)),
cases m with m; simp [k0, R, power_aux, omega_pos],
rw [← nat.cast_succ], apply nat_lt_omega },
{ rw power_mul, exact IH.1 k0 } },
refine ⟨λ_, _, _⟩,
{ rw [RR, ← power_mul _ _ (succ k.succ)],
have e0 := pos_iff_ne_zero.2 e0,
have rr0 := lt_of_lt_of_le e0 (le_add_left _ _),
apply add_lt_omega_power,
{ simp [power_mul, ω0, power_add],
rw [mul_lt_mul_iff_left ω00, ← ordinal.power_add],
have := (No.below_of_lt _).repr_lt, unfold repr at this,
refine mul_lt_omega_power rr0 this (nat_lt_omega _),
simpa using (add_lt_add_iff_left (repr a0)).2 e0 },
{ refine lt_of_lt_of_le Rl (power_le_power_right omega_pos $
mul_le_mul_left _ $ succ_le_succ.2 $ nat_cast_le.2 $ le_of_lt k.lt_succ_self) } },
refine calc
ω0 ^ k.succ * α' + R'
= ω0 ^ succ k * α' + (ω0 ^ k * α' * m + R) : by rw [nat_cast_succ, RR, ← mul_assoc]
... = (ω0 ^ k * α' + R) * α' + (ω0 ^ k * α' + R) * m : _
... = (α' + m) ^ succ k.succ : by rw [← ordinal.mul_add, ← nat_cast_succ, power_succ, IH.2],
congr' 1,
{ have αd : ω ∣ α' := dvd_add (dvd_mul_of_dvd _
(by simpa using power_dvd_power ω (one_le_iff_ne_zero.2 e0))) d,
rw [ordinal.mul_add (ω0 ^ k), add_assoc, ← mul_assoc, ← power_succ,
add_mul_limit _ (is_limit_iff_omega_dvd.2 ⟨ne_of_gt α0, αd⟩), mul_assoc,
@mul_omega_dvd n (nat_cast_pos.2 n.pos) (nat_lt_omega _) _ αd],
apply @add_absorp _ (repr a0 * succ k),
{ refine add_lt_omega_power _ Rl,
rw [power_mul, power_succ, mul_lt_mul_iff_left ω00],
exact No.snd'.repr_lt },
{ have := mul_le_mul_left (ω0 ^ succ k) (one_le_iff_pos.2 $ nat_cast_pos.2 n.pos),
rw power_mul, simpa [-power_succ] } },
{ cases m,
{ have : R = 0, {cases k; simp [R, power_aux]}, simp [this] },
{ rw [← nat_cast_succ, add_mul_succ],
apply add_absorp Rl,
rw [power_mul, power_succ],
apply ordinal.mul_le_mul_left,
simpa [α', repr] using omega_le_oadd a0 n a' } }
end
end
theorem repr_power (o₁ o₂) [NF o₁] [NF o₂] : repr (o₁ ^ o₂) = repr o₁ ^ repr o₂ :=
begin
cases e₁ : split o₁ with a m,
cases NF_repr_split e₁ with N₁ r₁,
cases a with a0 n a',
{ cases m with m,
{ by_cases o₂ = 0; simp [power_def, power, e₁, h, r₁],
have := mt repr_inj.1 h, rw zero_power this },
{ cases e₂ : split' o₂ with b' k,
cases NF_repr_split' e₂ with _ r₂,
by_cases m = 0; simp [power_def, power, e₁, h, r₁, e₂, r₂, -nat.cast_succ],
rw [power_add, power_mul, power_omega _ (nat_lt_omega _)],
simpa using nat_cast_lt.2 (nat.succ_lt_succ $ nat.pos_iff_ne_zero.2 h) } },
{ haveI := N₁.fst, haveI := N₁.snd,
cases N₁.of_dvd_omega (split_dvd e₁) with a00 ad,
have al := split_add_lt e₁,
have aa : repr (a' + of_nat m) = repr a' + m, {simp},
cases e₂ : split' o₂ with b' k,
cases NF_repr_split' e₂ with _ r₂,
simp [power_def, power, e₁, r₁, split_eq_scale_split' e₂],
cases k with k,
{ simp [power, r₂, power_mul, repr_power_aux₁ a00 al aa] },
{ simp [succ_eq_add_one, power, r₂, power_add, power_mul, mul_assoc],
rw [repr_power_aux₁ a00 al aa, scale_power_aux], simp [power_mul],
rw [← ordinal.mul_add, ← add_assoc (ω ^ repr a0 * (n:ℕ))], congr' 1,
rw [← power_succ],
exact (repr_power_aux₂ _ ad a00 al _ _).2 } }
end
end onote
/-- The type of normal ordinal notations. (It would have been
nicer to define this right in the inductive type, but `NF o`
requires `repr` which requires `onote`, so all these things
would have to be defined at once, which messes up the VM
representation.) -/
def nonote := {o : onote // o.NF}
instance : decidable_eq nonote := by unfold nonote; apply_instance
namespace nonote
open onote
instance NF (o : nonote) : NF o.1 := o.2
/-- Construct a `nonote` from an ordinal notation
(and infer normality) -/
def mk (o : onote) [h : NF o] : nonote := ⟨o, h⟩
/-- The ordinal represented by an ordinal notation.
(This function is noncomputable because ordinal
arithmetic is noncomputable. In computational applications
`nonote` can be used exclusively without reference
to `ordinal`, but this function allows for correctness
results to be stated.) -/
noncomputable def repr (o : nonote) : ordinal := o.1.repr
instance : has_to_string nonote := ⟨λ x, x.1.to_string⟩
instance : has_repr nonote := ⟨λ x, x.1.repr'⟩
instance : preorder nonote :=
{ le := λ x y, repr x ≤ repr y,
lt := λ x y, repr x < repr y,
le_refl := λ a, @le_refl ordinal _ _,
le_trans := λ a b c, @le_trans ordinal _ _ _ _,
lt_iff_le_not_le := λ a b, @lt_iff_le_not_le ordinal _ _ _ }
instance : has_zero nonote := ⟨⟨0, NF.zero⟩⟩
instance : inhabited nonote := ⟨0⟩
/-- Convert a natural number to an ordinal notation -/
def of_nat (n : ℕ) : nonote := ⟨of_nat n, _, NF_below_of_nat _⟩
/-- Compare ordinal notations -/
def cmp (a b : nonote) : ordering :=
cmp a.1 b.1
theorem cmp_compares : ∀ a b : nonote, (cmp a b).compares a b
| ⟨a, ha⟩ ⟨b, hb⟩ := begin
resetI,
dsimp [cmp], have := onote.cmp_compares a b,
cases onote.cmp a b; try {exact this},
exact subtype.mk_eq_mk.2 this
end
instance : linear_order nonote :=
{ le_antisymm := λ a b, match cmp a b, cmp_compares a b with
| ordering.lt, h, h₁, h₂ := (not_lt_of_le h₂).elim h
| ordering.eq, h, h₁, h₂ := h
| ordering.gt, h, h₁, h₂ := (not_lt_of_le h₁).elim h
end,
le_total := λ a b, match cmp a b, cmp_compares a b with
| ordering.lt, h := or.inl (le_of_lt h)
| ordering.eq, h := or.inl (le_of_eq h)
| ordering.gt, h := or.inr (le_of_lt h)
end,
..nonote.preorder }
instance decidable_lt : @decidable_rel nonote (<)
| a b := decidable_of_iff _ (cmp_compares a b).eq_lt
instance : decidable_linear_order nonote :=
{ decidable_le := λ a b, decidable_of_iff _ not_lt,
decidable_lt := nonote.decidable_lt,
..nonote.linear_order }
/-- Asserts that `repr a < ω ^ repr b`. Used in `nonote.rec_on` -/
def below (a b : nonote) : Prop := NF_below a.1 (repr b)
/-- The `oadd` pseudo-constructor for `nonote` -/
def oadd (e : nonote) (n : ℕ+) (a : nonote) (h : below a e) : nonote := ⟨_, NF.oadd e.2 n h⟩
/-- This is a recursor-like theorem for `nonote` suggesting an
inductive definition, which can't actually be defined this
way due to conflicting dependencies. -/
@[elab_as_eliminator] def rec_on {C : nonote → Sort*} (o : nonote)
(H0 : C 0)
(H1 : ∀ e n a h, C e → C a → C (oadd e n a h)) : C o :=
begin
cases o with o h, induction o with e n a IHe IHa,
{ exact H0 },
{ exact H1 ⟨e, h.fst⟩ n ⟨a, h.snd⟩ h.snd' (IHe _) (IHa _) }
end
/-- Addition of ordinal notations -/
instance : has_add nonote := ⟨λ x y, mk (x.1 + y.1)⟩
theorem repr_add (a b) : repr (a + b) = repr a + repr b :=
onote.repr_add a.1 b.1
/-- Subtraction of ordinal notations -/
instance : has_sub nonote := ⟨λ x y, mk (x.1 - y.1)⟩
theorem repr_sub (a b) : repr (a - b) = repr a - repr b :=
onote.repr_sub a.1 b.1
/-- Multiplication of ordinal notations -/
instance : has_mul nonote := ⟨λ x y, mk (x.1 * y.1)⟩
theorem repr_mul (a b) : repr (a * b) = repr a * repr b :=
onote.repr_mul a.1 b.1
/-- Exponentiation of ordinal notations -/
def power (x y : nonote) := mk (x.1.power y.1)
theorem repr_power (a b) : repr (power a b) = (repr a).power (repr b) :=
onote.repr_power a.1 b.1
end nonote
|
8b27522f5c8d1c0f07f0c7e56109291b90d7cbee | 297c4ceafbbaed2a59b6215504d09e6bf201a2ee | /finite.lean | 8a73a727a6d6581c3798ca2a00bd894fb9314be2 | [] | 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 | 10,651 | lean | import .finset.to_set
open nat classical
variable {A : Type}
noncomputable instance type_decidable_eq (A : Type) : decidable_eq A :=
λ a b, prop_decidable (a = b)
namespace set
attribute [class]
definition finite (s : set A) : Prop := ∃ (s' : finset A), s = finset.to_set s'
attribute [instance]
definition finite_finset (s : finset A) : finite (finset.to_set s) :=
exists.intro s rfl
noncomputable instance dec_finite (s : set A) : decidable (finite s) := prop_decidable (finite s)
noncomputable definition to_finset (s : set A) : finset A :=
if fins : finite s then some fins else finset.empty
theorem to_finset_of_not_finite {s : set A} (nfins : ¬ finite s) : to_finset s = finset.empty :=
dif_neg nfins
theorem to_set_to_finset (s : set A) [fins : finite s] : finset.to_set (to_finset s) = s :=
have to_finset s = some fins, from dif_pos fins,
by rw this; exact eq.symm (some_spec fins)
theorem mem_to_finset_eq (a : A) (s : set A) [finite s] :
(finset.mem a (to_finset s)) = (a ∈ s) :=
have (finset.mem a (to_finset s)) = (a ∈ (finset.to_set (to_finset s))), from rfl,
begin rw this, rw [to_set_to_finset] end
theorem to_set_to_finset_of_not_finite {s : set A} (nfins : ¬ finite s) :
finset.to_set (to_finset s) = ∅ :=
have to_finset s = finset.empty, from to_finset_of_not_finite nfins,
begin rw this, reflexivity end
theorem to_finset_to_set (s : finset A) : to_finset (finset.to_set s) = s :=
begin rw finset.eq_eq_to_set_eq, rw to_set_to_finset end
theorem to_finset_eq_of_to_set_eq {s : set A} {t : finset A} (H : finset.to_set t = s) :
to_finset s = t :=
finset.eq_of_to_set_eq_to_set (begin rw -H, rw to_finset_to_set end)
theorem finite_of_to_set_to_finset_eq {s : set A} (H : finset.to_set (to_finset s) = s) :
finite s :=
by rewrite -H; apply finite_finset
attribute [instance]
theorem finite_empty : finite (∅ : set A) :=
by rewrite [-finset.to_set_empty]; apply finite_finset
theorem to_finset_empty : to_finset (∅ : set A) = finset.empty :=
to_finset_eq_of_to_set_eq finset.to_set_empty
theorem to_finset_eq_empty_of_eq_empty {s : set A} [fins : finite s] (H : s = ∅) :
to_finset s = finset.empty := by rewrite [H, to_finset_empty]
theorem eq_empty_of_to_finset_eq_empty {s : set A} [fins : finite s]
(H : to_finset s = finset.empty) :
s = ∅ := by rewrite [-finset.to_set_empty, -H, to_set_to_finset]
theorem to_finset_eq_empty (s : set A) [fins : finite s] :
(to_finset s = finset.empty) ↔ (s = ∅) :=
iff.intro eq_empty_of_to_finset_eq_empty to_finset_eq_empty_of_eq_empty
attribute [instance]
theorem finite_insert (a : A) (s : set A) [finite s] : finite (set.insert a s) :=
exists.intro (finset.insert a (to_finset s))
(by rw [-(to_set_to_finset s), finset.to_set_insert, to_finset_to_set])
theorem to_finset_insert (a : A) (s : set A) [finite s] :
to_finset (insert a s) = finset.insert a (to_finset s) :=
begin apply to_finset_eq_of_to_set_eq,
rw [-finset.to_set_insert, to_set_to_finset], reflexivity end
attribute [instance]
theorem finite_union (s t : set A) [finite s] [finite t] :
finite (s ∪ t) :=
exists.intro (to_finset s ∪ to_finset t)
(by rewrite [finset.to_set_union]; repeat {rw to_set_to_finset})
theorem to_finset_union (s t : set A) [finite s] [finite t] :
to_finset (s ∪ t) = (to_finset s ∪ to_finset t) :=
by apply to_finset_eq_of_to_set_eq; rw [finset.to_set_union]; repeat {rw to_set_to_finset}
attribute [instance]
theorem finite_inter (s t : set A) [finite s] [finite t] :
finite (s ∩ t) :=
exists.intro (to_finset s ∩ to_finset t)
(by rw [finset.to_set_inter]; repeat {rw to_set_to_finset})
theorem to_finset_inter (s t : set A) [finite s] [finite t] :
to_finset (s ∩ t) = (to_finset s ∩ to_finset t) :=
by apply to_finset_eq_of_to_set_eq; rw [finset.to_set_inter]; repeat {rw to_set_to_finset}
noncomputable instance dec_prop (p : Prop) : decidable p := prop_decidable p
attribute [instance]
theorem finite_sep (s : set A) (p : A → Prop) [finite s] :
finite {x ∈ s | p x} :=
exists.intro (finset.sep p (to_finset s))
(by rw [finset.to_set_sep]; rw to_set_to_finset; reflexivity)
theorem to_finset_sep (s : set A) (p : A → Prop) [finite s] :
to_finset {x ∈ s | p x} = finset.sep p (to_finset s) :=
begin apply to_finset_eq_of_to_set_eq; rewrite [finset.to_set_sep, to_set_to_finset], reflexivity end
attribute [instance]
theorem finite_image {B : Type} (f : A → B) (s : set A) [finite s] :
finite (image f s) :=
exists.intro (finset.image f (to_finset s))
(begin rw [finset.to_set_image]; repeat {rw to_set_to_finset} end)
theorem to_finset_image {B : Type} (f : A → B) (s : set A)
[fins : finite s] :
to_finset (image f s) = (finset.image f (to_finset s)) :=
by apply to_finset_eq_of_to_set_eq; rewrite [finset.to_set_image, to_set_to_finset]
attribute [instance]
theorem finite_diff (s t : set A) [finite s] : finite (s \ t) :=
finite_sep _ _
theorem to_finset_diff (s t : set A) [finite s] [finite t] :
to_finset (s \ t) = (to_finset s \ to_finset t) :=
by apply to_finset_eq_of_to_set_eq; rw [finset.to_set_diff]; repeat {rw to_set_to_finset}
theorem finite_subset {s t : set A} [finite t] (ssubt : s ⊆ t) : finite s :=
by rewrite (eq_sep_of_subset ssubt); apply finite_sep
theorem to_finset_subset_to_finset_eq (s t : set A) [finite s] [finite t] :
(to_finset s ⊆ to_finset t) = (s ⊆ t) :=
by rw [finset.subset_eq_to_set_subset]; repeat {rw to_set_to_finset}
theorem finite_of_finite_insert {s : set A} {a : A} (finias : finite (insert a s)) : finite s :=
finite_subset (subset_insert a s)
attribute [instance]
theorem finite_upto (n : ℕ) : finite {i | i < n} :=
by rewrite [-finset.to_set_upto n]; apply finite_finset
theorem to_finset_upto (n : ℕ) : to_finset {i | i < n} = finset.upto n :=
by apply (to_finset_eq_of_to_set_eq (finset.to_set_upto _))
theorem finite_of_surj_on {B : Type} {f : A → B} {s : set A} [finite s] {t : set B}
(H : surj_on f s t) :
finite t :=
finite_subset H
section
-- classical inverse
open classical
variables {X Y : Type}
noncomputable definition inv_fun (f : X → Y) (a : set X) (dflt : X) (y : Y) : X :=
if H : ∃ x, x ∈ a ∧ f x = y then some H else dflt
theorem inv_fun_pos {f : X → Y} {a : set X} {dflt : X} {y : Y}
(H : ∃ x, x ∈ a ∧ f x = y) : (inv_fun f a dflt y ∈ a) ∧ (f (inv_fun f a dflt y) = y) :=
have H1 : inv_fun f a dflt y = some H, from dif_pos H,
let ⟨x,ina⟩ := some_spec H in
⟨by rw H1; assumption,by rw H1; assumption⟩
theorem inv_fun_neg {f : X → Y} {a : set X} {dflt : X} {y : Y}
(H : ¬ ∃ x, x ∈ a ∧ f x = y) : inv_fun f a dflt y = dflt :=
dif_neg H
variables {f : X → Y} {a : set X} {b : set Y}
theorem maps_to_inv_fun {dflt : X} (dflta : dflt ∈ a) :
maps_to (inv_fun f a dflt) b a :=
let f' := inv_fun f a dflt in
take y,
assume yb : y ∈ b,
show f' y ∈ a, from
by_cases
(assume H : ∃ x, x ∈ a ∧ f x = y,
and.left (inv_fun_pos H))
(assume H : ¬ ∃x, x ∈ a ∧ f x = y,
begin dsimp, rw (inv_fun_neg H), assumption end)
theorem left_inv_on_inv_fun_of_inj_on (dflt : X) (H : inj_on f a) :
left_inv_on (inv_fun f a dflt) f a :=
let f' := inv_fun f a dflt in
take x,
assume xa : x ∈ a,
have H1 : ∃ x', x' ∈ a ∧ f x' = f x, from ⟨x,xa,rfl⟩,
have H2 : f' (f x) ∈ a ∧ f (f' (f x)) = f x, from inv_fun_pos H1,
show f' (f x) = x, from H (and.left H2) xa (and.right H2)
theorem surj_on_inv_fun_of_inj_on (dflt : X) (mapsto : maps_to f a b) (H : inj_on f a) :
surj_on (inv_fun f a dflt) b a :=
surj_on_of_right_inv_on mapsto (left_inv_on_inv_fun_of_inj_on dflt H)
end
theorem finite_of_inj_on {B : Type} {f : A → B} {s : set A} {t : set B} [finite t]
(mapsto : maps_to f s t) (injf : inj_on f s) :
finite s :=
if H : s = ∅ then
begin rewrite H; apply _, apply finite_empty end
else
let ⟨dflt,xs⟩ := exists_mem_of_ne_empty H in
let finv := inv_fun f s dflt in
have surj_on finv t s, from surj_on_inv_fun_of_inj_on dflt mapsto injf,
finite_of_surj_on this
-- theorem finite_of_bij_on {B : Type} {f : A → B} {s : set A} {t : set B} [finite s]
-- (bijf : bij_on f s t) :
-- finite t :=
-- finite_of_surj_on (surj_on_of_bij_on bijf)
-- theorem finite_of_bij_on' {B : Type} {f : A → B} {s : set A} {t : set B} [finite t]
-- (bijf : bij_on f s t) :
-- finite s :=
-- finite_of_inj_on (maps_to_of_bij_on bijf) (inj_on_of_bij_on bijf)
-- theorem finite_iff_finite_of_bij_on {B : Type} {f : A → B} {s : set A} {t : set B}
-- (bijf : bij_on f s t) :
-- finite s ↔ finite t :=
-- iff.intro (assume fs, finite_of_bij_on bijf) (assume ft, finite_of_bij_on' bijf)
-- theorem finite_powerset (s : set A) [finite s] : finite 𝒫 s :=
-- have H : 𝒫 s = finset.to_set ' (finset.to_set (#finset 𝒫 (to_finset s))),
-- from ext (take t, iff.intro
-- (suppose t ∈ 𝒫 s,
-- have t ⊆ s, from this,
-- have finite t, from finite_subset this,
-- have (#finset to_finset t ∈ 𝒫 (to_finset s)),
-- by rewrite [finset.mem_powerset_iff_subset, to_finset_subset_to_finset_eq]; apply `t ⊆ s`,
-- have to_finset t ∈ (finset.to_set (finset.powerset (to_finset s))), from this,
-- mem_image this (by rewrite to_set_to_finset))
-- (assume H',
-- obtain t' [(tmem : (#finset t' ∈ 𝒫 (to_finset s))) (teq : finset.to_set t' = t)],
-- from H',
-- show t ⊆ s,
-- begin
-- rewrite [-teq, finset.mem_powerset_iff_subset at tmem, -to_set_to_finset s],
-- rewrite -finset.subset_eq_to_set_subset, assumption
-- end)),
-- by rewrite H; apply finite_image
/- induction for finite sets -/
attribute [recursor 6]
theorem induction_finite {P : set A → Prop}
(H1 : P ∅) (H2 : ∀ ⦃a : A⦄, ∀ {s : set A} [finite s], a ∉ s → P s → P (insert a s)) :
∀ (s : set A) [finite s], P s :=
(λ s fins,
have ∀ s' : finset A, P (finset.to_set s'), from
λ s', @finset.induction_on _ _ (λ x, P (finset.to_set x)) s'
(by rw finset.to_set_empty; exact H1)
(begin
intros a s' anin ih,
rw [-finset.to_set_insert], apply H2,
{rw [-finset.mem_eq_mem_to_set], exact anin},
{exact ih}
end),
begin rw [-to_set_to_finset s], exact (this (to_finset s)) end)
theorem induction_on_finite {P : set A → Prop} (s : set A) [finite s]
(H1 : P ∅) (H2 : ∀ ⦃a : A⦄, ∀ {s : set A} [finite s], a ∉ s → P s → P (insert a s)) :
P s :=
induction_finite H1 H2 s
end set
|
d8badc37e3f98099f7e5423829e6fae6485fbe1b | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/data/real/sqrt.lean | 2ba270b9a13950acd9cdc9f54eec7bef84a9dd6c | [
"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,417 | lean | /-
Copyright (c) 2020 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Floris van Doorn, Yury Kudryashov
-/
import topology.algebra.order.monotone_continuity
import topology.instances.nnreal
import tactic.positivity
/-!
# Square root of a real number
In this file we define
* `nnreal.sqrt` to be the square root of a nonnegative real number.
* `real.sqrt` to be the square root of a real number, defined to be zero on negative numbers.
Then we prove some basic properties of these functions.
## Implementation notes
We define `nnreal.sqrt` as the noncomputable inverse to the function `x ↦ x * x`. We use general
theory of inverses of strictly monotone functions to prove that `nnreal.sqrt x` exists. As a side
effect, `nnreal.sqrt` is a bundled `order_iso`, so for `nnreal` numbers we get continuity as well as
theorems like `sqrt x ≤ y ↔ x ≤ y * y` for free.
Then we define `real.sqrt x` to be `nnreal.sqrt (real.to_nnreal x)`. We also define a Cauchy
sequence `real.sqrt_aux (f : cau_seq ℚ abs)` which converges to `sqrt (mk f)` but do not prove (yet)
that this sequence actually converges to `sqrt (mk f)`.
## Tags
square root
-/
open set filter
open_locale filter nnreal topological_space
namespace nnreal
variables {x y : ℝ≥0}
/-- Square root of a nonnegative real number. -/
@[pp_nodot] noncomputable def sqrt : ℝ≥0 ≃o ℝ≥0 :=
order_iso.symm $ pow_order_iso 2 two_ne_zero
lemma sqrt_le_sqrt_iff : sqrt x ≤ sqrt y ↔ x ≤ y :=
sqrt.le_iff_le
lemma sqrt_lt_sqrt_iff : sqrt x < sqrt y ↔ x < y :=
sqrt.lt_iff_lt
lemma sqrt_eq_iff_sq_eq : sqrt x = y ↔ y ^ 2 = x :=
sqrt.to_equiv.apply_eq_iff_eq_symm_apply.trans eq_comm
lemma sqrt_le_iff : sqrt x ≤ y ↔ x ≤ y ^ 2 :=
sqrt.to_galois_connection _ _
lemma le_sqrt_iff : x ≤ sqrt y ↔ x ^ 2 ≤ y :=
(sqrt.symm.to_galois_connection _ _).symm
@[simp] lemma sqrt_eq_zero : sqrt x = 0 ↔ x = 0 :=
sqrt_eq_iff_sq_eq.trans $ by rw [eq_comm, sq, zero_mul]
@[simp] lemma sqrt_zero : sqrt 0 = 0 := sqrt_eq_zero.2 rfl
@[simp] lemma sqrt_one : sqrt 1 = 1 := sqrt_eq_iff_sq_eq.2 $ one_pow _
@[simp] lemma sq_sqrt (x : ℝ≥0) : (sqrt x)^2 = x := sqrt.symm_apply_apply x
@[simp] lemma mul_self_sqrt (x : ℝ≥0) : sqrt x * sqrt x = x := by rw [← sq, sq_sqrt]
@[simp] lemma sqrt_sq (x : ℝ≥0) : sqrt (x^2) = x := sqrt.apply_symm_apply x
@[simp] lemma sqrt_mul_self (x : ℝ≥0) : sqrt (x * x) = x := by rw [← sq, sqrt_sq x]
lemma sqrt_mul (x y : ℝ≥0) : sqrt (x * y) = sqrt x * sqrt y :=
by rw [sqrt_eq_iff_sq_eq, mul_pow, sq_sqrt, sq_sqrt]
/-- `nnreal.sqrt` as a `monoid_with_zero_hom`. -/
noncomputable def sqrt_hom : ℝ≥0 →*₀ ℝ≥0 := ⟨sqrt, sqrt_zero, sqrt_one, sqrt_mul⟩
lemma sqrt_inv (x : ℝ≥0) : sqrt (x⁻¹) = (sqrt x)⁻¹ := map_inv₀ sqrt_hom x
lemma sqrt_div (x y : ℝ≥0) : sqrt (x / y) = sqrt x / sqrt y := map_div₀ sqrt_hom x y
lemma continuous_sqrt : continuous sqrt := sqrt.continuous
end nnreal
namespace real
/-- An auxiliary sequence of rational numbers that converges to `real.sqrt (mk f)`.
Currently this sequence is not used in `mathlib`. -/
def sqrt_aux (f : cau_seq ℚ abs) : ℕ → ℚ
| 0 := rat.mk_nat (f 0).num.to_nat.sqrt (f 0).denom.sqrt
| (n + 1) := let s := sqrt_aux n in max 0 $ (s + f (n+1) / s) / 2
theorem sqrt_aux_nonneg (f : cau_seq ℚ abs) : ∀ i : ℕ, 0 ≤ sqrt_aux f i
| 0 := by rw [sqrt_aux, rat.mk_nat_eq, rat.mk_eq_div];
apply div_nonneg; exact int.cast_nonneg.2 (int.of_nat_nonneg _)
| (n + 1) := le_max_left _ _
/- TODO(Mario): finish the proof
theorem sqrt_aux_converges (f : cau_seq ℚ abs) : ∃ h x, 0 ≤ x ∧ x * x = max 0 (mk f) ∧
mk ⟨sqrt_aux f, h⟩ = x :=
begin
rcases sqrt_exists (le_max_left 0 (mk f)) with ⟨x, x0, hx⟩,
suffices : ∃ h, mk ⟨sqrt_aux f, h⟩ = x,
{ exact this.imp (λ h e, ⟨x, x0, hx, e⟩) },
apply of_near,
rsuffices ⟨δ, δ0, hδ⟩ : ∃ δ > 0, ∀ i, abs (↑(sqrt_aux f i) - x) < δ / 2 ^ i,
{ intros }
end -/
/-- The square root of a real number. This returns 0 for negative inputs. -/
@[pp_nodot] noncomputable def sqrt (x : ℝ) : ℝ :=
nnreal.sqrt (real.to_nnreal x)
/-quotient.lift_on x
(λ f, mk ⟨sqrt_aux f, (sqrt_aux_converges f).fst⟩)
(λ f g e, begin
rcases sqrt_aux_converges f with ⟨hf, x, x0, xf, xs⟩,
rcases sqrt_aux_converges g with ⟨hg, y, y0, yg, ys⟩,
refine xs.trans (eq.trans _ ys.symm),
rw [← @mul_self_inj_of_nonneg ℝ _ x y x0 y0, xf, yg],
congr' 1, exact quotient.sound e
end)-/
variables {x y : ℝ}
@[simp, norm_cast] lemma coe_sqrt {x : ℝ≥0} : (nnreal.sqrt x : ℝ) = real.sqrt x :=
by rw [real.sqrt, real.to_nnreal_coe]
@[continuity]
lemma continuous_sqrt : continuous sqrt :=
nnreal.continuous_coe.comp $ nnreal.sqrt.continuous.comp continuous_real_to_nnreal
theorem sqrt_eq_zero_of_nonpos (h : x ≤ 0) : sqrt x = 0 :=
by simp [sqrt, real.to_nnreal_eq_zero.2 h]
theorem sqrt_nonneg (x : ℝ) : 0 ≤ sqrt x := nnreal.coe_nonneg _
@[simp] theorem mul_self_sqrt (h : 0 ≤ x) : sqrt x * sqrt x = x :=
by rw [sqrt, ← nnreal.coe_mul, nnreal.mul_self_sqrt, real.coe_to_nnreal _ h]
@[simp] theorem sqrt_mul_self (h : 0 ≤ x) : sqrt (x * x) = x :=
(mul_self_inj_of_nonneg (sqrt_nonneg _) h).1 (mul_self_sqrt (mul_self_nonneg _))
theorem sqrt_eq_cases : sqrt x = y ↔ y * y = x ∧ 0 ≤ y ∨ x < 0 ∧ y = 0 :=
begin
split,
{ rintro rfl,
cases le_or_lt 0 x with hle hlt,
{ exact or.inl ⟨mul_self_sqrt hle, sqrt_nonneg x⟩ },
{ exact or.inr ⟨hlt, sqrt_eq_zero_of_nonpos hlt.le⟩ } },
{ rintro (⟨rfl, hy⟩|⟨hx, rfl⟩),
exacts [sqrt_mul_self hy, sqrt_eq_zero_of_nonpos hx.le] }
end
theorem sqrt_eq_iff_mul_self_eq (hx : 0 ≤ x) (hy : 0 ≤ y) :
sqrt x = y ↔ y * y = x :=
⟨λ h, by rw [← h, mul_self_sqrt hx], λ h, by rw [← h, sqrt_mul_self hy]⟩
theorem sqrt_eq_iff_mul_self_eq_of_pos (h : 0 < y) :
sqrt x = y ↔ y * y = x :=
by simp [sqrt_eq_cases, h.ne', h.le]
@[simp] lemma sqrt_eq_one : sqrt x = 1 ↔ x = 1 :=
calc sqrt x = 1 ↔ 1 * 1 = x :
sqrt_eq_iff_mul_self_eq_of_pos zero_lt_one
... ↔ x = 1 : by rw [eq_comm, mul_one]
@[simp] theorem sq_sqrt (h : 0 ≤ x) : (sqrt x)^2 = x :=
by rw [sq, mul_self_sqrt h]
@[simp] theorem sqrt_sq (h : 0 ≤ x) : sqrt (x ^ 2) = x :=
by rw [sq, sqrt_mul_self h]
theorem sqrt_eq_iff_sq_eq (hx : 0 ≤ x) (hy : 0 ≤ y) :
sqrt x = y ↔ y ^ 2 = x :=
by rw [sq, sqrt_eq_iff_mul_self_eq hx hy]
theorem sqrt_mul_self_eq_abs (x : ℝ) : sqrt (x * x) = |x| :=
by rw [← abs_mul_abs_self x, sqrt_mul_self (abs_nonneg _)]
theorem sqrt_sq_eq_abs (x : ℝ) : sqrt (x ^ 2) = |x| :=
by rw [sq, sqrt_mul_self_eq_abs]
@[simp] theorem sqrt_zero : sqrt 0 = 0 := by simp [sqrt]
@[simp] theorem sqrt_one : sqrt 1 = 1 := by simp [sqrt]
@[simp] theorem sqrt_le_sqrt_iff (hy : 0 ≤ y) : sqrt x ≤ sqrt y ↔ x ≤ y :=
by rw [sqrt, sqrt, nnreal.coe_le_coe, nnreal.sqrt_le_sqrt_iff, real.to_nnreal_le_to_nnreal_iff hy]
@[simp] theorem sqrt_lt_sqrt_iff (hx : 0 ≤ x) : sqrt x < sqrt y ↔ x < y :=
lt_iff_lt_of_le_iff_le (sqrt_le_sqrt_iff hx)
theorem sqrt_lt_sqrt_iff_of_pos (hy : 0 < y) : sqrt x < sqrt y ↔ x < y :=
by rw [sqrt, sqrt, nnreal.coe_lt_coe, nnreal.sqrt_lt_sqrt_iff, to_nnreal_lt_to_nnreal_iff hy]
theorem sqrt_le_sqrt (h : x ≤ y) : sqrt x ≤ sqrt y :=
by { rw [sqrt, sqrt, nnreal.coe_le_coe, nnreal.sqrt_le_sqrt_iff], exact to_nnreal_le_to_nnreal h }
theorem sqrt_lt_sqrt (hx : 0 ≤ x) (h : x < y) : sqrt x < sqrt y :=
(sqrt_lt_sqrt_iff hx).2 h
theorem sqrt_le_left (hy : 0 ≤ y) : sqrt x ≤ y ↔ x ≤ y ^ 2 :=
by rw [sqrt, ← real.le_to_nnreal_iff_coe_le hy, nnreal.sqrt_le_iff, sq, ← real.to_nnreal_mul hy,
real.to_nnreal_le_to_nnreal_iff (mul_self_nonneg y), sq]
theorem sqrt_le_iff : sqrt x ≤ y ↔ 0 ≤ y ∧ x ≤ y ^ 2 :=
begin
rw [← and_iff_right_of_imp (λ h, (sqrt_nonneg x).trans h), and.congr_right_iff],
exact sqrt_le_left
end
lemma sqrt_lt (hx : 0 ≤ x) (hy : 0 ≤ y) : sqrt x < y ↔ x < y ^ 2 :=
by rw [←sqrt_lt_sqrt_iff hx, sqrt_sq hy]
lemma sqrt_lt' (hy : 0 < y) : sqrt x < y ↔ x < y ^ 2 :=
by rw [←sqrt_lt_sqrt_iff_of_pos (pow_pos hy _), sqrt_sq hy.le]
/- note: if you want to conclude `x ≤ sqrt y`, then use `le_sqrt_of_sq_le`.
if you have `x > 0`, consider using `le_sqrt'` -/
theorem le_sqrt (hx : 0 ≤ x) (hy : 0 ≤ y) : x ≤ sqrt y ↔ x ^ 2 ≤ y :=
le_iff_le_iff_lt_iff_lt.2 $ sqrt_lt hy hx
lemma le_sqrt' (hx : 0 < x) : x ≤ sqrt y ↔ x ^ 2 ≤ y := le_iff_le_iff_lt_iff_lt.2 $ sqrt_lt' hx
theorem abs_le_sqrt (h : x^2 ≤ y) : |x| ≤ sqrt y :=
by rw ← sqrt_sq_eq_abs; exact sqrt_le_sqrt h
theorem sq_le (h : 0 ≤ y) : x^2 ≤ y ↔ -sqrt y ≤ x ∧ x ≤ sqrt y :=
begin
split,
{ simpa only [abs_le] using abs_le_sqrt },
{ rw [← abs_le, ← sq_abs],
exact (le_sqrt (abs_nonneg x) h).mp },
end
theorem neg_sqrt_le_of_sq_le (h : x^2 ≤ y) : -sqrt y ≤ x :=
((sq_le ((sq_nonneg x).trans h)).mp h).1
theorem le_sqrt_of_sq_le (h : x^2 ≤ y) : x ≤ sqrt y :=
((sq_le ((sq_nonneg x).trans h)).mp h).2
@[simp] theorem sqrt_inj (hx : 0 ≤ x) (hy : 0 ≤ y) : sqrt x = sqrt y ↔ x = y :=
by simp [le_antisymm_iff, hx, hy]
@[simp] theorem sqrt_eq_zero (h : 0 ≤ x) : sqrt x = 0 ↔ x = 0 :=
by simpa using sqrt_inj h le_rfl
theorem sqrt_eq_zero' : sqrt x = 0 ↔ x ≤ 0 :=
by rw [sqrt, nnreal.coe_eq_zero, nnreal.sqrt_eq_zero, real.to_nnreal_eq_zero]
theorem sqrt_ne_zero (h : 0 ≤ x) : sqrt x ≠ 0 ↔ x ≠ 0 :=
by rw [not_iff_not, sqrt_eq_zero h]
theorem sqrt_ne_zero' : sqrt x ≠ 0 ↔ 0 < x :=
by rw [← not_le, not_iff_not, sqrt_eq_zero']
@[simp] theorem sqrt_pos : 0 < sqrt x ↔ 0 < x :=
lt_iff_lt_of_le_iff_le (iff.trans
(by simp [le_antisymm_iff, sqrt_nonneg]) sqrt_eq_zero')
alias sqrt_pos ↔ _ sqrt_pos_of_pos
section
open tactic tactic.positivity
/-- Extension for the `positivity` tactic: a square root is nonnegative, and is strictly positive if
its input is. -/
@[positivity]
meta def _root_.tactic.positivity_sqrt : expr → tactic strictness
| `(real.sqrt %%a) := do
(do -- if can prove `0 < a`, report positivity
positive pa ← core a,
positive <$> mk_app ``sqrt_pos_of_pos [pa]) <|>
nonnegative <$> mk_app ``sqrt_nonneg [a] -- else report nonnegativity
| _ := failed
end
@[simp] theorem sqrt_mul (hx : 0 ≤ x) (y : ℝ) : sqrt (x * y) = sqrt x * sqrt y :=
by simp_rw [sqrt, ← nnreal.coe_mul, nnreal.coe_eq, real.to_nnreal_mul hx, nnreal.sqrt_mul]
@[simp] theorem sqrt_mul' (x) {y : ℝ} (hy : 0 ≤ y) : sqrt (x * y) = sqrt x * sqrt y :=
by rw [mul_comm, sqrt_mul hy, mul_comm]
@[simp] theorem sqrt_inv (x : ℝ) : sqrt x⁻¹ = (sqrt x)⁻¹ :=
by rw [sqrt, real.to_nnreal_inv, nnreal.sqrt_inv, nnreal.coe_inv, sqrt]
@[simp] theorem sqrt_div (hx : 0 ≤ x) (y : ℝ) : sqrt (x / y) = sqrt x / sqrt y :=
by rw [division_def, sqrt_mul hx, sqrt_inv, division_def]
@[simp] theorem div_sqrt : x / sqrt x = sqrt x :=
begin
cases le_or_lt x 0,
{ rw [sqrt_eq_zero'.mpr h, div_zero] },
{ rw [div_eq_iff (sqrt_ne_zero'.mpr h), mul_self_sqrt h.le] },
end
theorem sqrt_div_self' : sqrt x / x = 1 / sqrt x :=
by rw [←div_sqrt, one_div_div, div_sqrt]
theorem sqrt_div_self : sqrt x / x = (sqrt x)⁻¹ :=
by rw [sqrt_div_self', one_div]
lemma lt_sqrt (hx : 0 ≤ x) : x < sqrt y ↔ x ^ 2 < y :=
by rw [←sqrt_lt_sqrt_iff (sq_nonneg _), sqrt_sq hx]
lemma sq_lt : x^2 < y ↔ -sqrt y < x ∧ x < sqrt y := by rw [←abs_lt, ←sq_abs, lt_sqrt (abs_nonneg _)]
theorem neg_sqrt_lt_of_sq_lt (h : x^2 < y) : -sqrt y < x := (sq_lt.mp h).1
theorem lt_sqrt_of_sq_lt (h : x^2 < y) : x < sqrt y := (sq_lt.mp h).2
lemma lt_sq_of_sqrt_lt {x y : ℝ} (h : sqrt x < y) : x < y ^ 2 :=
by { have hy := x.sqrt_nonneg.trans_lt h,
rwa [←sqrt_lt_sqrt_iff_of_pos (sq_pos_of_pos hy), sqrt_sq hy.le] }
/-- The natural square root is at most the real square root -/
lemma nat_sqrt_le_real_sqrt {a : ℕ} : ↑(nat.sqrt a) ≤ real.sqrt ↑a :=
begin
rw real.le_sqrt (nat.cast_nonneg _) (nat.cast_nonneg _),
norm_cast,
exact nat.sqrt_le' a,
end
/-- The real square root is at most the natural square root plus one -/
lemma real_sqrt_le_nat_sqrt_succ {a : ℕ} : real.sqrt ↑a ≤ nat.sqrt a + 1 :=
begin
rw real.sqrt_le_iff,
split,
{ norm_cast, simp, },
{ norm_cast, exact le_of_lt (nat.lt_succ_sqrt' a), },
end
instance : star_ordered_ring ℝ :=
{ nonneg_iff := λ r, by
{ refine ⟨λ hr, ⟨sqrt r, show r = sqrt r * sqrt r, by rw [←sqrt_mul hr, sqrt_mul_self hr]⟩, _⟩,
rintros ⟨s, rfl⟩,
exact mul_self_nonneg s },
..real.ordered_add_comm_group }
end real
open real
variables {α : Type*}
lemma filter.tendsto.sqrt {f : α → ℝ} {l : filter α} {x : ℝ} (h : tendsto f l (𝓝 x)) :
tendsto (λ x, sqrt (f x)) l (𝓝 (sqrt x)) :=
(continuous_sqrt.tendsto _).comp h
variables [topological_space α] {f : α → ℝ} {s : set α} {x : α}
lemma continuous_within_at.sqrt (h : continuous_within_at f s x) :
continuous_within_at (λ x, sqrt (f x)) s x :=
h.sqrt
lemma continuous_at.sqrt (h : continuous_at f x) : continuous_at (λ x, sqrt (f x)) x := h.sqrt
lemma continuous_on.sqrt (h : continuous_on f s) : continuous_on (λ x, sqrt (f x)) s :=
λ x hx, (h x hx).sqrt
@[continuity]
lemma continuous.sqrt (h : continuous f) : continuous (λ x, sqrt (f x)) := continuous_sqrt.comp h
|
1e24d3b535a85894d4dd211eab4dc8c45270e343 | d450724ba99f5b50b57d244eb41fef9f6789db81 | /src/mywork/lectures/lecture_25a.lean | 453e68b244f9b712cc550d020abd15a1a4b205d4 | [] | no_license | jakekauff/CS2120F21 | 4f009adeb4ce4a148442b562196d66cc6c04530c | e69529ec6f5d47a554291c4241a3d8ec4fe8f5ad | refs/heads/main | 1,693,841,880,030 | 1,637,604,848,000 | 1,637,604,848,000 | 399,946,698 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 883 | lean | import .lecture_24
/-
BASIC SETUP
-/
namespace relations
section relation
/-
Define relation, r, as two-place predicate on
a type, β, with notation, x ≺ y, for (r x y).
-/
variables {α β γ : Type} (r : β → β → Prop)
local infix `≺`:50 := r
/-
ORDERING RELATIONS ON A TYPE, β
-/
def strict_ordering := asymmetric r ∧ transitive r
def ordering := reflexive r ∧ transitive r ∧ anti_symmetric r
def partial_order := reflexive r ∧ transitive r ∧ anti_symmetric r ∧ ¬strongly_connected r
def total_order := reflexive r ∧ transitive r ∧ anti_symmetric r ∧ strongly_connected r
def well_ordering := total_order ∧
(
∀ ( s : set β ),
∃ ( b : β ),
(∀ (b' : β), b' ∈ S → b ≺ b')
)
def inverse (r : α → β → Prop) :=
λ (b : β) (a : α), r a b
end relation
end relations
|
3aa18c6cf05f64a877d26e6c21cb2de2e1783ce2 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/data/mv_polynomial/comap.lean | 7dcbdb07d6f480ed4cb2fa5bf0ac7b501fbc8218 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 3,729 | lean | /-
Copyright (c) 2020 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import data.mv_polynomial.rename
/-!
# `comap` operation on `mv_polynomial`
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines the `comap` function on `mv_polynomial`.
`mv_polynomial.comap` is a low-tech example of a map of "algebraic varieties," modulo the fact that
`mathlib` does not yet define varieties.
## Notation
As in other polynomial files, we typically use the notation:
+ `σ : Type*` (indexing the variables)
+ `R : Type*` `[comm_semiring R]` (the coefficients)
-/
namespace mv_polynomial
variables {σ : Type*} {τ : Type*} {υ : Type*} {R : Type*} [comm_semiring R]
/--
Given an algebra hom `f : mv_polynomial σ R →ₐ[R] mv_polynomial τ R`
and a variable evaluation `v : τ → R`,
`comap f v` produces a variable evaluation `σ → R`.
-/
noncomputable def comap (f : mv_polynomial σ R →ₐ[R] mv_polynomial τ R) :
(τ → R) → (σ → R) :=
λ x i, aeval x (f (X i))
@[simp] lemma comap_apply (f : mv_polynomial σ R →ₐ[R] mv_polynomial τ R) (x : τ → R) (i : σ) :
comap f x i = aeval x (f (X i)) := rfl
@[simp] lemma comap_id_apply (x : σ → R) : comap (alg_hom.id R (mv_polynomial σ R)) x = x :=
by { funext i, simp only [comap, alg_hom.id_apply, id.def, aeval_X], }
variables (σ R)
lemma comap_id : comap (alg_hom.id R (mv_polynomial σ R)) = id :=
by { funext x, exact comap_id_apply x }
variables {σ R}
lemma comap_comp_apply (f : mv_polynomial σ R →ₐ[R] mv_polynomial τ R)
(g : mv_polynomial τ R →ₐ[R] mv_polynomial υ R) (x : υ → R) :
comap (g.comp f) x = comap f (comap g x) :=
begin
funext i,
transitivity (aeval x (aeval (λ i, g (X i)) (f (X i)))),
{ apply eval₂_hom_congr rfl rfl,
rw alg_hom.comp_apply,
suffices : g = aeval (λ i, g (X i)), { rw ← this, },
exact aeval_unique g },
{ simp only [comap, aeval_eq_eval₂_hom, map_eval₂_hom, alg_hom.comp_apply],
refine eval₂_hom_congr _ rfl rfl,
ext r, apply aeval_C },
end
lemma comap_comp (f : mv_polynomial σ R →ₐ[R] mv_polynomial τ R)
(g : mv_polynomial τ R →ₐ[R] mv_polynomial υ R) :
comap (g.comp f) = comap f ∘ comap g :=
by { funext x, exact comap_comp_apply _ _ _ }
lemma comap_eq_id_of_eq_id (f : mv_polynomial σ R →ₐ[R] mv_polynomial σ R)
(hf : ∀ φ, f φ = φ) (x : σ → R) :
comap f x = x :=
by { convert comap_id_apply x, ext1 φ, rw [hf, alg_hom.id_apply] }
lemma comap_rename (f : σ → τ) (x : τ → R) : comap (rename f) x = x ∘ f :=
by { ext i, simp only [rename_X, comap_apply, aeval_X] }
/--
If two polynomial types over the same coefficient ring `R` are equivalent,
there is a bijection between the types of functions from their variable types to `R`.
-/
noncomputable def comap_equiv (f : mv_polynomial σ R ≃ₐ[R] mv_polynomial τ R) :
(τ → R) ≃ (σ → R) :=
{ to_fun := comap f,
inv_fun := comap f.symm,
left_inv := by { intro x, rw [← comap_comp_apply], apply comap_eq_id_of_eq_id, intro,
simp only [alg_hom.id_apply, alg_equiv.comp_symm], },
right_inv := by { intro x, rw [← comap_comp_apply], apply comap_eq_id_of_eq_id, intro,
simp only [alg_hom.id_apply, alg_equiv.symm_comp] }, }
@[simp] lemma comap_equiv_coe (f : mv_polynomial σ R ≃ₐ[R] mv_polynomial τ R) :
(comap_equiv f : (τ → R) → (σ → R)) = comap f := rfl
@[simp] lemma comap_equiv_symm_coe (f : mv_polynomial σ R ≃ₐ[R] mv_polynomial τ R) :
((comap_equiv f).symm : (σ → R) → (τ → R)) = comap f.symm := rfl
end mv_polynomial
|
c91d7596f671dfd4fef7f2e412ce3b4399b30ea5 | 9c2e8d73b5c5932ceb1333265f17febc6a2f0a39 | /src/apps/topo_translation.lean | baa7d352368e4eb59252de8dfb2112e38d8d5f2b | [
"MIT"
] | permissive | minchaowu/ModalTab | 2150392108dfdcaffc620ff280a8b55fe13c187f | 9bb0bf17faf0554d907ef7bdd639648742889178 | refs/heads/master | 1,626,266,863,244 | 1,592,056,874,000 | 1,592,056,874,000 | 153,314,364 | 12 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 2,273 | lean | import .topological_semantics ..K.semantics
open nnf
-- local attribute [instance] classical.prop_decidable
@[simp] def topo_to_kripke {α : Type} (tm : topo_model α) : kripke α :=
{ rel := λ s t, s ∈ @_root_.closure _ tm.to_topological_space {t},
val := λ n s, tm.v n s }
theorem trans_force_left {α : Type} {tm : topo_model α} : Π {s} {φ : nnf}, (topo_force tm s φ) → force (topo_to_kripke tm) s φ
| s (var n) h := by dsimp at h; simp [h]
| s (neg n) h := by dsimp at h; simp [h]
| s (and φ ψ) h := begin cases h with l r, split, apply trans_force_left l, apply trans_force_left r end
| s (or φ ψ) h := begin cases h, left, apply trans_force_left h, right, apply trans_force_left h end
| s (box φ) h :=
begin
rcases h with ⟨w, hw, hmem⟩,
intros s' hs',
apply trans_force_left,
apply hw.2,
rw ←set.inter_singleton_nonempty,
have := (@mem_closure_iff _ tm.to_topological_space _ _).1,
swap 3, exact {s'}, apply this, simpa using hs',
exact hw.1, exact hmem
end
| s (dia φ) h :=
begin
let ts := tm.to_topological_space,
let o := ⋂₀ {x : set α | s ∈ x ∧ @is_open _ ts x},
have openo: @is_open _ ts o,
{ apply tm.is_alex, intros, exact H.2 },
have hmem : s ∈ o,
{ rw set.mem_sInter, intros, exact H.1 },
have ex := (@mem_closure_iff _ tm.to_topological_space _ _).1 h o openo hmem,
cases ex with w hw, dsimp,
split, split, swap 3,
{ exact w },
rw (@mem_closure_iff _ tm.to_topological_space _ _),
{ --apply to_bool_true,
intros o' hopen' hmem',
have : o ⊆ o',
{ intro x, intro hx, rw set.mem_sInter at hx, apply hx, split, repeat {assumption} },
rw set.inter_singleton_nonempty,
apply this hw.1 },
{ exact trans_force_left hw.2 }
end
theorem sat_of_topo_sat {Γ : list nnf}
{α : Type} (tm : topo_model α) (s) (h : topo_sat tm s Γ) :
sat (topo_to_kripke tm) s Γ := λ φ hφ, trans_force_left $ h φ hφ
theorem unsat_topo_of_unsat {Γ : list nnf} : unsatisfiable Γ → topo_unsatisfiable Γ :=
λ h, (λ α tm s hsat, @h _ (topo_to_kripke tm) s (sat_of_topo_sat _ _ hsat))
def not_topo_force_of_unsat {φ} : unsatisfiable [φ] → ∀ (α) (tm : topo_model α) s, ¬ topo_force tm s φ :=
λ h, topo_unsat_singleton $ unsat_topo_of_unsat h
|
e85c55dedf6d7b991c3baa12be34ab4ce16dc311 | 5ae26df177f810c5006841e9c73dc56e01b978d7 | /src/topology/instances/ennreal.lean | aa889dd4c15eb0c97b48abbbe525973cf091452b | [
"Apache-2.0"
] | permissive | ChrisHughes24/mathlib | 98322577c460bc6b1fe5c21f42ce33ad1c3e5558 | a2a867e827c2a6702beb9efc2b9282bd801d5f9a | refs/heads/master | 1,583,848,251,477 | 1,565,164,247,000 | 1,565,164,247,000 | 129,409,993 | 0 | 1 | Apache-2.0 | 1,565,164,817,000 | 1,523,628,059,000 | Lean | UTF-8 | Lean | false | false | 33,282 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Johannes Hölzl
Extended non-negative reals
-/
import topology.instances.nnreal data.real.ennreal
noncomputable theory
open classical set lattice filter metric
local attribute [instance] prop_decidable
variables {α : Type*} {β : Type*} {γ : Type*}
local notation `∞` := (⊤ : ennreal)
namespace ennreal
variables {a b c d : ennreal} {r p q : nnreal}
variables {x y z : ennreal} {ε ε₁ ε₂ : ennreal} {s : set ennreal}
section topological_space
open topological_space
/-- Topology on `ennreal`.
Note: this is different from the `emetric_space` topology. The `emetric_space` topology has
`is_open {⊤}`, while this topology doesn't have singleton elements. -/
instance : topological_space ennreal :=
topological_space.generate_from {s | ∃a, s = {b | a < b} ∨ s = {b | b < a}}
instance : orderable_topology ennreal := ⟨rfl⟩
instance : t2_space ennreal := by apply_instance
instance : second_countable_topology ennreal :=
⟨⟨⋃q ≥ (0:ℚ), {{a : ennreal | a < nnreal.of_real q}, {a : ennreal | ↑(nnreal.of_real q) < a}},
countable_bUnion (countable_encodable _) $ assume a ha, countable_insert (countable_singleton _),
le_antisymm
(le_generate_from $ by simp [or_imp_distrib, is_open_lt', is_open_gt'] {contextual := tt})
(le_generate_from $ λ s h, begin
rcases h with ⟨a, hs | hs⟩;
[ rw show s = ⋃q∈{q:ℚ | 0 ≤ q ∧ a < nnreal.of_real q}, {b | ↑(nnreal.of_real q) < b},
from set.ext (assume b, by simp [hs, @ennreal.lt_iff_exists_rat_btwn a b, and_assoc]),
rw show s = ⋃q∈{q:ℚ | 0 ≤ q ∧ ↑(nnreal.of_real q) < a}, {b | b < ↑(nnreal.of_real q)},
from set.ext (assume b, by simp [hs, @ennreal.lt_iff_exists_rat_btwn b a, and_comm, and_assoc])];
{ apply is_open_Union, intro q,
apply is_open_Union, intro hq,
exact generate_open.basic _ (mem_bUnion hq.1 $ by simp) }
end)⟩⟩
lemma embedding_coe : embedding (coe : nnreal → ennreal) :=
⟨⟨begin
refine le_antisymm _ _,
{ rw [orderable_topology.topology_eq_generate_intervals ennreal,
← coinduced_le_iff_le_induced],
refine le_generate_from (assume s ha, _),
rcases ha with ⟨a, rfl | rfl⟩,
show is_open {b : nnreal | a < ↑b},
{ cases a; simp [none_eq_top, some_eq_coe, is_open_lt'] },
show is_open {b : nnreal | ↑b < a},
{ cases a; simp [none_eq_top, some_eq_coe, is_open_gt', is_open_const] } },
{ rw [orderable_topology.topology_eq_generate_intervals nnreal],
refine le_generate_from (assume s ha, _),
rcases ha with ⟨a, rfl | rfl⟩,
exact ⟨{b : ennreal | ↑a < b}, @is_open_lt' ennreal ennreal.topological_space _ _ _, by simp⟩,
exact ⟨{b : ennreal | b < ↑a}, @is_open_gt' ennreal ennreal.topological_space _ _ _, by simp⟩ }
end⟩,
assume a b, coe_eq_coe.1⟩
lemma is_open_ne_top : is_open {a : ennreal | a ≠ ⊤} :=
is_open_neg (is_closed_eq continuous_id continuous_const)
lemma is_open_Ico_zero : is_open (Ico 0 b) := by { rw ennreal.Ico_eq_Iio, exact is_open_Iio}
lemma coe_range_mem_nhds : range (coe : nnreal → ennreal) ∈ nhds (r : ennreal) :=
have {a : ennreal | a ≠ ⊤} = range (coe : nnreal → ennreal),
from set.ext $ assume a, by cases a; simp [none_eq_top, some_eq_coe],
this ▸ mem_nhds_sets is_open_ne_top coe_ne_top
lemma tendsto_coe {f : filter α} {m : α → nnreal} {a : nnreal} :
tendsto (λa, (m a : ennreal)) f (nhds ↑a) ↔ tendsto m f (nhds a) :=
embedding_coe.tendsto_nhds_iff.symm
lemma continuous_coe {α} [topological_space α] {f : α → nnreal} :
continuous (λa, (f a : ennreal)) ↔ continuous f :=
embedding_coe.continuous_iff.symm
lemma nhds_coe {r : nnreal} : nhds (r : ennreal) = (nhds r).map coe :=
by rw [embedding_coe.induced, map_nhds_induced_eq coe_range_mem_nhds]
lemma nhds_coe_coe {r p : nnreal} : nhds ((r : ennreal), (p : ennreal)) =
(nhds (r, p)).map (λp:nnreal×nnreal, (p.1, p.2)) :=
begin
rw [(embedding_coe.prod_mk embedding_coe).map_nhds_eq],
rw [← prod_range_range_eq],
exact prod_mem_nhds_sets coe_range_mem_nhds coe_range_mem_nhds
end
lemma continuous_of_real : continuous ennreal.of_real :=
(continuous_coe.2 continuous_id).comp nnreal.continuous_of_real
lemma tendsto_of_real {f : filter α} {m : α → ℝ} {a : ℝ} (h : tendsto m f (nhds a)) :
tendsto (λa, ennreal.of_real (m a)) f (nhds (ennreal.of_real a)) :=
tendsto.comp (continuous.tendsto continuous_of_real _) h
lemma tendsto_to_nnreal {a : ennreal} : a ≠ ⊤ →
tendsto (ennreal.to_nnreal) (nhds a) (nhds a.to_nnreal) :=
begin
cases a; simp [some_eq_coe, none_eq_top, nhds_coe, tendsto_map'_iff, (∘)],
exact tendsto_id
end
lemma tendsto_nhds_top {m : α → ennreal} {f : filter α}
(h : ∀n:ℕ, {a | ↑n < m a} ∈ f) : tendsto m f (nhds ⊤) :=
tendsto_nhds_generate_from $ assume s hs,
match s, hs with
| _, ⟨none, or.inl rfl⟩, hr := (lt_irrefl ⊤ hr).elim
| _, ⟨some r, or.inl rfl⟩, hr :=
let ⟨n, hrn⟩ := exists_nat_gt r in
mem_sets_of_superset (h n) $ assume a hnma, show ↑r < m a, from
lt_trans (show (r : ennreal) < n, from (coe_nat n) ▸ coe_lt_coe.2 hrn) hnma
| _, ⟨a, or.inr rfl⟩, hr := (not_top_lt $ show ⊤ < a, from hr).elim
end
lemma nhds_top : nhds ∞ = ⨅a:{a:ennreal // a ≠ ⊤}, principal (Ioi a) :=
begin
rw nhds_generate_from,
refine le_antisymm
(infi_le_infi2 _)
(le_infi $ assume s, le_infi $ assume hs, _),
{ rintros ⟨a, ha⟩, use {b : ennreal | a < b}, refine infi_le_of_le _ _,
{ simp only [mem_set_of_eq], split, { rwa lt_top_iff_ne_top }, { use a, exact or.inl rfl } },
{ simp only [mem_principal_sets, le_principal_iff], assume a, simp } },
{ rcases hs with ⟨ht, ⟨a, hs⟩⟩, cases hs,
case or.inl
{ rw [hs, mem_set_of_eq, lt_top_iff_ne_top] at ht,
refine infi_le_of_le ⟨a, ht⟩ _,
simp only [mem_principal_sets, le_principal_iff],
assume x, simp [hs] },
case or.inr
{ rw [hs, mem_set_of_eq, lt_iff_not_ge] at ht,
have := le_top,
contradiction } }
end
lemma nhds_zero : nhds (0 : ennreal) = ⨅a:{a:ennreal // a ≠ 0}, principal (Iio a) :=
begin
rw nhds_generate_from,
refine le_antisymm
(infi_le_infi2 _)
(le_infi $ assume s, le_infi $ assume hs, _),
{ rintros ⟨a, ha⟩, use {b : ennreal | b < a}, refine infi_le_of_le _ _,
{ simp only [mem_set_of_eq], split, { rwa zero_lt_iff_ne_zero }, { use a, exact or.inr rfl } },
{ simp only [mem_principal_sets, le_principal_iff], assume a, simp } },
{ rcases hs with ⟨hz, ⟨a, hs⟩⟩, cases hs,
case or.inr
{ rw [hs, mem_set_of_eq, zero_lt_iff_ne_zero] at hz,
refine infi_le_of_le ⟨a, hz⟩ _,
simp only [mem_principal_sets, le_principal_iff],
assume x, simp [hs] },
case or.inl
{ rw [hs, mem_set_of_eq, lt_iff_not_ge] at hz,
have := zero_le a,
contradiction } }
end
-- using Icc because
-- • don't have 'Ioo (x - ε) (x + ε) ∈ nhds x' unless x > 0
-- • (x - y ≤ ε ↔ x ≤ ε + y) is true, while (x - y < ε ↔ x < ε + y) is not
lemma Icc_mem_nhds : x ≠ ⊤ → ε > 0 → Icc (x - ε) (x + ε) ∈ nhds x :=
begin
assume xt ε0, rw mem_nhds_sets_iff,
by_cases x0 : x = 0,
{ use Iio (x + ε),
have : Iio (x + ε) ⊆ Icc (x - ε) (x + ε), assume a, rw x0, simpa using le_of_lt,
use this, exact ⟨is_open_Iio, mem_Iio_self_add xt ε0⟩ },
{ use Ioo (x - ε) (x + ε), use Ioo_subset_Icc_self,
exact ⟨is_open_Ioo, mem_Ioo_self_sub_add xt x0 ε0 ε0 ⟩ }
end
lemma nhds_of_ne_top : x ≠ ⊤ → nhds x = ⨅ε:{ε:ennreal // ε > 0}, principal (Icc (x - ε) (x + ε)) :=
begin
assume xt, refine le_antisymm _ _,
-- first direction
simp only [le_infi_iff, le_principal_iff, subtype.forall], assume ε ε0, exact Icc_mem_nhds xt ε0,
-- second direction
rw nhds_generate_from, refine le_infi (assume s, le_infi $ assume hs, _),
simp only [mem_set_of_eq] at hs, rcases hs with ⟨xs, ⟨a, ha⟩⟩,
cases ha,
{ rw ha at *,
rcases dense xs with ⟨b, ⟨ab, bx⟩⟩,
have xb_pos : x - b > 0 := zero_lt_sub_iff_lt.2 bx,
have xxb : x - (x - b) = b := sub_sub_cancel (by rwa lt_top_iff_ne_top) (le_of_lt bx),
refine infi_le_of_le ⟨x - b, xb_pos⟩ _,
simp only [mem_principal_sets, le_principal_iff, subtype.coe_mk],
assume y, rintros ⟨h₁, h₂⟩, rw xxb at h₁, calc a < b : ab ... ≤ y : h₁ },
{ rw ha at *,
rcases dense xs with ⟨b, ⟨xb, ba⟩⟩,
have bx_pos : b - x > 0 := zero_lt_sub_iff_lt.2 xb,
have xbx : x + (b - x) = b := add_sub_cancel_of_le (le_of_lt xb),
refine infi_le_of_le ⟨b - x, bx_pos⟩ _,
simp only [mem_principal_sets, le_principal_iff, subtype.coe_mk],
assume y, rintros ⟨h₁, h₂⟩, rw xbx at h₂, calc y ≤ b : h₂ ... < a : ba },
end
protected theorem tendsto_nhds {f : filter α} {u : α → ennreal} {a : ennreal} (ha : a ≠ ⊤) :
tendsto u f (nhds a) ↔ ∀ ε > 0, ∃ n ∈ f, ∀x ∈ n, (u x) ∈ Icc (a - ε) (a + ε) :=
by { simp only [nhds_of_ne_top ha, tendsto_infi, subtype.forall, tendsto_principal, mem_Icc],
refine forall_congr (assume ε, forall_congr $ assume hε, exists_sets_subset_iff.symm) }
protected lemma tendsto_at_top [nonempty β] [semilattice_sup β] {f : β → ennreal} {a : ennreal}
(ha : a ≠ ⊤) : tendsto f at_top (nhds a) ↔ ∀ε>0, ∃N, ∀n≥N, (f n) ∈ Icc (a - ε) (a + ε) :=
by { simp only [nhds_of_ne_top ha, tendsto_infi, subtype.forall, tendsto_at_top_principal], refl }
lemma tendsto_coe_nnreal_nhds_top {α} {l : filter α} {f : α → nnreal} (h : tendsto f l at_top) :
tendsto (λa, (f a : ennreal)) l (nhds (⊤:ennreal)) :=
tendsto_nhds_top $ assume n,
have {a : α | ↑(n+1) ≤ f a} ∈ l := h $ mem_at_top _,
mem_sets_of_superset this $ assume a (ha : ↑(n+1) ≤ f a),
begin
rw [← coe_nat],
dsimp,
exact coe_lt_coe.2 (lt_of_lt_of_le (nat.cast_lt.2 (nat.lt_succ_self _)) ha)
end
instance : topological_add_monoid ennreal :=
⟨ continuous_iff_continuous_at.2 $
have hl : ∀a:ennreal, tendsto (λ (p : ennreal × ennreal), p.fst + p.snd) (nhds (⊤, a)) (nhds ⊤), from
assume a, tendsto_nhds_top $ assume n,
have set.prod {a | ↑n < a } univ ∈ nhds ((⊤:ennreal), a), from
prod_mem_nhds_sets (lt_mem_nhds $ coe_nat n ▸ coe_lt_top) univ_mem_sets,
show {a : ennreal × ennreal | ↑n < a.fst + a.snd} ∈ nhds (⊤, a),
begin filter_upwards [this] assume ⟨a₁, a₂⟩ ⟨h₁, h₂⟩, lt_of_lt_of_le h₁ (le_add_right $ le_refl _) end,
begin
rintro ⟨a₁, a₂⟩,
cases a₁, { simp [continuous_at, none_eq_top, hl a₂], },
cases a₂, { simp [continuous_at, none_eq_top, some_eq_coe, nhds_swap (a₁ : ennreal) ⊤,
tendsto_map'_iff, (∘), hl ↑a₁] },
simp [continuous_at, some_eq_coe, nhds_coe_coe, tendsto_map'_iff, (∘)],
simp only [coe_add.symm, tendsto_coe, tendsto_add']
end ⟩
protected lemma tendsto_mul' (ha : a ≠ 0 ∨ b ≠ ⊤) (hb : b ≠ 0 ∨ a ≠ ⊤) :
tendsto (λp:ennreal×ennreal, p.1 * p.2) (nhds (a, b)) (nhds (a * b)) :=
have ht : ∀b:ennreal, b ≠ 0 → tendsto (λp:ennreal×ennreal, p.1 * p.2) (nhds ((⊤:ennreal), b)) (nhds ⊤),
begin
refine assume b hb, tendsto_nhds_top $ assume n, _,
rcases dense (zero_lt_iff_ne_zero.2 hb) with ⟨ε', hε', hεb'⟩,
rcases ennreal.lt_iff_exists_coe.1 hεb' with ⟨ε, rfl, h⟩,
rcases exists_nat_gt (↑n / ε) with ⟨m, hm⟩,
have hε : ε > 0, from coe_lt_coe.1 hε',
refine mem_sets_of_superset (prod_mem_nhds_sets (lt_mem_nhds $ @coe_lt_top m) (lt_mem_nhds $ h)) _,
rintros ⟨a₁, a₂⟩ ⟨h₁, h₂⟩,
dsimp at h₁ h₂ ⊢,
calc (n:ennreal) = ↑(((n:nnreal) / ε) * ε) :
begin
simp [nnreal.div_def],
rw [mul_assoc, ← coe_mul, nnreal.inv_mul_cancel, coe_one, ← coe_nat, mul_one],
exact zero_lt_iff_ne_zero.1 hε
end
... < (↑m * ε : nnreal) : coe_lt_coe.2 $ mul_lt_mul hm (le_refl _) hε (nat.cast_nonneg _)
... ≤ a₁ * a₂ : by rw [coe_mul]; exact canonically_ordered_semiring.mul_le_mul
(le_of_lt h₁)
(le_of_lt h₂)
end,
begin
cases a, {simp [none_eq_top] at hb, simp [none_eq_top, ht b hb, top_mul, hb] },
cases b, {
simp [none_eq_top] at ha,
have ha' : a ≠ 0, from mt coe_eq_coe.2 ha,
simp [*, nhds_swap (a : ennreal) ⊤, none_eq_top, some_eq_coe, top_mul, tendsto_map'_iff, (∘), mul_comm] },
simp [some_eq_coe, nhds_coe_coe, tendsto_map'_iff, (∘)],
simp only [coe_mul.symm, tendsto_coe, tendsto_mul']
end
protected lemma tendsto_mul {f : filter α} {ma : α → ennreal} {mb : α → ennreal} {a b : ennreal}
(hma : tendsto ma f (nhds a)) (ha : a ≠ 0 ∨ b ≠ ⊤) (hmb : tendsto mb f (nhds b)) (hb : b ≠ 0 ∨ a ≠ ⊤) :
tendsto (λa, ma a * mb a) f (nhds (a * b)) :=
show tendsto ((λp:ennreal×ennreal, p.1 * p.2) ∘ (λa, (ma a, mb a))) f (nhds (a * b)), from
tendsto.comp (ennreal.tendsto_mul' ha hb) (tendsto_prod_mk_nhds hma hmb)
protected lemma tendsto_mul_right {f : filter α} {m : α → ennreal} {a b : ennreal}
(hm : tendsto m f (nhds b)) (hb : b ≠ 0 ∨ a ≠ ⊤) : tendsto (λb, a * m b) f (nhds (a * b)) :=
by_cases
(assume : a = 0, by simp [this, tendsto_const_nhds])
(assume ha : a ≠ 0, ennreal.tendsto_mul tendsto_const_nhds (or.inl ha) hm hb)
lemma Sup_add {s : set ennreal} (hs : s ≠ ∅) : Sup s + a = ⨆b∈s, b + a :=
have Sup ((λb, b + a) '' s) = Sup s + a,
from is_lub_iff_Sup_eq.mp $ is_lub_of_is_lub_of_tendsto
(assume x _ y _ h, add_le_add' h (le_refl _))
is_lub_Sup
hs
(tendsto_add (tendsto_id' inf_le_left) tendsto_const_nhds),
by simp [Sup_image, -add_comm] at this; exact this.symm
lemma supr_add {ι : Sort*} {s : ι → ennreal} [h : nonempty ι] : supr s + a = ⨆b, s b + a :=
let ⟨x⟩ := h in
calc supr s + a = Sup (range s) + a : by simp [Sup_range]
... = (⨆b∈range s, b + a) : Sup_add $ ne_empty_iff_exists_mem.mpr ⟨s x, x, rfl⟩
... = _ : by simp [supr_range, -mem_range]
lemma add_supr {ι : Sort*} {s : ι → ennreal} [h : nonempty ι] : a + supr s = ⨆b, a + s b :=
by rw [add_comm, supr_add]; simp
lemma supr_add_supr {ι : Sort*} {f g : ι → ennreal} (h : ∀i j, ∃k, f i + g j ≤ f k + g k) :
supr f + supr g = (⨆ a, f a + g a) :=
begin
by_cases hι : nonempty ι,
{ letI := hι,
refine le_antisymm _ (supr_le $ λ a, add_le_add' (le_supr _ _) (le_supr _ _)),
simpa [add_supr, supr_add] using
λ i j:ι, show f i + g j ≤ ⨆ a, f a + g a, from
let ⟨k, hk⟩ := h i j in le_supr_of_le k hk },
{ have : ∀f:ι → ennreal, (⨆i, f i) = 0 := assume f, bot_unique (supr_le $ assume i, (hι ⟨i⟩).elim),
rw [this, this, this, zero_add] }
end
lemma supr_add_supr_of_monotone {ι : Sort*} [semilattice_sup ι]
{f g : ι → ennreal} (hf : monotone f) (hg : monotone g) :
supr f + supr g = (⨆ a, f a + g a) :=
supr_add_supr $ assume i j, ⟨i ⊔ j, add_le_add' (hf $ le_sup_left) (hg $ le_sup_right)⟩
lemma finset_sum_supr_nat {α} {ι} [semilattice_sup ι] {s : finset α} {f : α → ι → ennreal}
(hf : ∀a, monotone (f a)) :
s.sum (λa, supr (f a)) = (⨆ n, s.sum (λa, f a n)) :=
begin
refine finset.induction_on s _ _,
{ simp,
exact (bot_unique $ supr_le $ assume i, le_refl ⊥).symm },
{ assume a s has ih,
simp only [finset.sum_insert has],
rw [ih, supr_add_supr_of_monotone (hf a)],
assume i j h,
exact (finset.sum_le_sum $ assume a ha, hf a h) }
end
lemma mul_Sup {s : set ennreal} {a : ennreal} : a * Sup s = ⨆i∈s, a * i :=
begin
by_cases hs : ∀x∈s, x = (0:ennreal),
{ have h₁ : Sup s = 0 := (bot_unique $ Sup_le $ assume a ha, (hs a ha).symm ▸ le_refl 0),
have h₂ : (⨆i ∈ s, a * i) = 0 :=
(bot_unique $ supr_le $ assume a, supr_le $ assume ha, by simp [hs a ha]),
rw [h₁, h₂, mul_zero] },
{ simp only [not_forall] at hs,
rcases hs with ⟨x, hx, hx0⟩,
have s₀ : s ≠ ∅ := not_eq_empty_iff_exists.2 ⟨x, hx⟩,
have s₁ : Sup s ≠ 0 :=
zero_lt_iff_ne_zero.1 (lt_of_lt_of_le (zero_lt_iff_ne_zero.2 hx0) (le_Sup hx)),
have : Sup ((λb, a * b) '' s) = a * Sup s :=
is_lub_iff_Sup_eq.mp (is_lub_of_is_lub_of_tendsto
(assume x _ y _ h, canonically_ordered_semiring.mul_le_mul (le_refl _) h)
is_lub_Sup
s₀
(ennreal.tendsto_mul_right (tendsto_id' inf_le_left) (or.inl s₁))),
rw [this.symm, Sup_image] }
end
lemma mul_supr {ι : Sort*} {f : ι → ennreal} {a : ennreal} : a * supr f = ⨆i, a * f i :=
by rw [← Sup_range, mul_Sup, supr_range]
lemma supr_mul {ι : Sort*} {f : ι → ennreal} {a : ennreal} : supr f * a = ⨆i, f i * a :=
by rw [mul_comm, mul_supr]; congr; funext; rw [mul_comm]
protected lemma tendsto_coe_sub : ∀{b:ennreal}, tendsto (λb:ennreal, ↑r - b) (nhds b) (nhds (↑r - b)) :=
begin
refine (forall_ennreal.2 $ and.intro (assume a, _) _),
{ simp [@nhds_coe a, tendsto_map'_iff, (∘), tendsto_coe, coe_sub.symm],
exact nnreal.tendsto_sub tendsto_const_nhds tendsto_id },
simp,
exact (tendsto.congr' (mem_sets_of_superset (lt_mem_nhds $ @coe_lt_top r) $
by simp [le_of_lt] {contextual := tt})) tendsto_const_nhds
end
lemma sub_supr {ι : Sort*} [hι : nonempty ι] {b : ι → ennreal} (hr : a < ⊤) :
a - (⨆i, b i) = (⨅i, a - b i) :=
let ⟨i⟩ := hι in
let ⟨r, eq, _⟩ := lt_iff_exists_coe.mp hr in
have Inf ((λb, ↑r - b) '' range b) = ↑r - (⨆i, b i),
from is_glb_iff_Inf_eq.mp $ is_glb_of_is_lub_of_tendsto
(assume x _ y _, sub_le_sub (le_refl _))
is_lub_supr
(ne_empty_of_mem ⟨i, rfl⟩)
(tendsto.comp ennreal.tendsto_coe_sub (tendsto_id' inf_le_left)),
by rw [eq, ←this]; simp [Inf_image, infi_range, -mem_range]; exact le_refl _
end topological_space
section tsum
variables {f g : α → ennreal}
protected lemma has_sum_coe {f : α → nnreal} {r : nnreal} :
has_sum (λa, (f a : ennreal)) ↑r ↔ has_sum f r :=
have (λs:finset α, s.sum (coe ∘ f)) = (coe : nnreal → ennreal) ∘ (λs:finset α, s.sum f),
from funext $ assume s, ennreal.coe_finset_sum.symm,
by unfold has_sum; rw [this, tendsto_coe]
protected lemma tsum_coe_eq {f : α → nnreal} (h : has_sum f r) : (∑a, (f a : ennreal)) = r :=
tsum_eq_has_sum $ ennreal.has_sum_coe.2 $ h
protected lemma tsum_coe {f : α → nnreal} : summable f → (∑a, (f a : ennreal)) = ↑(tsum f)
| ⟨r, hr⟩ := by rw [tsum_eq_has_sum hr, ennreal.tsum_coe_eq hr]
protected lemma has_sum : has_sum f (⨆s:finset α, s.sum f) :=
tendsto_orderable.2
⟨assume a' ha',
let ⟨s, hs⟩ := lt_supr_iff.mp ha' in
mem_at_top_sets.mpr ⟨s, assume t ht, lt_of_lt_of_le hs $ finset.sum_le_sum_of_subset ht⟩,
assume a' ha',
univ_mem_sets' $ assume s,
have s.sum f ≤ ⨆(s : finset α), s.sum f,
from le_supr (λ(s : finset α), s.sum f) s,
lt_of_le_of_lt this ha'⟩
@[simp] protected lemma summable : summable f := ⟨_, ennreal.has_sum⟩
protected lemma tsum_eq_supr_sum : (∑a, f a) = (⨆s:finset α, s.sum f) :=
tsum_eq_has_sum ennreal.has_sum
protected lemma tsum_sigma {β : α → Type*} (f : Πa, β a → ennreal) :
(∑p:Σa, β a, f p.1 p.2) = (∑a b, f a b) :=
tsum_sigma (assume b, ennreal.summable) ennreal.summable
protected lemma tsum_prod {f : α → β → ennreal} : (∑p:α×β, f p.1 p.2) = (∑a, ∑b, f a b) :=
let j : α × β → (Σa:α, β) := λp, sigma.mk p.1 p.2 in
let i : (Σa:α, β) → α × β := λp, (p.1, p.2) in
let f' : (Σa:α, β) → ennreal := λp, f p.1 p.2 in
calc (∑p:α×β, f' (j p)) = (∑p:Σa:α, β, f p.1 p.2) :
tsum_eq_tsum_of_iso j i (assume ⟨a, b⟩, rfl) (assume ⟨a, b⟩, rfl)
... = (∑a, ∑b, f a b) : ennreal.tsum_sigma f
protected lemma tsum_comm {f : α → β → ennreal} : (∑a, ∑b, f a b) = (∑b, ∑a, f a b) :=
let f' : α×β → ennreal := λp, f p.1 p.2 in
calc (∑a, ∑b, f a b) = (∑p:α×β, f' p) : ennreal.tsum_prod.symm
... = (∑p:β×α, f' (prod.swap p)) :
(tsum_eq_tsum_of_iso prod.swap (@prod.swap α β) (assume ⟨a, b⟩, rfl) (assume ⟨a, b⟩, rfl)).symm
... = (∑b, ∑a, f' (prod.swap (b, a))) : @ennreal.tsum_prod β α (λb a, f' (prod.swap (b, a)))
protected lemma tsum_add : (∑a, f a + g a) = (∑a, f a) + (∑a, g a) :=
tsum_add ennreal.summable ennreal.summable
protected lemma tsum_le_tsum (h : ∀a, f a ≤ g a) : (∑a, f a) ≤ (∑a, g a) :=
tsum_le_tsum h ennreal.summable ennreal.summable
protected lemma tsum_eq_supr_nat {f : ℕ → ennreal} :
(∑i:ℕ, f i) = (⨆i:ℕ, (finset.range i).sum f) :=
calc _ = (⨆s:finset ℕ, s.sum f) : ennreal.tsum_eq_supr_sum
... = (⨆i:ℕ, (finset.range i).sum f) : le_antisymm
(supr_le_supr2 $ assume s,
let ⟨n, hn⟩ := finset.exists_nat_subset_range s in
⟨n, finset.sum_le_sum_of_subset hn⟩)
(supr_le_supr2 $ assume i, ⟨finset.range i, le_refl _⟩)
protected lemma le_tsum (a : α) : f a ≤ (∑a, f a) :=
calc f a = ({a} : finset α).sum f : by simp
... ≤ (⨆s:finset α, s.sum f) : le_supr (λs:finset α, s.sum f) _
... = (∑a, f a) : by rw [ennreal.tsum_eq_supr_sum]
protected lemma mul_tsum : (∑i, a * f i) = a * (∑i, f i) :=
if h : ∀i, f i = 0 then by simp [h] else
let ⟨i, (hi : f i ≠ 0)⟩ := classical.not_forall.mp h in
have sum_ne_0 : (∑i, f i) ≠ 0, from ne_of_gt $
calc 0 < f i : lt_of_le_of_ne (zero_le _) hi.symm
... ≤ (∑i, f i) : ennreal.le_tsum _,
have tendsto (λs:finset α, s.sum ((*) a ∘ f)) at_top (nhds (a * (∑i, f i))),
by rw [← show (*) a ∘ (λs:finset α, s.sum f) = λs, s.sum ((*) a ∘ f),
from funext $ λ s, finset.mul_sum];
exact ennreal.tendsto_mul_right (has_sum_tsum ennreal.summable) (or.inl sum_ne_0),
tsum_eq_has_sum this
protected lemma tsum_mul : (∑i, f i * a) = (∑i, f i) * a :=
by simp [mul_comm, ennreal.mul_tsum]
@[simp] lemma tsum_supr_eq {α : Type*} (a : α) {f : α → ennreal} :
(∑b:α, ⨆ (h : a = b), f b) = f a :=
le_antisymm
(by rw [ennreal.tsum_eq_supr_sum]; exact supr_le (assume s,
calc s.sum (λb, ⨆ (h : a = b), f b) ≤ (finset.singleton a).sum (λb, ⨆ (h : a = b), f b) :
finset.sum_le_sum_of_ne_zero $ assume b _ hb,
suffices a = b, by simpa using this.symm,
classical.by_contradiction $ assume h,
by simpa [h] using hb
... = f a : by simp))
(calc f a ≤ (⨆ (h : a = a), f a) : le_supr (λh:a=a, f a) rfl
... ≤ (∑b:α, ⨆ (h : a = b), f b) : ennreal.le_tsum _)
lemma has_sum_iff_tendsto_nat {f : ℕ → ennreal} (r : ennreal) :
has_sum f r ↔ tendsto (λn:ℕ, (finset.range n).sum f) at_top (nhds r) :=
begin
refine ⟨tendsto_sum_nat_of_has_sum, assume h, _⟩,
rw [← supr_eq_of_tendsto _ h, ← ennreal.tsum_eq_supr_nat],
{ exact has_sum_tsum ennreal.summable },
{ exact assume s t hst, finset.sum_le_sum_of_subset (finset.range_subset.2 hst) }
end
end tsum
end ennreal
namespace nnreal
lemma exists_le_has_sum_of_le {f g : β → nnreal} {r : nnreal}
(hgf : ∀b, g b ≤ f b) (hfr : has_sum f r) : ∃p≤r, has_sum g p :=
have (∑b, (g b : ennreal)) ≤ r,
begin
refine has_sum_le (assume b, _) (has_sum_tsum ennreal.summable) (ennreal.has_sum_coe.2 hfr),
exact ennreal.coe_le_coe.2 (hgf _)
end,
let ⟨p, eq, hpr⟩ := ennreal.le_coe_iff.1 this in
⟨p, hpr, ennreal.has_sum_coe.1 $ eq ▸ has_sum_tsum ennreal.summable⟩
lemma summable_of_le {f g : β → nnreal} (hgf : ∀b, g b ≤ f b) : summable f → summable g
| ⟨r, hfr⟩ := let ⟨p, _, hp⟩ := exists_le_has_sum_of_le hgf hfr in summable_spec hp
lemma has_sum_iff_tendsto_nat {f : ℕ → nnreal} (r : nnreal) :
has_sum f r ↔ tendsto (λn:ℕ, (finset.range n).sum f) at_top (nhds r) :=
begin
rw [← ennreal.has_sum_coe, ennreal.has_sum_iff_tendsto_nat],
simp only [ennreal.coe_finset_sum.symm],
exact ennreal.tendsto_coe
end
end nnreal
lemma summable_of_nonneg_of_le {f g : β → ℝ}
(hg : ∀b, 0 ≤ g b) (hgf : ∀b, g b ≤ f b) (hf : summable f) : summable g :=
let f' (b : β) : nnreal := ⟨f b, le_trans (hg b) (hgf b)⟩ in
let g' (b : β) : nnreal := ⟨g b, hg b⟩ in
have summable f', from nnreal.summable_coe.1 hf,
have summable g', from
nnreal.summable_of_le (assume b, (@nnreal.coe_le (g' b) (f' b)).2 $ hgf b) this,
show summable (λb, g' b : β → ℝ), from nnreal.summable_coe.2 this
lemma has_sum_iff_tendsto_nat_of_nonneg {f : ℕ → ℝ} (hf : ∀i, 0 ≤ f i) (r : ℝ) :
has_sum f r ↔ tendsto (λn:ℕ, (finset.range n).sum f) at_top (nhds r) :=
⟨tendsto_sum_nat_of_has_sum,
assume hfr,
have 0 ≤ r := ge_of_tendsto at_top_ne_bot hfr $ univ_mem_sets' $ assume i,
show 0 ≤ (finset.range i).sum f, from finset.sum_nonneg $ assume i _, hf i,
let f' (n : ℕ) : nnreal := ⟨f n, hf n⟩, r' : nnreal := ⟨r, this⟩ in
have f_eq : f = (λi:ℕ, (f' i : ℝ)) := rfl,
have r_eq : r = r' := rfl,
begin
rw [f_eq, r_eq, nnreal.has_sum_coe, nnreal.has_sum_iff_tendsto_nat, ← nnreal.tendsto_coe],
simp only [nnreal.sum_coe],
exact hfr
end⟩
lemma infi_real_pos_eq_infi_nnreal_pos {α : Type*} [complete_lattice α] {f : ℝ → α} :
(⨅(n:ℝ) (h : n > 0), f n) = (⨅(n:nnreal) (h : n > 0), f n) :=
le_antisymm
(le_infi $ assume n, le_infi $ assume hn, infi_le_of_le n $ infi_le _ (nnreal.coe_pos.2 hn))
(le_infi $ assume r, le_infi $ assume hr, infi_le_of_le ⟨r, le_of_lt hr⟩ $ infi_le _ hr)
section
variables [emetric_space β]
open lattice ennreal filter emetric
/-- In an emetric ball, the distance between points is everywhere finite -/
lemma edist_ne_top_of_mem_ball {a : β} {r : ennreal} (x y : ball a r) : edist x.1 y.1 ≠ ⊤ :=
lt_top_iff_ne_top.1 $
calc edist x y ≤ edist a x + edist a y : edist_triangle_left x.1 y.1 a
... < r + r : by rw [edist_comm a x, edist_comm a y]; exact add_lt_add x.2 y.2
... ≤ ⊤ : le_top
/-- Each ball in an extended metric space gives us a metric space, as the edist
is everywhere finite. -/
def metric_space_emetric_ball (a : β) (r : ennreal) : metric_space (ball a r) :=
emetric_space.to_metric_space edist_ne_top_of_mem_ball
local attribute [instance] metric_space_emetric_ball
lemma nhds_eq_nhds_emetric_ball (a x : β) (r : ennreal) (h : x ∈ ball a r) :
nhds x = map (coe : ball a r → β) (nhds ⟨x, h⟩) :=
(map_nhds_subtype_val_eq _ $ mem_nhds_sets emetric.is_open_ball h).symm
end
section
variable [emetric_space α]
open emetric
/-- Yet another metric characterization of Cauchy sequences on integers. This one is often the
most efficient. -/
lemma emetric.cauchy_seq_iff_le_tendsto_0 [inhabited β] [semilattice_sup β] {s : β → α} :
cauchy_seq s ↔ (∃ (b: β → ennreal), (∀ n m N : β, N ≤ n → N ≤ m → edist (s n) (s m) ≤ b N)
∧ (tendsto b at_top (nhds 0))) :=
⟨begin
assume hs,
rw emetric.cauchy_seq_iff at hs,
/- `s` is Cauchy sequence. The sequence `b` will be constructed by taking
the supremum of the distances between `s n` and `s m` for `n m ≥ N`-/
let b := λN, Sup ((λ(p : β × β), edist (s p.1) (s p.2))''{p | p.1 ≥ N ∧ p.2 ≥ N}),
--Prove that it bounds the distances of points in the Cauchy sequence
have C : ∀ n m N, N ≤ n → N ≤ m → edist (s n) (s m) ≤ b N,
{ refine λm n N hm hn, le_Sup _,
use (prod.mk m n),
simp only [and_true, eq_self_iff_true, set.mem_set_of_eq],
exact ⟨hm, hn⟩ },
--Prove that it tends to `0`, by using the Cauchy property of `s`
have D : tendsto b at_top (nhds 0),
{ refine tendsto_orderable.2 ⟨λa ha, absurd ha (ennreal.not_lt_zero), λε εpos, _⟩,
rcases dense εpos with ⟨δ, δpos, δlt⟩,
rcases hs δ δpos with ⟨N, hN⟩,
refine filter.mem_at_top_sets.2 ⟨N, λn hn, _⟩,
have : b n ≤ δ := Sup_le begin
simp only [and_imp, set.mem_image, set.mem_set_of_eq, exists_imp_distrib, prod.exists],
intros d p q hp hq hd,
rw ← hd,
exact le_of_lt (hN q p (le_trans hn hq) (le_trans hn hp))
end,
simpa using lt_of_le_of_lt this δlt },
-- Conclude
exact ⟨b, ⟨C, D⟩⟩
end,
begin
rintros ⟨b, ⟨b_bound, b_lim⟩⟩,
/-b : ℕ → ℝ, b_bound : ∀ (n m N : ℕ), N ≤ n → N ≤ m → edist (s n) (s m) ≤ b N,
b_lim : tendsto b at_top (nhds 0)-/
refine emetric.cauchy_seq_iff.2 (λε εpos, _),
have : {n | b n < ε} ∈ at_top := (tendsto_orderable.1 b_lim ).2 _ εpos,
rcases filter.mem_at_top_sets.1 this with ⟨N, hN⟩,
exact ⟨N, λm n hm hn, calc
edist (s n) (s m) ≤ b N : b_bound n m N hn hm
... < ε : (hN _ (le_refl N)) ⟩
end⟩
lemma continuous_of_le_add_edist {f : α → ennreal} (C : ennreal)
(hC : C ≠ ⊤) (h : ∀x y, f x ≤ f y + C * edist x y) : continuous f :=
begin
refine continuous_iff_continuous_at.2 (λx, tendsto_orderable.2 ⟨_, _⟩),
show ∀e, e < f x → {y : α | e < f y} ∈ nhds x,
{ assume e he,
let ε := min (f x - e) 1,
have : ε < ⊤ := lt_of_le_of_lt (min_le_right _ _) (by simp [lt_top_iff_ne_top]),
have : 0 < ε := by simp [ε, hC, he, ennreal.zero_lt_one],
have : 0 < C⁻¹ * (ε/2) := bot_lt_iff_ne_bot.2 (by simp [hC, (ne_of_lt this).symm, ennreal.mul_eq_zero]),
have I : C * (C⁻¹ * (ε/2)) < ε,
{ by_cases C_zero : C = 0,
{ simp [C_zero, ‹0 < ε›] },
{ calc C * (C⁻¹ * (ε/2)) = (C * C⁻¹) * (ε/2) : by simp [mul_assoc]
... = ε/2 : by simp [ennreal.mul_inv_cancel C_zero hC]
... < ε : ennreal.half_lt_self (bot_lt_iff_ne_bot.1 ‹0 < ε›) (lt_top_iff_ne_top.1 ‹ε < ⊤›) }},
have : ball x (C⁻¹ * (ε/2)) ⊆ {y : α | e < f y},
{ rintros y hy,
by_cases htop : f y = ⊤,
{ simp [htop, lt_top_iff_ne_top, ne_top_of_lt he] },
{ simp at hy,
have : e + ε < f y + ε := calc
e + ε ≤ e + (f x - e) : add_le_add_left' (min_le_left _ _)
... = f x : by simp [le_of_lt he]
... ≤ f y + C * edist x y : h x y
... = f y + C * edist y x : by simp [edist_comm]
... ≤ f y + C * (C⁻¹ * (ε/2)) :
add_le_add_left' $ canonically_ordered_semiring.mul_le_mul (le_refl _) (le_of_lt hy)
... < f y + ε : (ennreal.add_lt_add_iff_left (lt_top_iff_ne_top.2 htop)).2 I,
show e < f y, from
(ennreal.add_lt_add_iff_right ‹ε < ⊤›).1 this }},
apply filter.mem_sets_of_superset (ball_mem_nhds _ (‹0 < C⁻¹ * (ε/2)›)) this },
show ∀e, f x < e → {y : α | f y < e} ∈ nhds x,
{ assume e he,
let ε := min (e - f x) 1,
have : ε < ⊤ := lt_of_le_of_lt (min_le_right _ _) (by simp [lt_top_iff_ne_top]),
have : 0 < ε := by simp [ε, he, ennreal.zero_lt_one],
have : 0 < C⁻¹ * (ε/2) := bot_lt_iff_ne_bot.2 (by simp [hC, (ne_of_lt this).symm, ennreal.mul_eq_zero]),
have I : C * (C⁻¹ * (ε/2)) < ε,
{ by_cases C_zero : C = 0,
simp [C_zero, ‹0 < ε›],
calc C * (C⁻¹ * (ε/2)) = (C * C⁻¹) * (ε/2) : by simp [mul_assoc]
... = ε/2 : by simp [ennreal.mul_inv_cancel C_zero hC]
... < ε : ennreal.half_lt_self (bot_lt_iff_ne_bot.1 ‹0 < ε›) (lt_top_iff_ne_top.1 ‹ε < ⊤›) },
have : ball x (C⁻¹ * (ε/2)) ⊆ {y : α | f y < e},
{ rintros y hy,
have htop : f x ≠ ⊤ := ne_top_of_lt he,
show f y < e, from calc
f y ≤ f x + C * edist y x : h y x
... ≤ f x + C * (C⁻¹ * (ε/2)) :
add_le_add_left' $ canonically_ordered_semiring.mul_le_mul (le_refl _) (le_of_lt hy)
... < f x + ε : (ennreal.add_lt_add_iff_left (lt_top_iff_ne_top.2 htop)).2 I
... ≤ f x + (e - f x) : add_le_add_left' (min_le_left _ _)
... = e : by simp [le_of_lt he] },
apply filter.mem_sets_of_superset (ball_mem_nhds _ (‹0 < C⁻¹ * (ε/2)›)) this },
end
theorem continuous_edist' : continuous (λp:α×α, edist p.1 p.2) :=
begin
apply continuous_of_le_add_edist 2 (by simp),
rintros ⟨x, y⟩ ⟨x', y'⟩,
calc edist x y ≤ edist x x' + edist x' y' + edist y' y : edist_triangle4 _ _ _ _
... = edist x' y' + (edist x x' + edist y y') : by simp [add_comm, edist_comm]
... ≤ edist x' y' + (edist (x, y) (x', y') + edist (x, y) (x', y')) :
add_le_add_left' (add_le_add' (by simp [edist, le_refl]) (by simp [edist, le_refl]))
... = edist x' y' + 2 * edist (x, y) (x', y') : by rw [← mul_two, mul_comm]
end
theorem continuous_edist [topological_space β] {f g : β → α}
(hf : continuous f) (hg : continuous g) : continuous (λb, edist (f b) (g b)) :=
continuous_edist'.comp (hf.prod_mk hg)
theorem tendsto_edist {f g : β → α} {x : filter β} {a b : α}
(hf : tendsto f x (nhds a)) (hg : tendsto g x (nhds b)) :
tendsto (λx, edist (f x) (g x)) x (nhds (edist a b)) :=
have tendsto (λp:α×α, edist p.1 p.2) (nhds (a, b)) (nhds (edist a b)),
from continuous_iff_continuous_at.mp continuous_edist' (a, b),
tendsto.comp (by rw [nhds_prod_eq] at this; exact this) (hf.prod_mk hg)
end --section
|
6a69b9d4316e8932dcdaa2cfc02a30d5fa6bc6fd | b794ca1df49bc5a3bd3fd5552eed3bc4f63b8b93 | /src/mywork/mypractice_3.lean | f8fcacb7ada9c227bdd429aef664c74d4acd8af9 | [] | no_license | akraisinger/cs2120f21 | 8235ac98375e04ffcec504cff5cab7833ee69e54 | 4ef83d7151bb6a284028092aa4f1d509c0eb8237 | refs/heads/main | 1,691,714,771,612 | 1,632,889,465,000 | 1,632,889,465,000 | 399,946,508 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,848 | lean | -- 1
example : 0 ≠ 1 :=
begin
assume h,
cases h,
end
-- 2
example : 0 ≠ 0 → 2 = 3 :=
begin
assume h,
apply false.elim,
apply h,
apply eq.refl,
end
-- alternative answer
example : 0 ≠ 0 → 2 = 3 :=
begin
assume h,
have f : false := h (eq.refl 0),
exact false.elim (f)
end
-- 3
example : ∀ (P : Prop), P → ¬¬P :=
begin
assume P p,
assume h, -- ¬¬P is the same as ¬P → false is the same as (P → false) → false
have ph := h p,
exact ph, -- can also use cases f or exact false.elim f
end
-- alternative answer:
example : ∀ (P : Prop), P → ¬¬P :=
begin
assume P p,
assume h, -- ¬¬P is the same as ¬P → false is the same as (P → false) → false
contradiction,
end
-- We might need classical (vs constructive) reasoning
#check classical.em
open classical
#check em
/-
axiom em : ∀ (p : Prop), p ∧ ¬p
This is the famous and historically controversial
"law" (now axiom) of the excluded middle. It's is
a key to proving many intuitive theorems in logic
and mathematics. But it also leads to giving up on
having evidence *why* something is either true or
not tru, in that you no longer need a proof of
either P or of ¬P to have a proof of P ∨ ¬P.
-/
-- 4
theorem neg_elim : ∀ (P: Prop), ¬¬P → P :=
begin
assume P,
assume h,
-- the elimination rule of negation allows eliminate double negations?
-- cannot assume ¬¬P is true under PL? add law of excluded to follow
-- classical logic that it is true? some stuff only CLASSICALLY true
have pornp := classical.em P,
cases pornp,
exact pornp,
apply false.elim,
have hpornp := h pornp,
exact hpornp, -- could also use contradiction
end
-- 5
theorem demorgan_1 : ∀ (P Q : Prop), ¬ (P ∧ Q) ↔ ¬P :=
begin
end
-- 6
theorem demorgan_2 : ∀ (P Q : Prop), ¬ (P ∨ Q) → ¬P :=
begin
end |
0bb47e09fe88f1d96805e41141367eee4fdc3759 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/run/tactic29.lean | 7a3644545ee502e2a11e159346017302c29e11c2 | [
"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 | 331 | lean | import logic
open tactic
section
set_option pp.universes true
set_option pp.implicit true
variable {A : Type}
variables {a b : A}
variable H : a = b
variables H1 H2 : b = a
check H1
check H
check H2
include H
theorem test : a = b ∧ a = a
:= by apply and.intro; apply H; apply eq.refl
end
check @test
|
79e6603add1f265bd501e5867178ee3306bfdae3 | aa3f8992ef7806974bc1ffd468baa0c79f4d6643 | /tests/lean/run/have1.lean | be42f602c12f202584050bd9e6948b6998282b5b | [
"Apache-2.0"
] | permissive | codyroux/lean | 7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3 | 0cca265db19f7296531e339192e9b9bae4a31f8b | refs/heads/master | 1,610,909,964,159 | 1,407,084,399,000 | 1,416,857,075,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 176 | lean | definition Prop : Type.{1} := Type.{0}
constants a b c : Prop
axiom Ha : a
axiom Hb : b
axiom Hc : c
check have H1 : a, from Ha,
have H2 : a, using H1, from H1,
H2
|
6ded5c3d1455bc6eb2d491fbb0cfa2ff7efd4e60 | 6950a6e5cebf75da9b91f42789baf52514655111 | /problem_translation.lean | fe0f45a8812becd863310bc67d2337747a4ca8da | [] | no_license | phlippe/Lean_hammer | a6d0a1af09fbce0c58b801032099b9b91d49ecf0 | 2116279b9c6b334f5b661e4abf4561368cca2391 | refs/heads/master | 1,587,486,769,513 | 1,561,466,931,000 | 1,561,466,931,000 | 169,705,506 | 0 | 1 | null | 1,550,228,564,000 | 1,549,614,939,000 | Lean | UTF-8 | Lean | false | false | 6,990 | lean | import .tptp.tptp
import .tptp.translation_tptp
import .tptp.simplification_tptp
-- import .tff.tff
-- import .tff.translation_tff
-- import .tff.simplification_tff
--##################################
--## 5.3 Translating declarations ##
--##################################
meta def translate_axiom_expression: expr → hammer_tactic unit
-- | `()
| `(%%l = %%r) := -- c = t : τ
do (τ, _) ← using_hammer $ tactic.infer_type r, -- Get type of right side
-- tactic.trace l,
-- tactic.trace r,
lip <- lives_in_prop_p τ, -- Check whether τ is from type prop (and therefore right side a proof) or not
if lip
then -- If yes, add new axiom of F(τ) (TODO: and name c)
do fe1 ← (hammer_f τ),
Cn ← mk_fresh_name,
add_axiom Cn fe1
else -- Otherwise, add type checker G(c,τ) as new axiom
do (c,_) <- using_hammer (hammer_c l),
g_axiom <- hammer_g c τ,
Cn ← mk_fresh_name,
add_axiom Cn g_axiom,
lit <- lives_in_prop_p r, -- Check if τ=Prop (or rather t : Prop)
if lit
then -- If yes, add new axiom c ↔ F(t)
do (fe1,_) <- using_hammer (hammer_f l),
(fe2,_) <- using_hammer (hammer_f r),
Cn ← mk_fresh_name,
add_axiom Cn (folform.iff fe1 fe2)
else -- Otherwise, check whether τ is from type Set or Type, or another type
do lis <- lives_in_type r, -- TODO: Implement check of τ for Set and Type!
if lis
then
do xn ← mk_fresh_name,
let f := folterm.lconst xn xn,
-- let f := folterm.lconst xn (foltype.from_name xn),
-- a <- wrap_quantifier folform.all [(xn, xn)] (folform.iff (hammer_c $ folterm.app c f) (hammer_g f r)),
-- TODO: Implement the correct formula
let a := folform.top,
Cn <- mk_fresh_name,
add_axiom Cn a
else
do Cn <- mk_fresh_name,
(Cc,_) <- using_hammer (hammer_c r),
(Ct,_) <- using_hammer (hammer_c l),
add_axiom Cn (folform.eq Cc Ct)
-- Inductive declarations are handled in advance. Thus we don't have to check for them anymore
| `(%%c : _) := -- c : τ
do (τ, _) ← using_hammer $ tactic.infer_type c, -- Get type of right side
-- tactic.trace c,
lip <- lives_in_prop_p τ, -- Check whether τ is from type prop (and therefore right side a proof) or not
-- tactic.trace τ,
-- Note that if τ is Prop itself, then the type checker G ... will take care of it.
if lip
then
do Cn <- mk_fresh_name,
(Fτ,_) <- using_hammer (hammer_f τ),
add_axiom Cn Fτ
else
-- Additional check which is not in the paper. If the axiom is of type Prop, we want to add it as statement which must be true.
-- Thus, declarations like (Π(x:ℕ) x+x=2*x) are translated by applying F.
do lip <- lives_in_prop_p c,
if lip
then
do Cn <- mk_fresh_name,
(Fc,_) <- using_hammer (hammer_f c),
add_axiom Cn Fc
else
do Cn <- mk_fresh_name,
(Cc,_) <- using_hammer (hammer_c c),
(Gcτ,_) <- using_hammer (hammer_g Cc τ),
add_axiom Cn Gcτ
meta def lambda_expr_to_pi : expr → expr → tactic expr
| s e@(expr.lam n b a c) := do
tactic.trace n,
tactic.trace a,
tactic.trace c,
match c with
| cexp@(expr.lam n0 b0 a0 c0) := do
conv_exp ← lambda_expr_to_pi s cexp,
return $ expr.pi n b a conv_exp
| cexp := do
f ← lambda_expr_to_pi s cexp,
let pi_e := expr.pi n b a `(f = s),
return pi_e
end
| s e := return e -- All other forms are ignored
meta def process_declarations : list name → hammer_tactic unit
| [] := tactic.skip
| (x :: xs) :=
do
d ← tactic.get_decl x,
translate_axiom_expression d.value,
process_declarations xs
-- TODO: inductive declarations work, but not simple declarations! We get lambda expressions but need pi expression with equality
meta def expr_in_parts : expr → tactic expr
| e@(expr.lam n b a c) := do tactic.trace ("Lambda expression with var " ++ name.to_string n ++ " and type "), tactic.trace a, new_c <- (expr_in_parts c), return $ e
| e@(expr.pi n b a c) := do tactic.trace ("Pi expression with var " ++ name.to_string n ++ " and type "), tactic.trace a, new_c <- (expr_in_parts c), return $ e
| e@(expr.const n _) := do tactic.trace ("Constant with name " ++ name.to_string n), return $ e
| e@(expr.app t1 t2) := do tactic.trace ("Application"), new_t1 <- expr_in_parts t1, new_t2 <- expr_in_parts t2, return $ e
| e@(expr.local_const n n1 _ _) := do tactic.trace ("Local constant with name " ++ name.to_string n ++ " and second name " ++ name.to_string n1), return $ e
| e@(expr.elet x τ t s) := do tactic.trace ("Let expression"), return e
| e@(expr.var n) := do tactic.trace ("Variable "), tactic.trace n, return $ e
| e := do tactic.trace ("Unknown expression"), tactic.trace e, return e
--###############################
--## Final problem translation ##
--###############################
meta def translate_declaration (e : name) : hammer_tactic unit :=
do
env <- tactic.get_env,
d <- tactic.get_decl e,
l ← tactic.get_eqn_lemmas_for tt e,
process_declarations (l.append [e])
meta def translate_problem: list name → list expr → hammer_tactic unit
| [] [] := tactic.skip
| [] (x::xs) := do translate_axiom_expression x, translate_problem [] xs
| (y::ys) xs := do translate_declaration y, translate_problem ys xs
meta def problem_to_tptp_format (declr: list name) (clauses: list expr) (conjecture: expr) : hammer_tactic format :=
do
⟨cl,cl_state⟩ <- using_hammer (translate_problem declr clauses),
⟨conj,conj_state⟩ <- using_hammer (hammer_f conjecture),
⟨cl_list,conj⟩ <- simplify_terms (hammer_state.axiomas cl_state) conj,
-- let cl_list := (hammer_state.axiomas cl_state), -- For debugging, if no simplification should be applied
return $ export_formula cl_list conj
-- meta def problem_to_tff_format (declr: list name) (clauses: list expr) (conjecture: expr) : hammer_tactic format :=
-- do
-- ⟨cl,cl_state⟩ <- using_hammer (translate_problem declr clauses),
-- ⟨conj,conj_state⟩ <- using_hammer (hammer_f conjecture),
-- ⟨td_list,cl_list,conj⟩ <- simplify_terms (hammer_state.type_definitions cl_state) (hammer_state.axiomas cl_state) conj,
-- -- ⟨cl_list,conj⟩ <- simplify_terms cl_list conj, -- TODO: Fix problem of not getting all simplifications in the first run (see function comments)
-- return $ export_formula td_list cl_list conj |
27519cb95f8fdcbb327da453d8d5cbb3627e3c9b | 63abd62053d479eae5abf4951554e1064a4c45b4 | /test/ring_exp.lean | 4db918ff420faf2aaaef52056ae8805059cf3e42 | [
"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 | 6,367 | lean | import tactic.ring_exp
import algebra.group_with_zero_power
universes u
section addition
/-!
### `addition` section
Test associativity and commutativity of `(+)`.
-/
example (a b : ℚ) : a = a := by ring_exp
example (a b : ℚ) : a + b = a + b := by ring_exp
example (a b : ℚ) : b + a = a + b := by ring_exp
example (a b : ℤ) : a + b + b = b + (a + b) := by ring_exp
example (a b c : ℕ) : a + b + b + (c + c) = c + (b + c) + (a + b) := by ring_exp
end addition
section numerals
/-!
### `numerals` section
Test that numerals behave like rational numbers.
-/
example (a : ℕ) : a + 5 + 5 = 0 + a + 10 := by ring_exp
example (a : ℤ) : a + 5 + 5 = 0 + a + 10 := by ring_exp
example (a : ℚ) : (1/2) * a + (1/2) * a = a := by ring_exp
end numerals
section multiplication
/-!
### `multiplication section`
Test that multiplication is associative and commutative.
Also test distributivity of `(+)` and `(*)`.
-/
example (a : ℕ) : 0 = a * 0 := by ring_exp_eq
example (a : ℕ) : a = a * 1 := by ring_exp
example (a : ℕ) : a + a = a * 2 := by ring_exp
example (a b : ℤ) : a * b = b * a := by ring_exp
example (a b : ℕ) : a * 4 * b + a = a * (4 * b + 1) := by ring_exp
end multiplication
section exponentiation
/-!
### `exponentiation` section
Test that exponentiation has the correct distributivity properties.
-/
example : 0 ^ 1 = 0 := by ring_exp
example : 0 ^ 2 = 0 := by ring_exp
example (a : ℕ) : a ^ 0 = 1 := by ring_exp
example (a : ℕ) : a ^ 1 = a := by ring_exp
example (a : ℕ) : a ^ 2 = a * a := by ring_exp
example (a b : ℕ) : a ^ b = a ^ b := by ring_exp
example (a b : ℕ) : a ^ (b + 1) = a * a ^ b := by ring_exp
example (n : ℕ) (a m : ℕ) : a * a^n * m = a^(n+1) * m := by ring_exp
example (n : ℕ) (a m : ℕ) : m * a^n * a = a^(n+1) * m := by ring_exp
example (n : ℕ) (a m : ℤ) : a * a^n * m = a^(n+1) * m := by ring_exp
example (n : ℕ) (m : ℤ) : 2 * 2^n * m = 2^(n+1) * m := by ring_exp
example (n : ℕ) (m : ℤ) : 2^(n+1) * m = 2 * 2^n * m := by ring_exp
example (n m : ℕ) (a : ℤ) : (a ^ n)^m = a^(n * m) := by ring_exp
example (n m : ℕ) (a : ℤ) : a^(n^0) = a^1 := by ring_exp
example (n : ℕ) : 0^(n + 1) = 0 := by ring_exp
example {α} [comm_ring α] (x : α) (k : ℕ) : x ^ (k + 2) = x * x * x^k := by ring_exp
example {α} [comm_ring α] (k : ℕ) (x y z : α) :
x * (z * (x - y)) + (x * (y * y ^ k) - y * (y * y ^ k)) = (z * x + y * y ^ k) * (x - y)
:= by ring_exp
-- We can represent a large exponent `n` more efficiently than just `n` multiplications:
example (a b : ℚ) : (a * b) ^ 1000000 = (b * a) ^ 1000000 := by ring_exp
example (n : ℕ) : 2 ^ (n + 1 + 1) = 2 * 2 ^ (n + 1) :=
by ring_exp_eq
end exponentiation
section power_of_sum
/-!
### `power_of_sum` section
Test that raising a sum to a power behaves like repeated multiplication,
if needed.
-/
example (a b : ℤ) : (a + b)^2 = a^2 + b^2 + a * b + b * a := by ring_exp
example (a b : ℤ) (n : ℕ) : (a + b)^(n + 2) = (a^2 + b^2 + a * b + b * a) * (a + b)^n := by ring_exp
end power_of_sum
section negation
/-!
### `negation` section
Test that negation and subtraction satisfy the expected properties,
also in semirings such as `ℕ`.
-/
example {α} [comm_ring α] (a : α) : a - a = 0 := by ring_exp_eq
example (a : ℤ) : a - a = 0 := by ring_exp
example (a : ℤ) : a + - a = 0 := by ring_exp
example (a : ℤ) : - a = (-1) * a := by ring_exp
-- Here, (a - b) is treated as an atom.
example (a b : ℕ) : a - b + a + a = a - b + 2 * a := by ring_exp
example (n : ℕ) : n + 1 - 1 = n := by ring_exp! -- But we can force a bit of evaluation anyway.
end negation
constant f {α} : α → α
section complicated
/-!
### `complicated` section
Test that complicated, real-life expressions also get normalized.
-/
example {α : Type} [linear_ordered_field α] (x : α) :
2 * x + 1 * 1 - (2 * f (x + 1 / 2) + 2 * 1) + (1 * 1 - (2 * x - 2 * f (x + 1 / 2))) = 0
:= by ring_exp_eq
example {α : Type u} [linear_ordered_field α] (x : α) :
f (x + 1 / 2) ^ 1 * -2 + (f (x + 1 / 2) ^ 1 * 2 + 0) = 0
:= by ring_exp_eq
example (x y : ℕ) : x + id y = y + id x := by ring_exp!
-- Here, we check that `n - s` is not treated as `n + additive_inverse s`,
-- if `s` doesn't have an additive inverse.
example (B s n : ℕ) : B * (f s * ((n - s) * f (n - s - 1))) = B * (n - s) * (f s * f (n - s - 1)) :=
by ring_exp
-- This is a somewhat subtle case: `-c/b` is parsed as `(-c)/b`,
-- so we can't simply treat both sides of the division as atoms.
-- Instead, we follow the `ring` tactic in interpreting `-c / b` as `-c * b⁻¹`,
-- with only `b⁻¹` an atom.
example {α} [linear_ordered_field α] (a b c : α) : a*(-c/b)*(-c/b) = a*((c/b)*(c/b)) := by ring_exp
-- test that `field_simp` works fine with powers and `ring_exp`.
example (x y : ℚ) (n : ℕ) (hx : x ≠ 0) (hy : y ≠ 0) :
1/ (2/(x / y))^(2 * n) + y / y^(n+1) - (x/y)^n * (x/(2 * y))^n / 2 ^n = 1/y^n :=
begin
simp [sub_eq_add_neg],
field_simp [hx, hy],
ring_exp
end
end complicated
section conv
/-!
### `conv` section
Test that `ring_exp` works inside of `conv`, both with and without `!`.
-/
example (n : ℕ) : (2^n * 2 + 1)^10 = (2^(n+1) + 1)^10 :=
begin
conv_rhs
{ congr,
ring_exp, },
conv_lhs
{ congr,
ring_exp, },
end
example (x y : ℤ) : x + id y - y + id x = x * 2 := begin
conv_lhs { ring_exp!, },
end
end conv
section benchmark
/-!
### `benchmark` section
The `ring_exp` tactic shouldn't be too slow.
-/
-- This last example was copied from `data/polynomial.lean`, because it timed out.
-- After some optimization, it doesn't.
variables {α : Type} [comm_ring α]
def pow_sub_pow_factor (x y : α) : Π {i : ℕ},{z // x^i - y^i = z*(x - y)}
| 0 := ⟨0, by simp⟩
| 1 := ⟨1, by simp⟩
| (k+2) :=
begin
cases @pow_sub_pow_factor (k+1) with z hz,
existsi z*x + y^(k+1),
rw [pow_succ x, pow_succ y, ←sub_add_sub_cancel (x*x^(k+1)) (x*y^(k+1)),
←mul_sub x, hz],
ring_exp_eq
end
-- Another benchmark: bound the growth of the complexity somewhat.
example {α} [comm_semiring α] (x : α) : (x + 1) ^ 4 = (1 + x) ^ 4 := by try_for 5000 {ring_exp}
example {α} [comm_semiring α] (x : α) : (x + 1) ^ 6 = (1 + x) ^ 6 := by try_for 10000 {ring_exp}
example {α} [comm_semiring α] (x : α) : (x + 1) ^ 8 = (1 + x) ^ 8 := by try_for 15000 {ring_exp}
end benchmark
|
c8628c179c4d37c0bfe57cbba0a5e409f6fc0944 | 75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2 | /hott/types/list.hlean | 585bb569036d918cbe605c9196bd92fdc776897c | [
"Apache-2.0"
] | permissive | jroesch/lean | 30ef0860fa905d35b9ad6f76de1a4f65c9af6871 | 3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2 | refs/heads/master | 1,586,090,835,348 | 1,455,142,203,000 | 1,455,142,277,000 | 51,536,958 | 1 | 0 | null | 1,455,215,811,000 | 1,455,215,811,000 | null | UTF-8 | Lean | false | false | 36,107 | hlean | /-
Copyright (c) 2014 Parikshit Khanna. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn
Basic properties of lists.
Ported from the standard library (list.basic and list.comb)
Some lemmas are commented out, their proofs need to be repaired when needed
-/
import .pointed .nat .pi
open eq lift nat is_trunc pi pointed sum function prod option sigma algebra
inductive list (T : Type) : Type :=
| nil {} : list T
| cons : T → list T → list T
definition pointed_list [instance] (A : Type) : pointed (list A) :=
pointed.mk list.nil
namespace list
notation h :: t := cons h t
notation `[` l:(foldr `, ` (h t, cons h t) nil `]`) := l
universe variable u
variable {T : Type.{u}}
lemma cons_ne_nil (a : T) (l : list T) : a::l ≠ [] :=
by contradiction
lemma head_eq_of_cons_eq {A : Type} {h₁ h₂ : A} {t₁ t₂ : list A} :
(h₁::t₁) = (h₂::t₂) → h₁ = h₂ :=
assume Peq, down (list.no_confusion Peq (assume Pheq Pteq, Pheq))
lemma tail_eq_of_cons_eq {A : Type} {h₁ h₂ : A} {t₁ t₂ : list A} :
(h₁::t₁) = (h₂::t₂) → t₁ = t₂ :=
assume Peq, down (list.no_confusion Peq (assume Pheq Pteq, Pteq))
/- append -/
definition append : list T → list T → list T
| [] l := l
| (h :: s) t := h :: (append s t)
notation l₁ ++ l₂ := append l₁ l₂
theorem append_nil_left (t : list T) : [] ++ t = t := idp
theorem append_cons (x : T) (s t : list T) : (x::s) ++ t = x :: (s ++ t) := idp
theorem append_nil_right : ∀ (t : list T), t ++ [] = t
| [] := rfl
| (a :: l) := calc
(a :: l) ++ [] = a :: (l ++ []) : rfl
... = a :: l : append_nil_right l
theorem append.assoc : ∀ (s t u : list T), s ++ t ++ u = s ++ (t ++ u)
| [] t u := rfl
| (a :: l) t u :=
show a :: (l ++ t ++ u) = (a :: l) ++ (t ++ u),
by rewrite (append.assoc l t u)
/- length -/
definition length : list T → nat
| [] := 0
| (a :: l) := length l + 1
theorem length_nil : length (@nil T) = 0 := idp
theorem length_cons (x : T) (t : list T) : length (x::t) = length t + 1 := idp
theorem length_append : ∀ (s t : list T), length (s ++ t) = length s + length t
| [] t := calc
length ([] ++ t) = length t : rfl
... = length [] + length t : by rewrite [length_nil, zero_add]
| (a :: s) t := calc
length (a :: s ++ t) = length (s ++ t) + 1 : rfl
... = length s + length t + 1 : length_append
... = (length s + 1) + length t : succ_add
... = length (a :: s) + length t : rfl
theorem eq_nil_of_length_eq_zero : ∀ {l : list T}, length l = 0 → l = []
| [] H := rfl
| (a::s) H := by contradiction
theorem ne_nil_of_length_eq_succ : ∀ {l : list T} {n : nat}, length l = succ n → l ≠ []
| [] n h := by contradiction
| (a::l) n h := by contradiction
-- add_rewrite length_nil length_cons
/- concat -/
definition concat : Π (x : T), list T → list T
| a [] := [a]
| a (b :: l) := b :: concat a l
theorem concat_nil (x : T) : concat x [] = [x] := idp
theorem concat_cons (x y : T) (l : list T) : concat x (y::l) = y::(concat x l) := idp
theorem concat_eq_append (a : T) : ∀ (l : list T), concat a l = l ++ [a]
| [] := rfl
| (b :: l) :=
show b :: (concat a l) = (b :: l) ++ (a :: []),
by rewrite concat_eq_append
theorem concat_ne_nil (a : T) : ∀ (l : list T), concat a l ≠ [] :=
by intro l; induction l; repeat contradiction
theorem length_concat (a : T) : ∀ (l : list T), length (concat a l) = length l + 1
| [] := rfl
| (x::xs) := by rewrite [concat_cons, *length_cons, length_concat]
theorem concat_append (a : T) : ∀ (l₁ l₂ : list T), concat a l₁ ++ l₂ = l₁ ++ a :: l₂
| [] := λl₂, rfl
| (x::xs) := λl₂, begin rewrite [concat_cons,append_cons, concat_append] end
theorem append_concat (a : T) : ∀(l₁ l₂ : list T), l₁ ++ concat a l₂ = concat a (l₁ ++ l₂)
| [] := λl₂, rfl
| (x::xs) := λl₂, begin rewrite [+append_cons, concat_cons, append_concat] end
/- last -/
definition last : Π l : list T, l ≠ [] → T
| [] h := absurd rfl h
| [a] h := a
| (a₁::a₂::l) h := last (a₂::l) !cons_ne_nil
lemma last_singleton (a : T) (h : [a] ≠ []) : last [a] h = a :=
rfl
lemma last_cons_cons (a₁ a₂ : T) (l : list T) (h : a₁::a₂::l ≠ [])
: last (a₁::a₂::l) h = last (a₂::l) !cons_ne_nil :=
rfl
theorem last_congr {l₁ l₂ : list T} (h₁ : l₁ ≠ []) (h₂ : l₂ ≠ []) (h₃ : l₁ = l₂)
: last l₁ h₁ = last l₂ h₂ :=
apd011 last h₃ !is_hprop.elim
theorem last_concat {x : T} : ∀ {l : list T} (h : concat x l ≠ []), last (concat x l) h = x
| [] h := rfl
| [a] h := rfl
| (a₁::a₂::l) h :=
begin
change last (a₁::a₂::concat x l) !cons_ne_nil = x,
rewrite last_cons_cons,
change last (concat x (a₂::l)) (cons_ne_nil a₂ (concat x l)) = x,
apply last_concat
end
-- add_rewrite append_nil append_cons
/- reverse -/
definition reverse : list T → list T
| [] := []
| (a :: l) := concat a (reverse l)
theorem reverse_nil : reverse (@nil T) = [] := idp
theorem reverse_cons (x : T) (l : list T) : reverse (x::l) = concat x (reverse l) := idp
theorem reverse_singleton (x : T) : reverse [x] = [x] := idp
theorem reverse_append : ∀ (s t : list T), reverse (s ++ t) = (reverse t) ++ (reverse s)
| [] t2 := calc
reverse ([] ++ t2) = reverse t2 : rfl
... = (reverse t2) ++ [] : append_nil_right
... = (reverse t2) ++ (reverse []) : by rewrite reverse_nil
| (a2 :: s2) t2 := calc
reverse ((a2 :: s2) ++ t2) = concat a2 (reverse (s2 ++ t2)) : rfl
... = concat a2 (reverse t2 ++ reverse s2) : reverse_append
... = (reverse t2 ++ reverse s2) ++ [a2] : concat_eq_append
... = reverse t2 ++ (reverse s2 ++ [a2]) : append.assoc
... = reverse t2 ++ concat a2 (reverse s2) : concat_eq_append
... = reverse t2 ++ reverse (a2 :: s2) : rfl
theorem reverse_reverse : ∀ (l : list T), reverse (reverse l) = l
| [] := rfl
| (a :: l) := calc
reverse (reverse (a :: l)) = reverse (concat a (reverse l)) : rfl
... = reverse (reverse l ++ [a]) : concat_eq_append
... = reverse [a] ++ reverse (reverse l) : reverse_append
... = reverse [a] ++ l : reverse_reverse
... = a :: l : rfl
theorem concat_eq_reverse_cons (x : T) (l : list T) : concat x l = reverse (x :: reverse l) :=
calc
concat x l = concat x (reverse (reverse l)) : reverse_reverse
... = reverse (x :: reverse l) : rfl
theorem length_reverse : ∀ (l : list T), length (reverse l) = length l
| [] := rfl
| (x::xs) := begin unfold reverse, rewrite [length_concat, length_cons, length_reverse] end
/- head and tail -/
definition head [h : pointed T] : list T → T
| [] := pt
| (a :: l) := a
theorem head_cons [h : pointed T] (a : T) (l : list T) : head (a::l) = a := idp
theorem head_append [h : pointed T] (t : list T) : ∀ {s : list T}, s ≠ [] → head (s ++ t) = head s
| [] H := absurd rfl H
| (a :: s) H :=
show head (a :: (s ++ t)) = head (a :: s),
by rewrite head_cons
definition tail : list T → list T
| [] := []
| (a :: l) := l
theorem tail_nil : tail (@nil T) = [] := idp
theorem tail_cons (a : T) (l : list T) : tail (a::l) = l := idp
theorem cons_head_tail [h : pointed T] {l : list T} : l ≠ [] → (head l)::(tail l) = l :=
list.cases_on l
(suppose [] ≠ [], absurd rfl this)
(take x l, suppose x::l ≠ [], rfl)
/- list membership -/
definition mem : T → list T → Type.{u}
| a [] := lift empty
| a (b :: l) := a = b ⊎ mem a l
notation e ∈ s := mem e s
notation e ∉ s := ¬ e ∈ s
theorem mem_nil_iff (x : T) : x ∈ [] ↔ empty :=
iff.intro down up
theorem not_mem_nil (x : T) : x ∉ [] :=
iff.mp !mem_nil_iff
theorem mem_cons (x : T) (l : list T) : x ∈ x :: l :=
sum.inl rfl
theorem mem_cons_of_mem (y : T) {x : T} {l : list T} : x ∈ l → x ∈ y :: l :=
assume H, sum.inr H
theorem mem_cons_iff (x y : T) (l : list T) : x ∈ y::l ↔ (x = y ⊎ x ∈ l) :=
iff.rfl
theorem eq_or_mem_of_mem_cons {x y : T} {l : list T} : x ∈ y::l → x = y ⊎ x ∈ l :=
assume h, h
theorem mem_singleton {x a : T} : x ∈ [a] → x = a :=
suppose x ∈ [a], sum.rec_on (eq_or_mem_of_mem_cons this)
(suppose x = a, this)
(suppose x ∈ [], absurd this !not_mem_nil)
theorem mem_of_mem_cons_of_mem {a b : T} {l : list T} : a ∈ b::l → b ∈ l → a ∈ l :=
assume ainbl binl, sum.rec_on (eq_or_mem_of_mem_cons ainbl)
(suppose a = b, by substvars; exact binl)
(suppose a ∈ l, this)
theorem mem_or_mem_of_mem_append {x : T} {s t : list T} : x ∈ s ++ t → x ∈ s ⊎ x ∈ t :=
list.rec_on s sum.inr
(take y s,
assume IH : x ∈ s ++ t → x ∈ s ⊎ x ∈ t,
suppose x ∈ y::s ++ t,
have x = y ⊎ x ∈ s ++ t, from this,
have x = y ⊎ x ∈ s ⊎ x ∈ t, from sum_of_sum_of_imp_right this IH,
iff.elim_right sum.assoc this)
theorem mem_append_of_mem_or_mem {x : T} {s t : list T} : (x ∈ s ⊎ x ∈ t) → x ∈ s ++ t :=
list.rec_on s
(take H, sum.rec_on H (empty.elim ∘ down) (assume H, H))
(take y s,
assume IH : (x ∈ s ⊎ x ∈ t) → x ∈ s ++ t,
suppose x ∈ y::s ⊎ x ∈ t,
sum.rec_on this
(suppose x ∈ y::s,
sum.rec_on (eq_or_mem_of_mem_cons this)
(suppose x = y, sum.inl this)
(suppose x ∈ s, sum.inr (IH (sum.inl this))))
(suppose x ∈ t, sum.inr (IH (sum.inr this))))
theorem mem_append_iff (x : T) (s t : list T) : x ∈ s ++ t ↔ x ∈ s ⊎ x ∈ t :=
iff.intro mem_or_mem_of_mem_append mem_append_of_mem_or_mem
theorem not_mem_of_not_mem_append_left {x : T} {s t : list T} : x ∉ s++t → x ∉ s :=
λ nxinst xins, absurd (mem_append_of_mem_or_mem (sum.inl xins)) nxinst
theorem not_mem_of_not_mem_append_right {x : T} {s t : list T} : x ∉ s++t → x ∉ t :=
λ nxinst xint, absurd (mem_append_of_mem_or_mem (sum.inr xint)) nxinst
theorem not_mem_append {x : T} {s t : list T} : x ∉ s → x ∉ t → x ∉ s++t :=
λ nxins nxint xinst, sum.rec_on (mem_or_mem_of_mem_append xinst)
(λ xins, by contradiction)
(λ xint, by contradiction)
lemma length_pos_of_mem {a : T} : ∀ {l : list T}, a ∈ l → 0 < length l
| [] := assume Pinnil, by induction Pinnil; contradiction
| (b::l) := assume Pin, !zero_lt_succ
local attribute mem [reducible]
local attribute append [reducible]
theorem mem_split {x : T} {l : list T} : x ∈ l → Σs t : list T, l = s ++ (x::t) :=
list.rec_on l
(suppose x ∈ [], empty.elim (iff.elim_left !mem_nil_iff this))
(take y l,
assume IH : x ∈ l → Σs t : list T, l = s ++ (x::t),
suppose x ∈ y::l,
sum.rec_on (eq_or_mem_of_mem_cons this)
(suppose x = y,
sigma.mk [] (!sigma.mk (this ▸ rfl)))
(suppose x ∈ l,
obtain s (H2 : Σt : list T, l = s ++ (x::t)), from IH this,
obtain t (H3 : l = s ++ (x::t)), from H2,
have y :: l = (y::s) ++ (x::t),
from H3 ▸ rfl,
!sigma.mk (!sigma.mk this)))
theorem mem_append_left {a : T} {l₁ : list T} (l₂ : list T) : a ∈ l₁ → a ∈ l₁ ++ l₂ :=
assume ainl₁, mem_append_of_mem_or_mem (sum.inl ainl₁)
theorem mem_append_right {a : T} (l₁ : list T) {l₂ : list T} : a ∈ l₂ → a ∈ l₁ ++ l₂ :=
assume ainl₂, mem_append_of_mem_or_mem (sum.inr ainl₂)
definition decidable_mem [instance] [H : decidable_eq T] (x : T) (l : list T) : decidable (x ∈ l) :=
list.rec_on l
(decidable.inr begin intro x, induction x, contradiction end)
(take (h : T) (l : list T) (iH : decidable (x ∈ l)),
show decidable (x ∈ h::l), from
decidable.rec_on iH
(assume Hp : x ∈ l,
decidable.rec_on (H x h)
(suppose x = h,
decidable.inl (sum.inl this))
(suppose x ≠ h,
decidable.inl (sum.inr Hp)))
(suppose ¬x ∈ l,
decidable.rec_on (H x h)
(suppose x = h, decidable.inl (sum.inl this))
(suppose x ≠ h,
have ¬(x = h ⊎ x ∈ l), from
suppose x = h ⊎ x ∈ l, sum.rec_on this
(suppose x = h, by contradiction)
(suppose x ∈ l, by contradiction),
have ¬x ∈ h::l, from
iff.elim_right (not_iff_not_of_iff !mem_cons_iff) this,
decidable.inr this)))
theorem mem_of_ne_of_mem {x y : T} {l : list T} (H₁ : x ≠ y) (H₂ : x ∈ y :: l) : x ∈ l :=
sum.rec_on (eq_or_mem_of_mem_cons H₂) (λe, absurd e H₁) (λr, r)
theorem ne_of_not_mem_cons {a b : T} {l : list T} : a ∉ b::l → a ≠ b :=
assume nin aeqb, absurd (sum.inl aeqb) nin
theorem not_mem_of_not_mem_cons {a b : T} {l : list T} : a ∉ b::l → a ∉ l :=
assume nin nainl, absurd (sum.inr nainl) nin
lemma not_mem_cons_of_ne_of_not_mem {x y : T} {l : list T} : x ≠ y → x ∉ l → x ∉ y::l :=
assume P1 P2, not.intro (assume Pxin, absurd (eq_or_mem_of_mem_cons Pxin) (not_sum P1 P2))
lemma ne_and_not_mem_of_not_mem_cons {x y : T} {l : list T} : x ∉ y::l → x ≠ y × x ∉ l :=
assume P, prod.mk (ne_of_not_mem_cons P) (not_mem_of_not_mem_cons P)
definition sublist (l₁ l₂ : list T) := ∀ ⦃a : T⦄, a ∈ l₁ → a ∈ l₂
infix ⊆ := sublist
theorem nil_sub (l : list T) : [] ⊆ l :=
λ b i, empty.elim (iff.mp (mem_nil_iff b) i)
theorem sub.refl (l : list T) : l ⊆ l :=
λ b i, i
theorem sub.trans {l₁ l₂ l₃ : list T} (H₁ : l₁ ⊆ l₂) (H₂ : l₂ ⊆ l₃) : l₁ ⊆ l₃ :=
λ b i, H₂ (H₁ i)
theorem sub_cons (a : T) (l : list T) : l ⊆ a::l :=
λ b i, sum.inr i
theorem sub_of_cons_sub {a : T} {l₁ l₂ : list T} : a::l₁ ⊆ l₂ → l₁ ⊆ l₂ :=
λ s b i, s b (mem_cons_of_mem _ i)
theorem cons_sub_cons {l₁ l₂ : list T} (a : T) (s : l₁ ⊆ l₂) : (a::l₁) ⊆ (a::l₂) :=
λ b Hin, sum.rec_on (eq_or_mem_of_mem_cons Hin)
(λ e : b = a, sum.inl e)
(λ i : b ∈ l₁, sum.inr (s i))
theorem sub_append_left (l₁ l₂ : list T) : l₁ ⊆ l₁++l₂ :=
λ b i, iff.mpr (mem_append_iff b l₁ l₂) (sum.inl i)
theorem sub_append_right (l₁ l₂ : list T) : l₂ ⊆ l₁++l₂ :=
λ b i, iff.mpr (mem_append_iff b l₁ l₂) (sum.inr i)
theorem sub_cons_of_sub (a : T) {l₁ l₂ : list T} : l₁ ⊆ l₂ → l₁ ⊆ (a::l₂) :=
λ (s : l₁ ⊆ l₂) (x : T) (i : x ∈ l₁), sum.inr (s i)
theorem sub_app_of_sub_left (l l₁ l₂ : list T) : l ⊆ l₁ → l ⊆ l₁++l₂ :=
λ (s : l ⊆ l₁) (x : T) (xinl : x ∈ l),
have x ∈ l₁, from s xinl,
mem_append_of_mem_or_mem (sum.inl this)
theorem sub_app_of_sub_right (l l₁ l₂ : list T) : l ⊆ l₂ → l ⊆ l₁++l₂ :=
λ (s : l ⊆ l₂) (x : T) (xinl : x ∈ l),
have x ∈ l₂, from s xinl,
mem_append_of_mem_or_mem (sum.inr this)
theorem cons_sub_of_sub_of_mem {a : T} {l m : list T} : a ∈ m → l ⊆ m → a::l ⊆ m :=
λ (ainm : a ∈ m) (lsubm : l ⊆ m) (x : T) (xinal : x ∈ a::l), sum.rec_on (eq_or_mem_of_mem_cons xinal)
(suppose x = a, by substvars; exact ainm)
(suppose x ∈ l, lsubm this)
theorem app_sub_of_sub_of_sub {l₁ l₂ l : list T} : l₁ ⊆ l → l₂ ⊆ l → l₁++l₂ ⊆ l :=
λ (l₁subl : l₁ ⊆ l) (l₂subl : l₂ ⊆ l) (x : T) (xinl₁l₂ : x ∈ l₁++l₂),
sum.rec_on (mem_or_mem_of_mem_append xinl₁l₂)
(suppose x ∈ l₁, l₁subl this)
(suppose x ∈ l₂, l₂subl this)
/- find -/
section
variable [H : decidable_eq T]
include H
definition find : T → list T → nat
| a [] := 0
| a (b :: l) := if a = b then 0 else succ (find a l)
theorem find_nil (x : T) : find x [] = 0 := idp
theorem find_cons (x y : T) (l : list T) : find x (y::l) = if x = y then 0 else succ (find x l) :=
idp
theorem find_cons_of_eq {x y : T} (l : list T) : x = y → find x (y::l) = 0 :=
assume e, if_pos e
theorem find_cons_of_ne {x y : T} (l : list T) : x ≠ y → find x (y::l) = succ (find x l) :=
assume n, if_neg n
/-theorem find_of_not_mem {l : list T} {x : T} : ¬x ∈ l → find x l = length l :=
list.rec_on l
(suppose ¬x ∈ [], _)
(take y l,
assume iH : ¬x ∈ l → find x l = length l,
suppose ¬x ∈ y::l,
have ¬(x = y ⊎ x ∈ l), from iff.elim_right (not_iff_not_of_iff !mem_cons_iff) this,
have ¬x = y × ¬x ∈ l, from (iff.elim_left not_sum_iff_not_prod_not this),
calc
find x (y::l) = if x = y then 0 else succ (find x l) : !find_cons
... = succ (find x l) : if_neg (prod.pr1 this)
... = succ (length l) : {iH (prod.pr2 this)}
... = length (y::l) : !length_cons⁻¹)-/
lemma find_le_length : ∀ {a} {l : list T}, find a l ≤ length l
| a [] := !le.refl
| a (b::l) := decidable.rec_on (H a b)
(assume Peq, by rewrite [find_cons_of_eq l Peq]; exact !zero_le)
(assume Pne,
begin
rewrite [find_cons_of_ne l Pne, length_cons],
apply succ_le_succ, apply find_le_length
end)
/-lemma not_mem_of_find_eq_length : ∀ {a} {l : list T}, find a l = length l → a ∉ l
| a [] := assume Peq, !not_mem_nil
| a (b::l) := decidable.rec_on (H a b)
(assume Peq, by rewrite [find_cons_of_eq l Peq, length_cons]; contradiction)
(assume Pne,
begin
rewrite [find_cons_of_ne l Pne, length_cons, mem_cons_iff],
intro Plen, apply (not_or Pne),
exact not_mem_of_find_eq_length (succ.inj Plen)
end)-/
/-lemma find_lt_length {a} {l : list T} (Pin : a ∈ l) : find a l < length l :=
begin
apply nat.lt_of_le_prod_ne,
apply find_le_length,
apply not.intro, intro Peq,
exact absurd Pin (not_mem_of_find_eq_length Peq)
end-/
end
/- nth element -/
section nth
definition nth : list T → nat → option T
| [] n := none
| (a :: l) 0 := some a
| (a :: l) (n+1) := nth l n
theorem nth_zero (a : T) (l : list T) : nth (a :: l) 0 = some a := idp
theorem nth_succ (a : T) (l : list T) (n : nat) : nth (a::l) (succ n) = nth l n := idp
theorem nth_eq_some : ∀ {l : list T} {n : nat}, n < length l → Σ a : T, nth l n = some a
| [] n h := absurd h !not_lt_zero
| (a::l) 0 h := ⟨a, rfl⟩
| (a::l) (succ n) h :=
have n < length l, from lt_of_succ_lt_succ h,
obtain (r : T) (req : nth l n = some r), from nth_eq_some this,
⟨r, by rewrite [nth_succ, req]⟩
open decidable
theorem find_nth [h : decidable_eq T] {a : T} : ∀ {l}, a ∈ l → nth l (find a l) = some a
| [] ain := absurd ain !not_mem_nil
| (b::l) ainbl := by_cases
(λ aeqb : a = b, by rewrite [find_cons_of_eq _ aeqb, nth_zero, aeqb])
(λ aneb : a ≠ b, sum.rec_on (eq_or_mem_of_mem_cons ainbl)
(λ aeqb : a = b, absurd aeqb aneb)
(λ ainl : a ∈ l, by rewrite [find_cons_of_ne _ aneb, nth_succ, find_nth ainl]))
definition inth [h : pointed T] (l : list T) (n : nat) : T :=
match nth l n with
| some a := a
| none := pt
end
theorem inth_zero [h : pointed T] (a : T) (l : list T) : inth (a :: l) 0 = a := idp
theorem inth_succ [h : pointed T] (a : T) (l : list T) (n : nat) : inth (a::l) (n+1) = inth l n :=
idp
end nth
section ith
definition ith : Π (l : list T) (i : nat), i < length l → T
| nil i h := absurd h !not_lt_zero
| (x::xs) 0 h := x
| (x::xs) (succ i) h := ith xs i (lt_of_succ_lt_succ h)
lemma ith_zero (a : T) (l : list T) (h : 0 < length (a::l)) : ith (a::l) 0 h = a :=
rfl
lemma ith_succ (a : T) (l : list T) (i : nat) (h : succ i < length (a::l))
: ith (a::l) (succ i) h = ith l i (lt_of_succ_lt_succ h) :=
rfl
end ith
open decidable
definition has_decidable_eq {A : Type} [H : decidable_eq A] : ∀ l₁ l₂ : list A, decidable (l₁ = l₂)
| [] [] := inl rfl
| [] (b::l₂) := inr (by contradiction)
| (a::l₁) [] := inr (by contradiction)
| (a::l₁) (b::l₂) :=
match H a b with
| inl Hab :=
match has_decidable_eq l₁ l₂ with
| inl He := inl (by congruence; repeat assumption)
| inr Hn := inr (by intro H; injection H; contradiction)
end
| inr Hnab := inr (by intro H; injection H; contradiction)
end
/- quasiequal a l l' means that l' is exactly l, with a added
once somewhere -/
section qeq
variable {A : Type.{u}}
inductive qeq (a : A) : list A → list A → Type.{u} :=
| qhead : ∀ l, qeq a l (a::l)
| qcons : ∀ (b : A) {l l' : list A}, qeq a l l' → qeq a (b::l) (b::l')
open qeq
notation l' `≈`:50 a `|` l:50 := qeq a l l'
theorem qeq_app : ∀ (l₁ : list A) (a : A) (l₂ : list A), l₁++(a::l₂) ≈ a|l₁++l₂
| [] a l₂ := qhead a l₂
| (x::xs) a l₂ := qcons x (qeq_app xs a l₂)
theorem mem_head_of_qeq {a : A} {l₁ l₂ : list A} : l₁≈a|l₂ → a ∈ l₁ :=
take q, qeq.rec_on q
(λ l, !mem_cons)
(λ b l l' q r, sum.inr r)
theorem mem_tail_of_qeq {a : A} {l₁ l₂ : list A} : l₁≈a|l₂ → ∀ x, x ∈ l₂ → x ∈ l₁ :=
take q, qeq.rec_on q
(λ l x i, sum.inr i)
(λ b l l' q r x xinbl, sum.rec_on (eq_or_mem_of_mem_cons xinbl)
(λ xeqb : x = b, xeqb ▸ mem_cons x l')
(λ xinl : x ∈ l, sum.inr (r x xinl)))
/-
theorem mem_cons_of_qeq {a : A} {l₁ l₂ : list A} : l₁≈a|l₂ → ∀ x, x ∈ l₁ → x ∈ a::l₂ :=
take q, qeq.rec_on q
(λ l x i, i)
(λ b l l' q r x xinbl', sum.elim_on (eq_or_mem_of_mem_cons xinbl')
(λ xeqb : x = b, xeqb ▸ sum.inr (mem_cons x l))
(λ xinl' : x ∈ l', sum.rec_on (eq_or_mem_of_mem_cons (r x xinl'))
(λ xeqa : x = a, xeqa ▸ mem_cons x (b::l))
(λ xinl : x ∈ l, sum.inr (sum.inr xinl))))-/
theorem length_eq_of_qeq {a : A} {l₁ l₂ : list A} : l₁≈a|l₂ → length l₁ = succ (length l₂) :=
take q, qeq.rec_on q
(λ l, rfl)
(λ b l l' q r, by rewrite [*length_cons, r])
theorem qeq_of_mem {a : A} {l : list A} : a ∈ l → (Σl', l≈a|l') :=
list.rec_on l
(λ h : a ∈ nil, absurd h (not_mem_nil a))
(λ x xs r ainxxs, sum.rec_on (eq_or_mem_of_mem_cons ainxxs)
(λ aeqx : a = x,
assert aux : Σ l, x::xs≈x|l, from
sigma.mk xs (qhead x xs),
by rewrite aeqx; exact aux)
(λ ainxs : a ∈ xs,
have Σl', xs ≈ a|l', from r ainxs,
obtain (l' : list A) (q : xs ≈ a|l'), from this,
have x::xs ≈ a | x::l', from qcons x q,
sigma.mk (x::l') this))
theorem qeq_split {a : A} {l l' : list A} : l'≈a|l → Σl₁ l₂, l = l₁++l₂ × l' = l₁++(a::l₂) :=
take q, qeq.rec_on q
(λ t,
have t = []++t × a::t = []++(a::t), from prod.mk rfl rfl,
sigma.mk [] (sigma.mk t this))
(λ b t t' q r,
obtain (l₁ l₂ : list A) (h : t = l₁++l₂ × t' = l₁++(a::l₂)), from r,
have b::t = (b::l₁)++l₂ × b::t' = (b::l₁)++(a::l₂),
begin
rewrite [prod.pr2 h, prod.pr1 h],
constructor, repeat reflexivity
end,
sigma.mk (b::l₁) (sigma.mk l₂ this))
/-theorem sub_of_mem_of_sub_of_qeq {a : A} {l : list A} {u v : list A} : a ∉ l → a::l ⊆ v → v≈a|u → l ⊆ u :=
λ (nainl : a ∉ l) (s : a::l ⊆ v) (q : v≈a|u) (x : A) (xinl : x ∈ l),
have x ∈ v, from s (sum.inr xinl),
have x ∈ a::u, from mem_cons_of_qeq q x this,
sum.rec_on (eq_or_mem_of_mem_cons this)
(suppose x = a, by substvars; contradiction)
(suppose x ∈ u, this)-/
end qeq
section firstn
variable {A : Type}
definition firstn : nat → list A → list A
| 0 l := []
| (n+1) [] := []
| (n+1) (a::l) := a :: firstn n l
lemma firstn_zero : ∀ (l : list A), firstn 0 l = [] :=
by intros; reflexivity
lemma firstn_nil : ∀ n, firstn n [] = ([] : list A)
| 0 := rfl
| (n+1) := rfl
lemma firstn_cons : ∀ n (a : A) (l : list A), firstn (succ n) (a::l) = a :: firstn n l :=
by intros; reflexivity
lemma firstn_all : ∀ (l : list A), firstn (length l) l = l
| [] := rfl
| (a::l) := begin unfold [length, firstn], rewrite firstn_all end
/-lemma firstn_all_of_ge : ∀ {n} {l : list A}, n ≥ length l → firstn n l = l
| 0 [] h := rfl
| 0 (a::l) h := absurd h (not_le_of_gt !succ_pos)
| (n+1) [] h := rfl
| (n+1) (a::l) h := begin unfold firstn, rewrite [firstn_all_of_ge (le_of_succ_le_succ h)] end-/
/-lemma firstn_firstn : ∀ (n m) (l : list A), firstn n (firstn m l) = firstn (min n m) l
| n 0 l := by rewrite [min_zero, firstn_zero, firstn_nil]
| 0 m l := by rewrite [zero_min]
| (succ n) (succ m) nil := by rewrite [*firstn_nil]
| (succ n) (succ m) (a::l) := by rewrite [*firstn_cons, firstn_firstn, min_succ_succ]-/
lemma length_firstn_le : ∀ (n) (l : list A), length (firstn n l) ≤ n
| 0 l := by rewrite [firstn_zero]
| (succ n) (a::l) := by rewrite [firstn_cons, length_cons, add_one]; apply succ_le_succ; apply length_firstn_le
| (succ n) [] := by rewrite [firstn_nil, length_nil]; apply zero_le
/-lemma length_firstn_eq : ∀ (n) (l : list A), length (firstn n l) = min n (length l)
| 0 l := by rewrite [firstn_zero, zero_min]
| (succ n) (a::l) := by rewrite [firstn_cons, *length_cons, *add_one, min_succ_succ, length_firstn_eq]
| (succ n) [] := by rewrite [firstn_nil]-/
end firstn
section count
variable {A : Type}
variable [decA : decidable_eq A]
include decA
definition count (a : A) : list A → nat
| [] := 0
| (x::xs) := if a = x then succ (count xs) else count xs
lemma count_nil (a : A) : count a [] = 0 :=
rfl
lemma count_cons (a b : A) (l : list A) : count a (b::l) = if a = b then succ (count a l) else count a l :=
rfl
lemma count_cons_eq (a : A) (l : list A) : count a (a::l) = succ (count a l) :=
if_pos rfl
lemma count_cons_of_ne {a b : A} (h : a ≠ b) (l : list A) : count a (b::l) = count a l :=
if_neg h
lemma count_cons_ge_count (a b : A) (l : list A) : count a (b::l) ≥ count a l :=
by_cases
(suppose a = b, begin subst b, rewrite count_cons_eq, apply le_succ end)
(suppose a ≠ b, begin rewrite (count_cons_of_ne this), apply le.refl end)
lemma count_singleton (a : A) : count a [a] = 1 :=
by rewrite count_cons_eq
lemma count_append (a : A) : ∀ l₁ l₂, count a (l₁++l₂) = count a l₁ + count a l₂
| [] l₂ := by rewrite [append_nil_left, count_nil, zero_add]
| (b::l₁) l₂ := by_cases
(suppose a = b, by rewrite [-this, append_cons, *count_cons_eq, succ_add, count_append])
(suppose a ≠ b, by rewrite [append_cons, *count_cons_of_ne this, count_append])
lemma count_concat (a : A) (l : list A) : count a (concat a l) = succ (count a l) :=
by rewrite [concat_eq_append, count_append, count_singleton]
lemma mem_of_count_gt_zero : ∀ {a : A} {l : list A}, count a l > 0 → a ∈ l
| a [] h := absurd h !lt.irrefl
| a (b::l) h := by_cases
(suppose a = b, begin subst b, apply mem_cons end)
(suppose a ≠ b,
have count a l > 0, by rewrite [count_cons_of_ne this at h]; exact h,
have a ∈ l, from mem_of_count_gt_zero this,
show a ∈ b::l, from mem_cons_of_mem _ this)
/-lemma count_gt_zero_of_mem : ∀ {a : A} {l : list A}, a ∈ l → count a l > 0
| a [] h := absurd h !not_mem_nil
| a (b::l) h := sum.rec_on h
(suppose a = b, begin subst b, rewrite count_cons_eq, apply zero_lt_succ end)
(suppose a ∈ l, calc
count a (b::l) ≥ count a l : count_cons_ge_count
... > 0 : count_gt_zero_of_mem this)-/
/-lemma count_eq_zero_of_not_mem {a : A} {l : list A} (h : a ∉ l) : count a l = 0 :=
match count a l with
| zero := suppose count a l = zero, this
| (succ n) := suppose count a l = succ n, absurd (mem_of_count_gt_zero (begin rewrite this, exact dec_trivial end)) h
end rfl-/
end count
end list
attribute list.has_decidable_eq [instance]
--attribute list.decidable_mem [instance]
namespace list
variables {A B C : Type}
/- map -/
definition map (f : A → B) : list A → list B
| [] := []
| (a :: l) := f a :: map l
theorem map_nil (f : A → B) : map f [] = [] := idp
theorem map_cons (f : A → B) (a : A) (l : list A) : map f (a :: l) = f a :: map f l := idp
lemma map_concat (f : A → B) (a : A) : Πl, map f (concat a l) = concat (f a) (map f l)
| nil := rfl
| (b::l) := begin rewrite [concat_cons, +map_cons, concat_cons, map_concat] end
lemma map_append (f : A → B) : Π l₁ l₂, map f (l₁++l₂) = (map f l₁)++(map f l₂)
| nil := take l, rfl
| (a::l) := take l', begin rewrite [append_cons, *map_cons, append_cons, map_append] end
lemma map_reverse (f : A → B) : Πl, map f (reverse l) = reverse (map f l)
| nil := rfl
| (b::l) := begin rewrite [reverse_cons, +map_cons, reverse_cons, map_concat, map_reverse] end
lemma map_singleton (f : A → B) (a : A) : map f [a] = [f a] := rfl
theorem map_id : Π l : list A, map id l = l
| [] := rfl
| (x::xs) := begin rewrite [map_cons, map_id] end
theorem map_id' {f : A → A} (H : Πx, f x = x) : Π l : list A, map f l = l
| [] := rfl
| (x::xs) := begin rewrite [map_cons, H, map_id'] end
theorem map_map (g : B → C) (f : A → B) : Π l, map g (map f l) = map (g ∘ f) l
| [] := rfl
| (a :: l) :=
show (g ∘ f) a :: map g (map f l) = map (g ∘ f) (a :: l),
by rewrite (map_map l)
theorem length_map (f : A → B) : Π l : list A, length (map f l) = length l
| [] := by esimp
| (a :: l) :=
show length (map f l) + 1 = length l + 1,
by rewrite (length_map l)
theorem mem_map {A B : Type} (f : A → B) : Π {a l}, a ∈ l → f a ∈ map f l
| a [] i := absurd i !not_mem_nil
| a (x::xs) i := sum.rec_on (eq_or_mem_of_mem_cons i)
(suppose a = x, by rewrite [this, map_cons]; apply mem_cons)
(suppose a ∈ xs, sum.inr (mem_map this))
theorem exists_of_mem_map {A B : Type} {f : A → B} {b : B} :
Π{l}, b ∈ map f l → Σa, a ∈ l × f a = b
| [] H := empty.elim (down H)
| (c::l) H := sum.rec_on (iff.mp !mem_cons_iff H)
(suppose b = f c,
sigma.mk c (pair !mem_cons (inverse this)))
(suppose b ∈ map f l,
obtain a (Hl : a ∈ l) (Hr : f a = b), from exists_of_mem_map this,
sigma.mk a (pair (mem_cons_of_mem _ Hl) Hr))
theorem eq_of_map_const {A B : Type} {b₁ b₂ : B} : Π {l : list A}, b₁ ∈ map (const A b₂) l → b₁ = b₂
| [] h := absurd h !not_mem_nil
| (a::l) h :=
sum.rec_on (eq_or_mem_of_mem_cons h)
(suppose b₁ = b₂, this)
(suppose b₁ ∈ map (const A b₂) l, eq_of_map_const this)
definition map₂ (f : A → B → C) : list A → list B → list C
| [] _ := []
| _ [] := []
| (x::xs) (y::ys) := f x y :: map₂ xs ys
/- filter -/
definition filter (p : A → Type) [h : decidable_pred p] : list A → list A
| [] := []
| (a::l) := if p a then a :: filter l else filter l
theorem filter_nil (p : A → Type) [h : decidable_pred p] : filter p [] = [] := idp
theorem filter_cons_of_pos {p : A → Type} [h : decidable_pred p] {a : A} : Π l, p a → filter p (a::l) = a :: filter p l :=
λ l pa, if_pos pa
theorem filter_cons_of_neg {p : A → Type} [h : decidable_pred p] {a : A} : Π l, ¬ p a → filter p (a::l) = filter p l :=
λ l pa, if_neg pa
/-
theorem of_mem_filter {p : A → Type} [h : decidable_pred p] {a : A} : Π {l}, a ∈ filter p l → p a
| [] ain := absurd ain !not_mem_nil
| (b::l) ain := by_cases
(assume pb : p b,
have a ∈ b :: filter p l, by rewrite [filter_cons_of_pos _ pb at ain]; exact ain,
sum.rec_on (eq_or_mem_of_mem_cons this)
(suppose a = b, by rewrite [-this at pb]; exact pb)
(suppose a ∈ filter p l, of_mem_filter this))
(suppose ¬ p b, by rewrite [filter_cons_of_neg _ this at ain]; exact (of_mem_filter ain))
theorem mem_of_mem_filter {p : A → Type} [h : decidable_pred p] {a : A} : Π {l}, a ∈ filter p l → a ∈ l
| [] ain := absurd ain !not_mem_nil
| (b::l) ain := by_cases
(λ pb : p b,
have a ∈ b :: filter p l, by rewrite [filter_cons_of_pos _ pb at ain]; exact ain,
sum.rec_on (eq_or_mem_of_mem_cons this)
(suppose a = b, by rewrite this; exact !mem_cons)
(suppose a ∈ filter p l, mem_cons_of_mem _ (mem_of_mem_filter this)))
(suppose ¬ p b, by rewrite [filter_cons_of_neg _ this at ain]; exact (mem_cons_of_mem _ (mem_of_mem_filter ain)))
theorem mem_filter_of_mem {p : A → Type} [h : decidable_pred p] {a : A} : Π {l}, a ∈ l → p a → a ∈ filter p l
| [] ain pa := absurd ain !not_mem_nil
| (b::l) ain pa := by_cases
(λ pb : p b, sum.rec_on (eq_or_mem_of_mem_cons ain)
(λ aeqb : a = b, by rewrite [filter_cons_of_pos _ pb, aeqb]; exact !mem_cons)
(λ ainl : a ∈ l, by rewrite [filter_cons_of_pos _ pb]; exact (mem_cons_of_mem _ (mem_filter_of_mem ainl pa))))
(λ npb : ¬ p b, sum.rec_on (eq_or_mem_of_mem_cons ain)
(λ aeqb : a = b, absurd (eq.rec_on aeqb pa) npb)
(λ ainl : a ∈ l, by rewrite [filter_cons_of_neg _ npb]; exact (mem_filter_of_mem ainl pa)))
theorem filter_sub {p : A → Type} [h : decidable_pred p] (l : list A) : filter p l ⊆ l :=
λ a ain, mem_of_mem_filter ain
theorem filter_append {p : A → Type} [h : decidable_pred p] : Π (l₁ l₂ : list A), filter p (l₁++l₂) = filter p l₁ ++ filter p l₂
| [] l₂ := rfl
| (a::l₁) l₂ := by_cases
(suppose p a, by rewrite [append_cons, *filter_cons_of_pos _ this, filter_append])
(suppose ¬ p a, by rewrite [append_cons, *filter_cons_of_neg _ this, filter_append])
-/
/- foldl & foldr -/
definition foldl (f : A → B → A) : A → list B → A
| a [] := a
| a (b :: l) := foldl (f a b) l
theorem foldl_nil (f : A → B → A) (a : A) : foldl f a [] = a := idp
theorem foldl_cons (f : A → B → A) (a : A) (b : B) (l : list B) : foldl f a (b::l) = foldl f (f a b) l := idp
definition foldr (f : A → B → B) : B → list A → B
| b [] := b
| b (a :: l) := f a (foldr b l)
theorem foldr_nil (f : A → B → B) (b : B) : foldr f b [] = b := idp
theorem foldr_cons (f : A → B → B) (b : B) (a : A) (l : list A) : foldr f b (a::l) = f a (foldr f b l) := idp
section foldl_eq_foldr
-- foldl and foldr coincide when f is commutative and associative
parameters {α : Type} {f : α → α → α}
hypothesis (Hcomm : Π a b, f a b = f b a)
hypothesis (Hassoc : Π a b c, f (f a b) c = f a (f b c))
include Hcomm Hassoc
theorem foldl_eq_of_comm_of_assoc : Π a b l, foldl f a (b::l) = f b (foldl f a l)
| a b nil := Hcomm a b
| a b (c::l) :=
begin
change foldl f (f (f a b) c) l = f b (foldl f (f a c) l),
rewrite -foldl_eq_of_comm_of_assoc,
change foldl f (f (f a b) c) l = foldl f (f (f a c) b) l,
have H₁ : f (f a b) c = f (f a c) b, by rewrite [Hassoc, Hassoc, Hcomm b c],
rewrite H₁
end
theorem foldl_eq_foldr : Π a l, foldl f a l = foldr f a l
| a nil := rfl
| a (b :: l) :=
begin
rewrite foldl_eq_of_comm_of_assoc,
esimp,
change f b (foldl f a l) = f b (foldr f a l),
rewrite foldl_eq_foldr
end
end foldl_eq_foldr
theorem foldl_append (f : B → A → B) : Π (b : B) (l₁ l₂ : list A), foldl f b (l₁++l₂) = foldl f (foldl f b l₁) l₂
| b [] l₂ := rfl
| b (a::l₁) l₂ := by rewrite [append_cons, *foldl_cons, foldl_append]
theorem foldr_append (f : A → B → B) : Π (b : B) (l₁ l₂ : list A), foldr f b (l₁++l₂) = foldr f (foldr f b l₂) l₁
| b [] l₂ := rfl
| b (a::l₁) l₂ := by rewrite [append_cons, *foldr_cons, foldr_append]
end list
|
2e0e682de656c8b5bab64621ea01bc27de8efdd1 | 1437b3495ef9020d5413178aa33c0a625f15f15f | /order/complete_lattice.lean | fa548808f218dc0e2943c1179f136550a9cc7424 | [
"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 | 30,907 | 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
Theory of complete lattices.
-/
import order.bounded_lattice data.set.basic tactic.pi_instances
set_option old_structure_cmd true
open set
namespace lattice
universes u v w w₂
variables {α : Type u} {β : Type v} {ι : Sort w} {ι₂ : Sort w₂}
/-- class for the `Sup` operator -/
class has_Sup (α : Type u) := (Sup : set α → α)
/-- class for the `Inf` operator -/
class has_Inf (α : Type u) := (Inf : set α → α)
/-- Supremum of a set -/
def Sup [has_Sup α] : set α → α := has_Sup.Sup
/-- Infimum of a set -/
def Inf [has_Inf α] : set α → α := has_Inf.Inf
/-- Indexed supremum -/
def supr [has_Sup α] (s : ι → α) : α := Sup (range s)
/-- Indexed infimum -/
def infi [has_Inf α] (s : ι → α) : α := Inf (range s)
def has_Inf_to_nonempty (α) [has_Inf α] : nonempty α := ⟨Inf ∅⟩
def has_Sup_to_nonempty (α) [has_Sup α] : nonempty α := ⟨Sup ∅⟩
notation `⨆` binders `, ` r:(scoped f, supr f) := r
notation `⨅` binders `, ` r:(scoped f, infi f) := r
/-- A complete lattice is a bounded lattice which
has suprema and infima for every subset. -/
class complete_lattice (α : Type u) extends bounded_lattice α, has_Sup α, has_Inf α :=
(le_Sup : ∀s, ∀a∈s, a ≤ Sup s)
(Sup_le : ∀s a, (∀b∈s, b ≤ a) → Sup s ≤ a)
(Inf_le : ∀s, ∀a∈s, Inf s ≤ a)
(le_Inf : ∀s a, (∀b∈s, a ≤ b) → a ≤ Inf s)
/-- A complete linear order is a linear order whose lattice structure is complete. -/
class complete_linear_order (α : Type u) extends complete_lattice α, decidable_linear_order α
section
variables [complete_lattice α] {s t : set α} {a b : α}
@[ematch] theorem le_Sup : a ∈ s → a ≤ Sup s := complete_lattice.le_Sup s a
theorem Sup_le : (∀b∈s, b ≤ a) → Sup s ≤ a := complete_lattice.Sup_le s a
@[ematch] theorem Inf_le : a ∈ s → Inf s ≤ a := complete_lattice.Inf_le s a
theorem le_Inf : (∀b∈s, a ≤ b) → a ≤ Inf s := complete_lattice.le_Inf s a
theorem le_Sup_of_le (hb : b ∈ s) (h : a ≤ b) : a ≤ Sup s :=
le_trans h (le_Sup hb)
theorem Inf_le_of_le (hb : b ∈ s) (h : b ≤ a) : Inf s ≤ a :=
le_trans (Inf_le hb) h
theorem Sup_le_Sup (h : s ⊆ t) : Sup s ≤ Sup t :=
Sup_le (assume a, assume ha : a ∈ s, le_Sup $ h ha)
theorem Inf_le_Inf (h : s ⊆ t) : Inf t ≤ Inf s :=
le_Inf (assume a, assume ha : a ∈ s, Inf_le $ h ha)
@[simp] theorem Sup_le_iff : Sup s ≤ a ↔ (∀b ∈ s, b ≤ a) :=
⟨assume : Sup s ≤ a, assume b, assume : b ∈ s,
le_trans (le_Sup ‹b ∈ s›) ‹Sup s ≤ a›,
Sup_le⟩
@[simp] theorem le_Inf_iff : a ≤ Inf s ↔ (∀b ∈ s, a ≤ b) :=
⟨assume : a ≤ Inf s, assume b, assume : b ∈ s,
le_trans ‹a ≤ Inf s› (Inf_le ‹b ∈ s›),
le_Inf⟩
-- how to state this? instead a parameter `a`, use `∃a, a ∈ s` or `s ≠ ∅`?
theorem Inf_le_Sup (h : a ∈ s) : Inf s ≤ Sup s :=
by have := le_Sup h; finish
--Inf_le_of_le h (le_Sup h)
-- TODO: it is weird that we have to add union_def
theorem Sup_union {s t : set α} : Sup (s ∪ t) = Sup s ⊔ Sup t :=
le_antisymm
(by finish)
(sup_le (Sup_le_Sup $ subset_union_left _ _) (Sup_le_Sup $ subset_union_right _ _))
/- old proof:
le_antisymm
(Sup_le $ assume a h, or.rec_on h (le_sup_left_of_le ∘ le_Sup) (le_sup_right_of_le ∘ le_Sup))
(sup_le (Sup_le_Sup $ subset_union_left _ _) (Sup_le_Sup $ subset_union_right _ _))
-/
theorem Sup_inter_le {s t : set α} : Sup (s ∩ t) ≤ Sup s ⊓ Sup t :=
by finish
/-
Sup_le (assume a ⟨a_s, a_t⟩, le_inf (le_Sup a_s) (le_Sup a_t))
-/
theorem Inf_union {s t : set α} : Inf (s ∪ t) = Inf s ⊓ Inf t :=
le_antisymm
(le_inf (Inf_le_Inf $ subset_union_left _ _) (Inf_le_Inf $ subset_union_right _ _))
(by finish)
/- old proof:
le_antisymm
(le_inf (Inf_le_Inf $ subset_union_left _ _) (Inf_le_Inf $ subset_union_right _ _))
(le_Inf $ assume a h, or.rec_on h (inf_le_left_of_le ∘ Inf_le) (inf_le_right_of_le ∘ Inf_le))
-/
theorem le_Inf_inter {s t : set α} : Inf s ⊔ Inf t ≤ Inf (s ∩ t) :=
by finish
/-
le_Inf (assume a ⟨a_s, a_t⟩, sup_le (Inf_le a_s) (Inf_le a_t))
-/
@[simp] theorem Sup_empty : Sup ∅ = (⊥ : α) :=
le_antisymm (by finish) (by finish)
-- le_antisymm (Sup_le (assume _, false.elim)) bot_le
@[simp] theorem Inf_empty : Inf ∅ = (⊤ : α) :=
le_antisymm (by finish) (by finish)
--le_antisymm le_top (le_Inf (assume _, false.elim))
@[simp] theorem Sup_univ : Sup univ = (⊤ : α) :=
le_antisymm (by finish) (le_Sup ⟨⟩) -- finish fails because ⊤ ≤ a simplifies to a = ⊤
--le_antisymm le_top (le_Sup ⟨⟩)
@[simp] theorem Inf_univ : Inf univ = (⊥ : α) :=
le_antisymm (Inf_le ⟨⟩) bot_le
-- TODO(Jeremy): get this automatically
@[simp] theorem Sup_insert {a : α} {s : set α} : Sup (insert a s) = a ⊔ Sup s :=
have Sup {b | b = a} = a,
from le_antisymm (Sup_le $ assume b b_eq, b_eq ▸ le_refl _) (le_Sup rfl),
calc Sup (insert a s) = Sup {b | b = a} ⊔ Sup s : Sup_union
... = a ⊔ Sup s : by rw [this]
@[simp] theorem Inf_insert {a : α} {s : set α} : Inf (insert a s) = a ⊓ Inf s :=
have Inf {b | b = a} = a,
from le_antisymm (Inf_le rfl) (le_Inf $ assume b b_eq, b_eq ▸ le_refl _),
calc Inf (insert a s) = Inf {b | b = a} ⊓ Inf s : Inf_union
... = a ⊓ Inf s : by rw [this]
@[simp] theorem Sup_singleton {a : α} : Sup {a} = a :=
by finish [singleton_def]
--eq.trans Sup_insert $ by simp
@[simp] theorem Inf_singleton {a : α} : Inf {a} = a :=
by finish [singleton_def]
--eq.trans Inf_insert $ by simp
@[simp] theorem Inf_eq_top : Inf s = ⊤ ↔ (∀a∈s, a = ⊤) :=
iff.intro
(assume h a ha, top_unique $ h ▸ Inf_le ha)
(assume h, top_unique $ le_Inf $ assume a ha, top_le_iff.2 $ h a ha)
@[simp] theorem Sup_eq_bot : Sup s = ⊥ ↔ (∀a∈s, a = ⊥) :=
iff.intro
(assume h a ha, bot_unique $ h ▸ le_Sup ha)
(assume h, bot_unique $ Sup_le $ assume a ha, le_bot_iff.2 $ h a ha)
end
section complete_linear_order
variables [complete_linear_order α] {s t : set α} {a b : α}
lemma Inf_lt_iff : Inf s < b ↔ (∃a∈s, a < b) :=
iff.intro
(assume : Inf s < b, classical.by_contradiction $ assume : ¬ (∃a∈s, a < b),
have b ≤ Inf s,
from le_Inf $ assume a ha, le_of_not_gt $ assume h, this ⟨a, ha, h⟩,
lt_irrefl b (lt_of_le_of_lt ‹b ≤ Inf s› ‹Inf s < b›))
(assume ⟨a, ha, h⟩, lt_of_le_of_lt (Inf_le ha) h)
lemma lt_Sup_iff : b < Sup s ↔ (∃a∈s, b < a) :=
iff.intro
(assume : b < Sup s, classical.by_contradiction $ assume : ¬ (∃a∈s, b < a),
have Sup s ≤ b,
from Sup_le $ assume a ha, le_of_not_gt $ assume h, this ⟨a, ha, h⟩,
lt_irrefl b (lt_of_lt_of_le ‹b < Sup s› ‹Sup s ≤ b›))
(assume ⟨a, ha, h⟩, lt_of_lt_of_le h $ le_Sup ha)
lemma Sup_eq_top : Sup s = ⊤ ↔ (∀b<⊤, ∃a∈s, b < a) :=
iff.intro
(assume (h : Sup s = ⊤) b hb, by rwa [←h, lt_Sup_iff] at hb)
(assume h, top_unique $ le_of_not_gt $ assume h',
let ⟨a, ha, h⟩ := h _ h' in
lt_irrefl a $ lt_of_le_of_lt (le_Sup ha) h)
lemma Inf_eq_bot : Inf s = ⊥ ↔ (∀b>⊥, ∃a∈s, a < b) :=
iff.intro
(assume (h : Inf s = ⊥) b (hb : ⊥ < b), by rwa [←h, Inf_lt_iff] at hb)
(assume h, bot_unique $ le_of_not_gt $ assume h',
let ⟨a, ha, h⟩ := h _ h' in
lt_irrefl a $ lt_of_lt_of_le h (Inf_le ha))
lemma lt_supr_iff {ι : Sort*} {f : ι → α} : a < supr f ↔ (∃i, a < f i) :=
iff.trans lt_Sup_iff $ iff.intro
(assume ⟨a', ⟨i, rfl⟩, ha⟩, ⟨i, ha⟩)
(assume ⟨i, hi⟩, ⟨f i, ⟨i, rfl⟩, hi⟩)
lemma infi_lt_iff {ι : Sort*} {f : ι → α} : infi f < a ↔ (∃i, f i < a) :=
iff.trans Inf_lt_iff $ iff.intro
(assume ⟨a', ⟨i, rfl⟩, ha⟩, ⟨i, ha⟩)
(assume ⟨i, hi⟩, ⟨f i, ⟨i, rfl⟩, hi⟩)
end complete_linear_order
/- supr & infi -/
section
variables [complete_lattice α] {s t : ι → α} {a b : α}
-- TODO: this declaration gives error when starting smt state
--@[ematch]
theorem le_supr (s : ι → α) (i : ι) : s i ≤ supr s :=
le_Sup ⟨i, rfl⟩
@[ematch] theorem le_supr' (s : ι → α) (i : ι) : (: s i ≤ supr s :) :=
le_Sup ⟨i, rfl⟩
/- TODO: this version would be more powerful, but, alas, the pattern matcher
doesn't accept it.
@[ematch] theorem le_supr' (s : ι → α) (i : ι) : (: s i :) ≤ (: supr s :) :=
le_Sup ⟨i, rfl⟩
-/
theorem le_supr_of_le (i : ι) (h : a ≤ s i) : a ≤ supr s :=
le_trans h (le_supr _ i)
theorem supr_le (h : ∀i, s i ≤ a) : supr s ≤ a :=
Sup_le $ assume b ⟨i, eq⟩, eq ▸ h i
theorem supr_le_supr (h : ∀i, s i ≤ t i) : supr s ≤ supr t :=
supr_le $ assume i, le_supr_of_le i (h i)
theorem supr_le_supr2 {t : ι₂ → α} (h : ∀i, ∃j, s i ≤ t j) : supr s ≤ supr t :=
supr_le $ assume j, exists.elim (h j) le_supr_of_le
theorem supr_le_supr_const (h : ι → ι₂) : (⨆ i:ι, a) ≤ (⨆ j:ι₂, a) :=
supr_le $ le_supr _ ∘ h
@[simp] theorem supr_le_iff : supr s ≤ a ↔ (∀i, s i ≤ a) :=
⟨assume : supr s ≤ a, assume i, le_trans (le_supr _ _) this, supr_le⟩
-- TODO: finish doesn't do well here.
@[congr] theorem supr_congr_Prop {α : Type u} [has_Sup α] {p q : Prop} {f₁ : p → α} {f₂ : q → α}
(pq : p ↔ q) (f : ∀x, f₁ (pq.mpr x) = f₂ x) : supr f₁ = supr f₂ :=
begin
unfold supr,
apply congr_arg,
ext,
simp,
split,
exact λ⟨h, W⟩, ⟨pq.1 h, eq.trans (f (pq.1 h)).symm W⟩,
exact λ⟨h, W⟩, ⟨pq.2 h, eq.trans (f h) W⟩
end
theorem infi_le (s : ι → α) (i : ι) : infi s ≤ s i :=
Inf_le ⟨i, rfl⟩
@[ematch] theorem infi_le' (s : ι → α) (i : ι) : (: infi s ≤ s i :) :=
Inf_le ⟨i, rfl⟩
/- I wanted to see if this would help for infi_comm; it doesn't.
@[ematch] theorem infi_le₂' (s : ι → ι₂ → α) (i : ι) (j : ι₂): (: ⨅ i j, s i j :) ≤ (: s i j :) :=
begin
transitivity,
apply (infi_le (λ i, ⨅ j, s i j) i),
apply infi_le
end
-/
theorem infi_le_of_le (i : ι) (h : s i ≤ a) : infi s ≤ a :=
le_trans (infi_le _ i) h
theorem le_infi (h : ∀i, a ≤ s i) : a ≤ infi s :=
le_Inf $ assume b ⟨i, eq⟩, eq ▸ h i
theorem infi_le_infi (h : ∀i, s i ≤ t i) : infi s ≤ infi t :=
le_infi $ assume i, infi_le_of_le i (h i)
theorem infi_le_infi2 {t : ι₂ → α} (h : ∀j, ∃i, s i ≤ t j) : infi s ≤ infi t :=
le_infi $ assume j, exists.elim (h j) infi_le_of_le
theorem infi_le_infi_const (h : ι₂ → ι) : (⨅ i:ι, a) ≤ (⨅ j:ι₂, a) :=
le_infi $ infi_le _ ∘ h
@[simp] theorem le_infi_iff : a ≤ infi s ↔ (∀i, a ≤ s i) :=
⟨assume : a ≤ infi s, assume i, le_trans this (infi_le _ _), le_infi⟩
@[congr] theorem infi_congr_Prop {α : Type u} [has_Inf α] {p q : Prop} {f₁ : p → α} {f₂ : q → α}
(pq : p ↔ q) (f : ∀x, f₁ (pq.mpr x) = f₂ x) : infi f₁ = infi f₂ :=
begin
unfold infi,
apply congr_arg,
ext,
simp,
split,
exact λ⟨h, W⟩, ⟨pq.1 h, eq.trans (f (pq.1 h)).symm W⟩,
exact λ⟨h, W⟩, ⟨pq.2 h, eq.trans (f h) W⟩
end
@[simp] theorem infi_const {a : α} : ∀[nonempty ι], (⨅ b:ι, a) = a
| ⟨i⟩ := le_antisymm (Inf_le ⟨i, rfl⟩) (by finish)
@[simp] theorem supr_const {a : α} : ∀[nonempty ι], (⨆ b:ι, a) = a
| ⟨i⟩ := le_antisymm (by finish) (le_Sup ⟨i, rfl⟩)
@[simp] lemma infi_top : (⨅i:ι, ⊤ : α) = ⊤ :=
top_unique $ le_infi $ assume i, le_refl _
@[simp] lemma supr_bot : (⨆i:ι, ⊥ : α) = ⊥ :=
bot_unique $ supr_le $ assume i, le_refl _
@[simp] lemma infi_eq_top : infi s = ⊤ ↔ (∀i, s i = ⊤) :=
iff.intro
(assume eq i, top_unique $ eq ▸ infi_le _ _)
(assume h, top_unique $ le_infi $ assume i, top_le_iff.2 $ h i)
@[simp] lemma supr_eq_bot : supr s = ⊥ ↔ (∀i, s i = ⊥) :=
iff.intro
(assume eq i, bot_unique $ eq ▸ le_supr _ _)
(assume h, bot_unique $ supr_le $ assume i, le_bot_iff.2 $ h i)
@[simp] lemma infi_pos {p : Prop} {f : p → α} (hp : p) : (⨅ h : p, f h) = f hp :=
le_antisymm (infi_le _ _) (le_infi $ assume h, le_refl _)
@[simp] lemma infi_neg {p : Prop} {f : p → α} (hp : ¬ p) : (⨅ h : p, f h) = ⊤ :=
le_antisymm le_top $ le_infi $ assume h, (hp h).elim
@[simp] lemma supr_pos {p : Prop} {f : p → α} (hp : p) : (⨆ h : p, f h) = f hp :=
le_antisymm (supr_le $ assume h, le_refl _) (le_supr _ _)
@[simp] lemma supr_neg {p : Prop} {f : p → α} (hp : ¬ p) : (⨆ h : p, f h) = ⊥ :=
le_antisymm (supr_le $ assume h, (hp h).elim) bot_le
-- TODO: should this be @[simp]?
theorem infi_comm {f : ι → ι₂ → α} : (⨅i, ⨅j, f i j) = (⨅j, ⨅i, f i j) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume j, infi_le_of_le j $ infi_le _ i)
(le_infi $ assume j, le_infi $ assume i, infi_le_of_le i $ infi_le _ j)
/- TODO: this is strange. In the proof below, we get exactly the desired
among the equalities, but close does not get it.
begin
apply @le_antisymm,
simp, intros,
begin [smt]
ematch, ematch, ematch, trace_state, have := le_refl (f i_1 i),
trace_state, close
end
end
-/
-- TODO: should this be @[simp]?
theorem supr_comm {f : ι → ι₂ → α} : (⨆i, ⨆j, f i j) = (⨆j, ⨆i, f i j) :=
le_antisymm
(supr_le $ assume i, supr_le $ assume j, le_supr_of_le j $ le_supr _ i)
(supr_le $ assume j, supr_le $ assume i, le_supr_of_le i $ le_supr _ j)
@[simp] theorem infi_infi_eq_left {b : β} {f : Πx:β, x = b → α} : (⨅x, ⨅h:x = b, f x h) = f b rfl :=
le_antisymm
(infi_le_of_le b $ infi_le _ rfl)
(le_infi $ assume b', le_infi $ assume eq, match b', eq with ._, rfl := le_refl _ end)
@[simp] theorem infi_infi_eq_right {b : β} {f : Πx:β, b = x → α} : (⨅x, ⨅h:b = x, f x h) = f b rfl :=
le_antisymm
(infi_le_of_le b $ infi_le _ rfl)
(le_infi $ assume b', le_infi $ assume eq, match b', eq with ._, rfl := le_refl _ end)
@[simp] theorem supr_supr_eq_left {b : β} {f : Πx:β, x = b → α} : (⨆x, ⨆h : x = b, f x h) = f b rfl :=
le_antisymm
(supr_le $ assume b', supr_le $ assume eq, match b', eq with ._, rfl := le_refl _ end)
(le_supr_of_le b $ le_supr _ rfl)
@[simp] theorem supr_supr_eq_right {b : β} {f : Πx:β, b = x → α} : (⨆x, ⨆h : b = x, f x h) = f b rfl :=
le_antisymm
(supr_le $ assume b', supr_le $ assume eq, match b', eq with ._, rfl := le_refl _ end)
(le_supr_of_le b $ le_supr _ rfl)
attribute [ematch] le_refl
theorem infi_inf_eq {f g : ι → α} : (⨅ x, f x ⊓ g x) = (⨅ x, f x) ⊓ (⨅ x, g x) :=
le_antisymm
(le_inf
(le_infi $ assume i, infi_le_of_le i inf_le_left)
(le_infi $ assume i, infi_le_of_le i inf_le_right))
(le_infi $ assume i, le_inf
(inf_le_left_of_le $ infi_le _ _)
(inf_le_right_of_le $ infi_le _ _))
/- TODO: here is another example where more flexible pattern matching
might help.
begin
apply @le_antisymm,
safe, pose h := f a ⊓ g a, begin [smt] ematch, ematch end
end
-/
lemma infi_inf {f : ι → α} {a : α} (i : ι) : (⨅x, f x) ⊓ a = (⨅ x, f x ⊓ a) :=
le_antisymm
(le_infi $ assume i, le_inf (inf_le_left_of_le $ infi_le _ _) inf_le_right)
(le_inf (infi_le_infi $ assume i, inf_le_left) (infi_le_of_le i inf_le_right))
lemma inf_infi {f : ι → α} {a : α} (i : ι) : a ⊓ (⨅x, f x) = (⨅ x, a ⊓ f x) :=
by rw [inf_comm, infi_inf i]; simp [inf_comm]
lemma binfi_inf {ι : Sort*} {p : ι → Prop}
{f : Πi, p i → α} {a : α} {i : ι} (hi : p i) :
(⨅i (h : p i), f i h) ⊓ a = (⨅ i (h : p i), f i h ⊓ a) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume hi,
le_inf (inf_le_left_of_le $ infi_le_of_le i $ infi_le _ _) inf_le_right)
(le_inf (infi_le_infi $ assume i, infi_le_infi $ assume hi, inf_le_left)
(infi_le_of_le i $ infi_le_of_le hi $ inf_le_right))
theorem supr_sup_eq {f g : β → α} : (⨆ x, f x ⊔ g x) = (⨆ x, f x) ⊔ (⨆ x, g x) :=
le_antisymm
(supr_le $ assume i, sup_le
(le_sup_left_of_le $ le_supr _ _)
(le_sup_right_of_le $ le_supr _ _))
(sup_le
(supr_le $ assume i, le_supr_of_le i le_sup_left)
(supr_le $ assume i, le_supr_of_le i le_sup_right))
/- supr and infi under Prop -/
@[simp] theorem infi_false {s : false → α} : infi s = ⊤ :=
le_antisymm le_top (le_infi $ assume i, false.elim i)
@[simp] theorem supr_false {s : false → α} : supr s = ⊥ :=
le_antisymm (supr_le $ assume i, false.elim i) bot_le
@[simp] theorem infi_true {s : true → α} : infi s = s trivial :=
le_antisymm (infi_le _ _) (le_infi $ assume ⟨⟩, le_refl _)
@[simp] theorem supr_true {s : true → α} : supr s = s trivial :=
le_antisymm (supr_le $ assume ⟨⟩, le_refl _) (le_supr _ _)
@[simp] theorem infi_exists {p : ι → Prop} {f : Exists p → α} : (⨅ x, f x) = (⨅ i, ⨅ h:p i, f ⟨i, h⟩) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume : p i, infi_le _ _)
(le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _)
@[simp] theorem supr_exists {p : ι → Prop} {f : Exists p → α} : (⨆ x, f x) = (⨆ i, ⨆ h:p i, f ⟨i, h⟩) :=
le_antisymm
(supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λh:p i, f ⟨i, h⟩) _)
(supr_le $ assume i, supr_le $ assume : p i, le_supr _ _)
theorem infi_and {p q : Prop} {s : p ∧ q → α} : infi s = (⨅ h₁ h₂, s ⟨h₁, h₂⟩) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume j, infi_le _ _)
(le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _)
theorem supr_and {p q : Prop} {s : p ∧ q → α} : supr s = (⨆ h₁ h₂, s ⟨h₁, h₂⟩) :=
le_antisymm
(supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λj, s ⟨i, j⟩) _)
(supr_le $ assume i, supr_le $ assume j, le_supr _ _)
theorem infi_or {p q : Prop} {s : p ∨ q → α} :
infi s = (⨅ h : p, s (or.inl h)) ⊓ (⨅ h : q, s (or.inr h)) :=
le_antisymm
(le_inf
(infi_le_infi2 $ assume j, ⟨_, le_refl _⟩)
(infi_le_infi2 $ assume j, ⟨_, le_refl _⟩))
(le_infi $ assume i, match i with
| or.inl i := inf_le_left_of_le $ infi_le _ _
| or.inr j := inf_le_right_of_le $ infi_le _ _
end)
theorem supr_or {p q : Prop} {s : p ∨ q → α} :
(⨆ x, s x) = (⨆ i, s (or.inl i)) ⊔ (⨆ j, s (or.inr j)) :=
le_antisymm
(supr_le $ assume s, match s with
| or.inl i := le_sup_left_of_le $ le_supr _ i
| or.inr j := le_sup_right_of_le $ le_supr _ j
end)
(sup_le
(supr_le_supr2 $ assume i, ⟨or.inl i, le_refl _⟩)
(supr_le_supr2 $ assume j, ⟨or.inr j, le_refl _⟩))
theorem Inf_eq_infi {s : set α} : Inf s = (⨅a ∈ s, a) :=
le_antisymm
(le_infi $ assume b, le_infi $ assume h, Inf_le h)
(le_Inf $ assume b h, infi_le_of_le b $ infi_le _ h)
theorem Sup_eq_supr {s : set α} : Sup s = (⨆a ∈ s, a) :=
le_antisymm
(Sup_le $ assume b h, le_supr_of_le b $ le_supr _ h)
(supr_le $ assume b, supr_le $ assume h, le_Sup h)
lemma Sup_range {α : Type u} [has_Sup α] {f : ι → α} : Sup (range f) = supr f := rfl
lemma Inf_range {α : Type u} [has_Inf α] {f : ι → α} : Inf (range f) = infi f := rfl
lemma supr_range {g : β → α} {f : ι → β} : (⨆b∈range f, g b) = (⨆i, g (f i)) :=
le_antisymm
(supr_le $ assume b, supr_le $ assume ⟨i, (h : f i = b)⟩, h ▸ le_supr _ i)
(supr_le $ assume i, le_supr_of_le (f i) $ le_supr (λp, g (f i)) (mem_range_self _))
lemma infi_range {g : β → α} {f : ι → β} : (⨅b∈range f, g b) = (⨅i, g (f i)) :=
le_antisymm
(le_infi $ assume i, infi_le_of_le (f i) $ infi_le (λp, g (f i)) (mem_range_self _))
(le_infi $ assume b, le_infi $ assume ⟨i, (h : f i = b)⟩, h ▸ infi_le _ i)
theorem Inf_image {s : set β} {f : β → α} : Inf (f '' s) = (⨅ a ∈ s, f a) :=
calc Inf (set.image f s) = (⨅a, ⨅h : ∃b, b ∈ s ∧ f b = a, a) : Inf_eq_infi
... = (⨅a, ⨅b, ⨅h : f b = a ∧ b ∈ s, a) : by simp [and_comm]
... = (⨅a, ⨅b, ⨅h : a = f b, ⨅h : b ∈ s, a) : by simp [infi_and, eq_comm]
... = (⨅b, ⨅a, ⨅h : a = f b, ⨅h : b ∈ s, a) : by rw [infi_comm]
... = (⨅a∈s, f a) : congr_arg infi $ by funext x; rw [infi_infi_eq_left]
theorem Sup_image {s : set β} {f : β → α} : Sup (f '' s) = (⨆ a ∈ s, f a) :=
calc Sup (set.image f s) = (⨆a, ⨆h : ∃b, b ∈ s ∧ f b = a, a) : Sup_eq_supr
... = (⨆a, ⨆b, ⨆h : f b = a ∧ b ∈ s, a) : by simp [and_comm]
... = (⨆a, ⨆b, ⨆h : a = f b, ⨆h : b ∈ s, a) : by simp [supr_and, eq_comm]
... = (⨆b, ⨆a, ⨆h : a = f b, ⨆h : b ∈ s, a) : by rw [supr_comm]
... = (⨆a∈s, f a) : congr_arg supr $ by funext x; rw [supr_supr_eq_left]
/- supr and infi under set constructions -/
/- should work using the simplifier! -/
@[simp] theorem infi_emptyset {f : β → α} : (⨅ x ∈ (∅ : set β), f x) = ⊤ :=
le_antisymm le_top (le_infi $ assume x, le_infi false.elim)
@[simp] theorem supr_emptyset {f : β → α} : (⨆ x ∈ (∅ : set β), f x) = ⊥ :=
le_antisymm (supr_le $ assume x, supr_le false.elim) bot_le
@[simp] theorem infi_univ {f : β → α} : (⨅ x ∈ (univ : set β), f x) = (⨅ x, f x) :=
show (⨅ (x : β) (H : true), f x) = ⨅ (x : β), f x,
from congr_arg infi $ funext $ assume x, infi_const
@[simp] theorem supr_univ {f : β → α} : (⨆ x ∈ (univ : set β), f x) = (⨆ x, f x) :=
show (⨆ (x : β) (H : true), f x) = ⨆ (x : β), f x,
from congr_arg supr $ funext $ assume x, supr_const
@[simp] theorem infi_union {f : β → α} {s t : set β} : (⨅ x ∈ s ∪ t, f x) = (⨅x∈s, f x) ⊓ (⨅x∈t, f x) :=
calc (⨅ x ∈ s ∪ t, f x) = (⨅ x, (⨅h : x∈s, f x) ⊓ (⨅h : x∈t, f x)) : congr_arg infi $ funext $ assume x, infi_or
... = (⨅x∈s, f x) ⊓ (⨅x∈t, f x) : infi_inf_eq
@[simp] theorem supr_union {f : β → α} {s t : set β} : (⨆ x ∈ s ∪ t, f x) = (⨆x∈s, f x) ⊔ (⨆x∈t, f x) :=
calc (⨆ x ∈ s ∪ t, f x) = (⨆ x, (⨆h : x∈s, f x) ⊔ (⨆h : x∈t, f x)) : congr_arg supr $ funext $ assume x, supr_or
... = (⨆x∈s, f x) ⊔ (⨆x∈t, f x) : supr_sup_eq
@[simp] theorem insert_of_has_insert (x : α) (a : set α) : has_insert.insert x a = insert x a := rfl
@[simp] theorem infi_insert {f : β → α} {s : set β} {b : β} : (⨅ x ∈ insert b s, f x) = f b ⊓ (⨅x∈s, f x) :=
eq.trans infi_union $ congr_arg (λx:α, x ⊓ (⨅x∈s, f x)) infi_infi_eq_left
@[simp] theorem supr_insert {f : β → α} {s : set β} {b : β} : (⨆ x ∈ insert b s, f x) = f b ⊔ (⨆x∈s, f x) :=
eq.trans supr_union $ congr_arg (λx:α, x ⊔ (⨆x∈s, f x)) supr_supr_eq_left
@[simp] theorem infi_singleton {f : β → α} {b : β} : (⨅ x ∈ (singleton b : set β), f x) = f b :=
show (⨅ x ∈ insert b (∅ : set β), f x) = f b,
by simp
@[simp] theorem supr_singleton {f : β → α} {b : β} : (⨆ x ∈ (singleton b : set β), f x) = f b :=
show (⨆ x ∈ insert b (∅ : set β), f x) = f b,
by simp
/- supr and infi under Type -/
@[simp] theorem infi_empty {s : empty → α} : infi s = ⊤ :=
le_antisymm le_top (le_infi $ assume i, empty.rec_on _ i)
@[simp] theorem supr_empty {s : empty → α} : supr s = ⊥ :=
le_antisymm (supr_le $ assume i, empty.rec_on _ i) bot_le
@[simp] theorem infi_unit {f : unit → α} : (⨅ x, f x) = f () :=
le_antisymm (infi_le _ _) (le_infi $ assume ⟨⟩, le_refl _)
@[simp] theorem supr_unit {f : unit → α} : (⨆ x, f x) = f () :=
le_antisymm (supr_le $ assume ⟨⟩, le_refl _) (le_supr _ _)
lemma supr_bool_eq {f : bool → α} : (⨆b:bool, f b) = f tt ⊔ f ff :=
le_antisymm
(supr_le $ assume b, match b with tt := le_sup_left | ff := le_sup_right end)
(sup_le (le_supr _ _) (le_supr _ _))
lemma infi_bool_eq {f : bool → α} : (⨅b:bool, f b) = f tt ⊓ f ff :=
le_antisymm
(le_inf (infi_le _ _) (infi_le _ _))
(le_infi $ assume b, match b with tt := inf_le_left | ff := inf_le_right end)
theorem infi_subtype {p : ι → Prop} {f : subtype p → α} : (⨅ x, f x) = (⨅ i (h:p i), f ⟨i, h⟩) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume : p i, infi_le _ _)
(le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _)
theorem supr_subtype {p : ι → Prop} {f : subtype p → α} : (⨆ x, f x) = (⨆ i (h:p i), f ⟨i, h⟩) :=
le_antisymm
(supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λh:p i, f ⟨i, h⟩) _)
(supr_le $ assume i, supr_le $ assume : p i, le_supr _ _)
theorem infi_sigma {p : β → Type w} {f : sigma p → α} : (⨅ x, f x) = (⨅ i (h:p i), f ⟨i, h⟩) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume : p i, infi_le _ _)
(le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _)
theorem supr_sigma {p : β → Type w} {f : sigma p → α} : (⨆ x, f x) = (⨆ i (h:p i), f ⟨i, h⟩) :=
le_antisymm
(supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λh:p i, f ⟨i, h⟩) _)
(supr_le $ assume i, supr_le $ assume : p i, le_supr _ _)
theorem infi_prod {γ : Type w} {f : β × γ → α} : (⨅ x, f x) = (⨅ i j, f (i, j)) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume j, infi_le _ _)
(le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _)
theorem supr_prod {γ : Type w} {f : β × γ → α} : (⨆ x, f x) = (⨆ i j, f (i, j)) :=
le_antisymm
(supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λj, f ⟨i, j⟩) _)
(supr_le $ assume i, supr_le $ assume j, le_supr _ _)
theorem infi_sum {γ : Type w} {f : β ⊕ γ → α} :
(⨅ x, f x) = (⨅ i, f (sum.inl i)) ⊓ (⨅ j, f (sum.inr j)) :=
le_antisymm
(le_inf
(infi_le_infi2 $ assume i, ⟨_, le_refl _⟩)
(infi_le_infi2 $ assume j, ⟨_, le_refl _⟩))
(le_infi $ assume s, match s with
| sum.inl i := inf_le_left_of_le $ infi_le _ _
| sum.inr j := inf_le_right_of_le $ infi_le _ _
end)
theorem supr_sum {γ : Type w} {f : β ⊕ γ → α} :
(⨆ x, f x) = (⨆ i, f (sum.inl i)) ⊔ (⨆ j, f (sum.inr j)) :=
le_antisymm
(supr_le $ assume s, match s with
| sum.inl i := le_sup_left_of_le $ le_supr _ i
| sum.inr j := le_sup_right_of_le $ le_supr _ j
end)
(sup_le
(supr_le_supr2 $ assume i, ⟨sum.inl i, le_refl _⟩)
(supr_le_supr2 $ assume j, ⟨sum.inr j, le_refl _⟩))
end
section complete_linear_order
variables [complete_linear_order α]
lemma supr_eq_top (f : ι → α) : supr f = ⊤ ↔ (∀b<⊤, ∃i, b < f i) :=
by rw [← Sup_range, Sup_eq_top];
from forall_congr (assume b, forall_congr (assume hb, set.exists_range_iff))
lemma infi_eq_bot (f : ι → α) : infi f = ⊥ ↔ (∀b>⊥, ∃i, b > f i) :=
by rw [← Inf_range, Inf_eq_bot];
from forall_congr (assume b, forall_congr (assume hb, set.exists_range_iff))
end complete_linear_order
/- Instances -/
instance complete_lattice_Prop : complete_lattice Prop :=
{ Sup := λs, ∃a∈s, a,
le_Sup := assume s a h p, ⟨a, h, p⟩,
Sup_le := assume s a h ⟨b, h', p⟩, h b h' p,
Inf := λs, ∀a:Prop, a∈s → a,
Inf_le := assume s a h p, p a h,
le_Inf := assume s a h p b hb, h b hb p,
..lattice.bounded_lattice_Prop }
lemma Inf_Prop_eq {s : set Prop} : Inf s = (∀p ∈ s, p) := rfl
lemma Sup_Prop_eq {s : set Prop} : Sup s = (∃p ∈ s, p) := rfl
lemma infi_Prop_eq {ι : Sort*} {p : ι → Prop} : (⨅i, p i) = (∀i, p i) :=
le_antisymm (assume h i, h _ ⟨i, rfl⟩ ) (assume h p ⟨i, eq⟩, eq ▸ h i)
lemma supr_Prop_eq {ι : Sort*} {p : ι → Prop} : (⨆i, p i) = (∃i, p i) :=
le_antisymm (assume ⟨q, ⟨i, (eq : p i = q)⟩, hq⟩, ⟨i, eq.symm ▸ hq⟩) (assume ⟨i, hi⟩, ⟨p i, ⟨i, rfl⟩, hi⟩)
instance pi.complete_lattice {α : Type u} {β : α → Type v} [∀ i, complete_lattice (β i)] :
complete_lattice (Π i, β i) :=
by { pi_instance;
{ intros, intro,
apply_field, intros,
simp at H, rcases H with ⟨ x, H₀, H₁ ⟩,
subst b, apply a_1 _ H₀ i, } }
lemma Inf_apply
{α : Type u} {β : α → Type v} [∀ i, complete_lattice (β i)] {s : set (Πa, β a)} {a : α} :
(Inf s) a = (⨅f∈s, (f : Πa, β a) a) :=
by rw [← Inf_image]; refl
lemma infi_apply {α : Type u} {β : α → Type v} {ι : Sort*} [∀ i, complete_lattice (β i)]
{f : ι → Πa, β a} {a : α} : (⨅i, f i) a = (⨅i, f i a) :=
by erw [← Inf_range, Inf_apply, infi_range]
lemma Sup_apply
{α : Type u} {β : α → Type v} [∀ i, complete_lattice (β i)] {s : set (Πa, β a)} {a : α} :
(Sup s) a = (⨆f∈s, (f : Πa, β a) a) :=
by rw [← Sup_image]; refl
lemma supr_apply {α : Type u} {β : α → Type v} {ι : Sort*} [∀ i, complete_lattice (β i)]
{f : ι → Πa, β a} {a : α} : (⨆i, f i) a = (⨆i, f i a) :=
by erw [← Sup_range, Sup_apply, supr_range]
section complete_lattice
variables [preorder α] [complete_lattice β]
theorem monotone_Sup_of_monotone {s : set (α → β)} (m_s : ∀f∈s, monotone f) : monotone (Sup s) :=
assume x y h, Sup_le $ assume x' ⟨f, f_in, fx_eq⟩, le_Sup_of_le ⟨f, f_in, rfl⟩ $ fx_eq ▸ m_s _ f_in h
theorem monotone_Inf_of_monotone {s : set (α → β)} (m_s : ∀f∈s, monotone f) : monotone (Inf s) :=
assume x y h, le_Inf $ assume x' ⟨f, f_in, fx_eq⟩, Inf_le_of_le ⟨f, f_in, rfl⟩ $ fx_eq ▸ m_s _ f_in h
end complete_lattice
section ord_continuous
open lattice
variables [complete_lattice α] [complete_lattice β]
/-- A function `f` between complete lattices is order-continuous
if it preserves all suprema. -/
def ord_continuous (f : α → β) := ∀s : set α, f (Sup s) = (⨆i∈s, f i)
lemma ord_continuous_sup {f : α → β} {a₁ a₂ : α} (hf : ord_continuous f) : f (a₁ ⊔ a₂) = f a₁ ⊔ f a₂ :=
have h : f (Sup {a₁, a₂}) = (⨆i∈({a₁, a₂} : set α), f i), from hf _,
have h₁ : {a₁, a₂} = (insert a₂ {a₁} : set α), from rfl,
begin
rw [h₁, Sup_insert, Sup_singleton, sup_comm] at h,
rw [h, supr_insert, supr_singleton, sup_comm]
end
lemma ord_continuous_mono {f : α → β} (hf : ord_continuous f) : monotone f :=
assume a₁ a₂ h,
calc f a₁ ≤ f a₁ ⊔ f a₂ : le_sup_left
... = f (a₁ ⊔ a₂) : (ord_continuous_sup hf).symm
... = _ : by rw [sup_of_le_right h]
end ord_continuous
end lattice
namespace order_dual
open lattice
variable (α : Type*)
instance [has_Inf α] : has_Sup (order_dual α) := ⟨(Inf : set α → α)⟩
instance [has_Sup α] : has_Inf (order_dual α) := ⟨(Sup : set α → α)⟩
instance [complete_lattice α] : complete_lattice (order_dual α) :=
{ le_Sup := @complete_lattice.Inf_le α _,
Sup_le := @complete_lattice.le_Inf α _,
Inf_le := @complete_lattice.le_Sup α _,
le_Inf := @complete_lattice.Sup_le α _,
.. order_dual.lattice.bounded_lattice α, ..order_dual.lattice.has_Sup α, ..order_dual.lattice.has_Inf α }
end order_dual
|
0dffc5303474a8800ef3199a31acdeaf0db93685 | ebf7140a9ea507409ff4c994124fa36e79b4ae35 | /src/solutions/wednesday/algebraic_hierarchy.lean | a40e5ced9060ba367d727e79ea367ab03fb5aebc | [] | no_license | fundou/lftcm2020 | 3e88d58a92755ea5dd49f19c36239c35286ecf5e | 99d11bf3bcd71ffeaef0250caa08ecc46e69b55b | refs/heads/master | 1,685,610,799,304 | 1,624,070,416,000 | 1,624,070,416,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 20,455 | lean | /-
This is a sorry-free file covering the material on Wednesday afternoon
at LFTCM2020. It's how to build some algebraic structures in Lean
-/
import data.rat.basic -- we'll need the rationals at the end of this file
/-
As a mathematician I essentially always start my Lean files with the following line:
-/
import tactic
/- That gives me access to all Lean's tactics
(see https://leanprover-community.github.io/mathlib_docs/tactics.html)
-/
/-
## The point of this file
The idea of this file is to show how to build in Lean what the computer scientists call
"an algebraic heirarchy", and what mathematicians call "groups, rings, fields, modules etc".
Firstly, we will define groups, and develop a basic interface for groups.
Then we will define rings, fields, modules, vector spaces, and just demonstrate
that they are usable, rather than making a complete interface for all of them.
Let's start with the theory of groups. Unfortunately Lean has groups already,
so we will have to do everything in a namespace
-/
namespace lftcm
/-
... which means that now when we define `group`, it will actually be called `lftcm.group`.
## Notation typeclasses
To make a term of type `has_mul G`, you need to give a map G^2 → G (or
more precisely, a map `has_mul.mul : G → G → G`. Lean's notation `g * h`
is notation for `has_mul.mul g h`. Furthermore, `has_mul` is a class.
In short, this means that if you write `[has_mul G]` then `G` will
magically have a multiplication called `*` (satisfying no axioms).
Similarly `[has_one G]` gives you `has_one.one : G` with notation `1 : G`,
and `[has_inv G]` gives you `has_inv.inv : G → G` with notation `g⁻¹ : G`
## Definition of a group
If `G` is a type, equipped with `* : G^2 → G`, `1 : G` and `⁻¹ : G → G`
then it's a group if it satisfies the group axioms.
-/
-- `group G` is the type of group structures on a type `G`.
-- first we ask for the structure
class group (G : Type) extends has_mul G, has_one G, has_inv G :=
-- and then we ask for the axioms
(mul_assoc : ∀ (a b c : G), a * b * c = a * (b * c))
(one_mul : ∀ (a : G), 1 * a = a)
(mul_left_inv : ∀ (a : G), a⁻¹ * a = 1)
/-
Advantages of this approach: axioms look lovely.
Disadvantage: what if I want the group law to be `+`?? I have embedded `has_mul`
in the definition.
Lean's solution: develop a `to_additive` metaprogram which translates all theorems about
`group`s (with group law `*`) to theorems about `add_group`s (with group law `+`). We will
not go into details here.
-/
namespace group
-- let G be a group
variables {G : Type} [group G]
/-
Lemmas about groups are proved in this namespace. We already have some!
All the group axioms are theorems in this namespace. Indeed we have just defined
`group.mul_assoc : ∀ (a b c : G), a * b * c = a * (b * c)`
`group.one_mul : ∀ (a : G), 1 * a = a`
`group.mul_left_inv : ∀ (a : G), a⁻¹ * a = 1`
Because we are in the `group` namespace, we don't need to write `group.`
everywhere.
Let's put some more theorems into the `group` namespace.
We definitely need `mul_one` and `mul_right_inv`, and it's a fun exercise to
get them. Here is a route:
`mul_left_cancel : ∀ (a b c : G), a * b = a * c → b = c`
`mul_eq_of_eq_inv_mul {a x y : G} : x = a⁻¹ * y → a * x = y`
`mul_one (a : G) : a * 1 = a`
`mul_right_inv (a : G) : a * a⁻¹ = 1`
-/
lemma mul_left_cancel (a b c : G) (Habac : a * b = a * c) : b = c :=
calc b = 1 * b : by rw one_mul
... = (a⁻¹ * a) * b : /- inline sorry -/by rw mul_left_inv/- inline sorry -/
... = a⁻¹ * (a * b) : /- inline sorry -/by rw mul_assoc/- inline sorry -/
... = a⁻¹ * (a * c) : /- inline sorry -/by rw Habac/- inline sorry -/
... = (a⁻¹ * a) * c : /- inline sorry -/by rw mul_assoc/- inline sorry -/
... = 1 * c : /- inline sorry -/by rw mul_left_inv/- inline sorry -/
... = c : /- inline sorry -/by rw one_mul/- inline sorry -/
-- more mathlib-ish proof:
lemma mul_left_cancel' (a b c : G) (Habac : a * b = a * c) : b = c :=
begin
rw [←one_mul b, ←mul_left_inv a, mul_assoc, Habac, ←mul_assoc, mul_left_inv, one_mul],
end
lemma mul_eq_of_eq_inv_mul {a x y : G} (h : x = a⁻¹ * y) : a * x = y :=
begin
apply mul_left_cancel a⁻¹,
-- ⊢ a⁻¹ * (a * x) = a⁻¹ * y
-- sorry
rw ←mul_assoc,
-- ⊢ a⁻¹ * a * x = a⁻¹ * y (remember this means (a⁻¹ * a) * x = ...)
rw mul_left_inv,
-- ⊢ 1 * x = a⁻¹ * y
rw one_mul,
-- ⊢ x = a⁻¹ * y
exact h
-- sorry
end
-- The same proof
lemma mul_eq_of_eq_inv_mul' {a x y : G} (h : x = a⁻¹ * y) : a * x = y :=
mul_left_cancel a⁻¹ _ _ $ by rwa [←mul_assoc, mul_left_inv, one_mul]
/-
So now we can finally prove `mul_one` and `mul_right_inv`.
But before we start, let's learn a little bit about the simplifier.
## The `simp` tactic -- Lean's simplifier
We have the theorems (axioms) `one_mul g : 1 * g = g` and
`mul_left_inv g : g⁻¹ * g = 1`. Both of these theorems are of
the form `A = B`, with `A` more complicated than `B`. This means
that they are *perfect* theorems for the simplifier. Let's teach
those theorems to the simplifier, by adding the `@[simp]` attribute to them.
An "attribute" is just a tag which we attach to a theorem (or definition).
-/
attribute [simp] one_mul mul_left_inv
/-
Now let's prove `mul_one` using the simplifier. This also a perfect
`simp` lemma, so let's also add the `simp` tag to it.
-/
@[simp] theorem mul_one (a : G) : a * 1 = a :=
begin
apply mul_eq_of_eq_inv_mul,
-- ⊢ 1 = a⁻¹ * a
simp,
end
/-
The simplifier solved `1 = a⁻¹ * a` because it knew `mul_left_inv`.
Feel free to comment out the `attribute [simp] one_mul mul_left_inv` line
above, and observe that the proof breaks.
-/
-- term mode proof
theorem mul_one' (a : G) : a * 1 = a :=
mul_eq_of_eq_inv_mul $ by simp
-- see if you can get the simplifier to do this one too
@[simp] theorem mul_right_inv (a : G) : a * a⁻¹ = 1 :=
begin
-- sorry
apply mul_eq_of_eq_inv_mul,
-- ⊢ a⁻¹ = a⁻¹ * 1
simp
-- sorry
end
-- Now here's a question. Can we train the simplifier to solve the following problem:
--example (a b c d : G) :
-- ((a * b)⁻¹ * a * 1⁻¹⁻¹⁻¹ * b⁻¹ * b * b * 1 * 1⁻¹)⁻¹ = (c⁻¹⁻¹ * d * d⁻¹ * 1⁻¹⁻¹ * c⁻¹⁻¹⁻¹)⁻¹⁻¹ :=
--by simp
-- Remove the --'s and see that it fails. Let's see if we can get it to work.
-- We start with two very natural `simp` lemmas.
@[simp] lemma one_inv : (1 : G)⁻¹ = 1 :=
begin
-- sorry
apply mul_left_cancel (1 : G),
simp,
-- sorry
end
@[simp] lemma inv_inv (a : G) : a⁻¹⁻¹ = a :=
begin
-- sorry
apply mul_left_cancel a⁻¹,
simp,
-- sorry
end
-- Here is a riskier looking `[simp]` lemma.
attribute [simp] mul_assoc -- recall this says (a * b) * c = a * (b * c)
-- The simplifier will now push all brackets to the right, which means
-- that it's worth proving the following two lemmas and tagging
-- them `[simp]`, so that we can still cancel a with a⁻¹ in these situations.
@[simp] lemma inv_mul_cancel_left (a b : G) : a⁻¹ * (a * b) = b :=
begin
-- sorry
rw ←mul_assoc,
simp,
-- sorry
end
@[simp] lemma mul_inv_cancel_left (a b : G) : a * (a⁻¹ * b) = b :=
begin
-- sorry
rw ←mul_assoc,
simp
-- sorry
end
-- Finally, let's make a `simp` lemma which enables us to
-- reduce all inverses to inverses of variables
@[simp] lemma mul_inv_rev (a b : G) : (a * b)⁻¹ = b⁻¹ * a⁻¹ :=
begin
-- sorry
apply mul_left_cancel (a * b),
rw mul_right_inv,
simp,
-- sorry
end
/-
If you solved them all -- congratulations!
You have just turned Lean's simplifier into a normalising confluent
rewriting system for groups, following Knuth-Bendix.
https://en.wikipedia.org/wiki/Confluence_(abstract_rewriting)#Motivating_examples
In other words, the simplifier will now put any element of a free group
into a canonical normal form, and can hence solve the word problem
for free groups.
-/
example (a b c d : G) :
((a * b)⁻¹ * a * 1⁻¹⁻¹⁻¹ * b⁻¹ * b * b * 1 * 1⁻¹)⁻¹ = (c⁻¹⁻¹ * d * d⁻¹ * 1⁻¹⁻¹ * c⁻¹⁻¹⁻¹)⁻¹⁻¹ :=
by simp
-- Abstract example of the power of classes: we can define products of groups with instances
instance (G : Type) [group G] (H : Type) [group H] : group (G × H) :=
{ mul := λ k l, (k.1*l.1, k.2*l.2),
one := (1,1),
inv := λ k, (k.1⁻¹, k.2⁻¹),
mul_assoc := begin
intros a b c,
cases a, cases b, cases c,
ext;
simp,
end,
one_mul := begin
-- sorry
intro a,
cases a,
ext;
simp,
-- sorry
end,
mul_left_inv := begin
-- sorry
intro a,
cases a,
ext;
simp
-- sorry
end }
-- the type class inference system now knows that products of groups are groups
example (G H K : Type) [group G] [group H] [group K] : group (G × H × K) :=
by apply_instance
end group
-- let's make a group of order two.
-- First the elements {+1, -1}
inductive mu2
| p1 : mu2
| m1 : mu2
namespace mu2
-- Now let's do some CS stuff:
-- 1) prove it has decidable equality
attribute [derive decidable_eq] mu2
-- 2) prove it is finite
instance : fintype mu2 := ⟨⟨[mu2.p1, mu2.m1], by simp⟩, λ x, by cases x; simp⟩
-- now back to the maths.
-- Define multiplication by doing all cases
def mul : mu2 → mu2 → mu2
| p1 p1 := p1
| p1 m1 := m1
| m1 p1 := m1
| m1 m1 := p1
instance : has_mul mu2 := ⟨mul⟩
-- identity
def one : mu2 := p1
-- notation
instance : has_one mu2 := ⟨one⟩
-- inverse
def inv : mu2 → mu2 := id
-- notation
instance : has_inv mu2 := ⟨inv⟩
-- currently we have notation but no axioms
example : p1 * m1 * m1 = p1⁻¹ * p1 := rfl -- all true by definition
-- now let's make it a group
instance : group mu2 :=
begin
-- first define the structure
refine_struct { mul := mul, one := one, inv := inv },
-- now we have three goals (the axioms)
all_goals {exact dec_trivial}
end
end mu2
-- Now let's build rings and modules and stuff (via monoids and add_comm_groups)
-- a monoid is a group without inverses
class monoid (M : Type) extends has_mul M, has_one M :=
(mul_assoc : ∀ (a b c : M), a * b * c = a * (b * c))
(one_mul : ∀ (a : M), 1 * a = a)
(mul_one : ∀ (a : M), a * 1 = a)
-- additive commutative groups from first principles
class add_comm_group (A : Type) extends has_add A, has_zero A, has_neg A :=
(add_assoc : ∀ (a b c : A), a + b + c = a + (b + c))
(zero_add : ∀ (a : A), 0 + a = a)
(add_left_neg : ∀ (a : A), -a + a = 0)
(add_comm : ∀ a b : A, a + b = b + a)
-- Notation for subtraction is handy to have; define a - b to be a + (-b)
instance (A : Type) [add_comm_group A] : has_sub A := ⟨λ a b, a + -b⟩
-- rings are additive abelian groups and multiplicative monoids,
-- with distributivity
class ring (R : Type) extends monoid R, add_comm_group R :=
(mul_add : ∀ (a b c : R), a * (b + c) = a * b + a * c)
(add_mul : ∀ (a b c : R), (a + b) * c = a * c + b * c)
-- for commutative rings, add commutativity of multiplication
class comm_ring (R : Type) extends ring R :=
(mul_comm : ∀ a b : R, a * b = b * a)
/-- Typeclass for types with a scalar multiplication operation, denoted `•` (`\bu`) -/
class has_scalar (R : Type) (M : Type) := (smul : R → M → M)
infixr ` • `:73 := has_scalar.smul
-- modules for a ring
class module (R : Type) [ring R] (M : Type) [add_comm_group M]
extends has_scalar R M :=
(smul_add : ∀(r : R) (x y : M), r • (x + y) = r • x + r • y)
(add_smul : ∀(r s : R) (x : M), (r + s) • x = r • x + s • x)
(mul_smul : ∀ (r s : R) (x : M), (r * s) • x = r • s • x)
(one_smul : ∀ x : M, (1 : R) • x = x)
-- for fields we let ⁻¹ be defined on the entire field, and demand 0⁻¹ = 0
-- and that a⁻¹ * a = 1 for non-zero a. This is merely for convenience;
-- one can easily check that it's mathematically equivalent to the usual
-- definition of a field.
class field (K : Type) extends comm_ring K, has_inv K :=
(zero_ne_one : (0 : K) ≠ 1)
(mul_inv_cancel : ∀ {a : K}, a ≠ 0 → a * a⁻¹ = 1)
(inv_zero : (0 : K)⁻¹ = 0)
-- the type of vector spaces
def vector_space (K : Type) [field K] (V : Type) [add_comm_group V] := module K V
/-
Exercise for the reader: define manifolds, schemes, perfectoid spaces in Lean.
All have been done! As you can see, it is clearly *feasible*, although it does
sometimes take time to get it right. It is all very much work in progress.
The extraordinary thing is that although these computer theorem
provers have been around for about 50 years, there has never been a serious
effort to make the standard definitions used all over modern mathematics in
one of them, and this is why these systems are rarely used in mathematics departments.
Changing this is one of the goals of the Leanprover community.
-/
/-
Let's check that we can make the rational numbers into a field. Of course
they are already a field in Lean, but remember that when we say `field`
below, we mean our just-defined structure `lftcm.field`.
-/
-- the rationals are a field (easy because all the work is done in the import)
instance : field ℚ :=
{ mul := (*),
one := 1,
mul_assoc := rat.mul_assoc,
one_mul := rat.one_mul,
mul_one := rat.mul_one,
add := (+),
zero := 0,
neg := has_neg.neg, -- no () trickery for unary operators
add_assoc := rat.add_assoc,
zero_add := rat.zero_add,
add_left_neg := rat.add_left_neg,
add_comm := rat.add_comm,
mul_add := rat.mul_add,
add_mul := rat.add_mul,
mul_comm := rat.mul_comm,
inv := has_inv.inv, -- see neg
zero_ne_one := rat.zero_ne_one,
mul_inv_cancel := rat.mul_inv_cancel,
inv_zero := inv_zero -- I don't know why rat.inv_zero was never explicitly defined
}
/-
Below is evidence that we can prove basic theorems about these structures.
Note however that it is a *complete pain* because we are *re-implementing*
everything; `add_comm` defaults to Lean's version for Lean's `add_comm_group`s, so we
have to explicitly write `add_comm_group.add_comm` to use our own version.
The mathlib versions of these proofs are less ugly.
-/
variables {A : Type} [add_comm_group A]
lemma add_comm_group.add_left_cancel (a b c : A) (Habac : a + b = a + c) : b = c :=
begin
rw ←add_comm_group.zero_add b,
rw ←add_comm_group.add_left_neg a,
rw add_comm_group.add_assoc,
rw Habac,
rw ←add_comm_group.add_assoc,
rw add_comm_group.add_left_neg,
rw add_comm_group.zero_add,
end
lemma add_comm_group.add_right_neg (a : A) : a + -a = 0 :=
begin
rw add_comm_group.add_comm,
rw add_comm_group.add_left_neg,
end
lemma add_comm_group.sub_eq_add_neg (a b : A) :
a - b = a + -b :=
begin
-- this is just our definition of subtraction
refl
end
lemma add_comm_group.sub_self (a : A) : a - a = 0 :=
begin
rw add_comm_group.sub_eq_add_neg,
rw add_comm_group.add_comm,
rw add_comm_group.add_left_neg,
end
lemma add_comm_group.neg_eq_of_add_eq_zero (a b : A) (h : a + b = 0) : -a = b :=
begin
apply add_comm_group.add_left_cancel a,
rw h,
rw add_comm_group.add_right_neg,
end
lemma add_comm_group.add_zero (a : A) : a + 0 = a :=
begin
rw add_comm_group.add_comm,
rw add_comm_group.zero_add,
end
variables {R : Type} [ring R]
lemma ring.mul_zero (r : R) : r * 0 = 0 :=
begin
apply add_comm_group.add_left_cancel (r * 0),
rw ←ring.mul_add,
rw add_comm_group.add_zero,
rw add_comm_group.add_zero,
end
lemma ring.mul_neg (a b : R) : a * -b = -(a * b) :=
begin
-- sorry
symmetry,
apply add_comm_group.neg_eq_of_add_eq_zero,
rw ←ring.mul_add,
rw add_comm_group.add_right_neg,
rw ring.mul_zero
-- sorry
end
lemma ring.mul_sub (R : Type) [comm_ring R] (r a b : R) : r * (a - b) = r * a - r * b :=
begin
-- sorry
rw add_comm_group.sub_eq_add_neg,
rw ring.mul_add,
rw ring.mul_neg,
refl,
-- sorry
end
lemma comm_ring.sub_mul (R : Type) [comm_ring R] (r a b : R) : (a - b) * r = a * r - b * r :=
begin
-- sorry
rw comm_ring.mul_comm (a - b),
rw comm_ring.mul_comm a,
rw comm_ring.mul_comm b,
apply ring.mul_sub
-- sorry
end
-- etc etc, for thousands of lines of mathlib, which develop the interface
-- abelian groups, rings, commutative rings, modules, fields, vector spaces etc.
end lftcm
/-
## Advertisement
Finished the natural number game? Have Lean installed? Want more games/exercises?
Take a look at the following projects, many of which are ongoing but
the first three of which are pretty much ready:
*) The complex number game (complete, needs to be played within VS Code)
https://github.com/ImperialCollegeLondon/complex-number-game
To install, type
`leanproject get ImperialCollegeLondon/complex-number-game`
and then just open the levels in `src/complex`.
*) Undergraduate level mathematics Lean puzzles (plenty of stuff here,
and more appearing over the summer):
https://github.com/ImperialCollegeLondon/Example-Lean-Projects
`leanproject get ImperialCollegeLondon/Example-Lean-Projects`
*) The max mini-game (a simple browser game like the natural number game)
http://wwwf.imperial.ac.uk/~buzzard/xena/max_minigame/
(this is part of what will become the real number game, a game to teach
series, sequences and limits etc like the natural number game):
`leanproject get ImperialCollegeLondon/real-number-game`
*) Some commutative algebra experiments (ongoing work to prove the Nullstellensatz,
going slowly because I'm busy):
https://github.com/ImperialCollegeLondon/M4P33/blob/1a179372db71ad6802d11eacbc1f02f327d55f8f/src/for_mathlib/commutative_algebra/Zariski_lemma.lean#L80-L81
`leanproject get ImperialCollegeLondon/M4P33`
*) The group theory game (work in progress, expect more progress over the summer,
as a couple of undergraduates are working on it)
https://github.com/ImperialCollegeLondon/group-theory-game
`leanproject get ImperialCollegeLondon/group-theory-game`
*) Galois theory experiments
https://github.com/ImperialCollegeLondon/P11-Galois-Theory
`leanproject get ImperialCollegeLondon/P11-Galois-Theory`
*) Beginnings of the theory of condensed sets (currently on hold because
we need a good interface for abelian categories in mathlib)
https://github.com/ImperialCollegeLondon/condensed-sets
`leanproject get ImperialCollegeLondon/condensed-sets`
## The Xena Project
Why do these projects exist? I (Kevin Buzzard) am interested in teaching
undergraduates how to use Lean. I have been running a club at Imperial College London
called the Xena Project for the last three years, I am proud that many Imperial
mathematics undegraduates have contributed to Lean's maths library, and three of them
(Chris Hughes, Kenny Lau, Amelia Livingston) have each contributed over 5,000 lines of
code. It is non-trivial to get your work into such a polished state that it
is acceptable to the mathlib maintainers. It is also very good practice.
I am running Lean summer projects this summer, on a Discord server. If you
know of any undergraduates who you think might be interested in Lean, please
direct them to the Xena Project Discord!
https://discord.gg/BgyVYgJ
Undergraduates use Discord for lots of things, and seem to be more likely
to use a Discord server than the Zulip chat. The Discord server is chaotic and
full of off-topic material -- quite unlike the Lean Zulip server, which is
professional and focussed. If you have a serious question about Lean,
ask it on the Zulip chat! But if you know an undergraduate who is interested
in Lean, they might be interested in the Discord server. We have meetings
every Thursday evening (UK time), with live Lean coding and streaming, speedruns,
there is music, people posting pictures of cats, Haikus, and so on. To a large
extent it is run by undergraduates and PhD students. Over the summer (July
and August 2020) there are also live Twitch talks at https://www.twitch.tv/kbuzzard ,
on Tuesdays 10am and Thursdays 4pm UK time (UTC+1), aimed at mathematics
undergraduates. It is an informal place for undergraduates to hang out and
meet other undergraduates who are interested in Lean.
I believe that it is crucial to make undergraduates aware of computer proof
verification systems, because one day (possibly a long time in the future,
but one day) these things will cause a paradigm shift in the way mathematics
is done, and the sooner young mathematicians learn about them, the sooner it will happen.
Prove a theorem. Write a function. @XenaProject
https://twitter.com/XenaProject
-/
|
18ef4ac22da51e744fec2b133fe9458fa60b6451 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/data/seq/wseq_auto.lean | c758bb5f58f947abab5a38d73020e8d9af1bdb93 | [] | 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 | 37,017 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.seq.seq
import Mathlib.Lean3Lib.data.dlist
import Mathlib.PostPort
universes u_1 u v w
namespace Mathlib
/-
coinductive wseq (α : Type u) : Type u
| nil : wseq α
| cons : α → wseq α → wseq α
| think : wseq α → wseq α
-/
/-- Weak sequences.
While the `seq` structure allows for lists which may not be finite,
a weak sequence also allows the computation of each element to
involve an indeterminate amount of computation, including possibly
an infinite loop. This is represented as a regular `seq` interspersed
with `none` elements to indicate that computation is ongoing.
This model is appropriate for Haskell style lazy lists, and is closed
under most interesting computation patterns on infinite lists,
but conversely it is difficult to extract elements from it. -/
def wseq (α : Type u_1) := seq (Option α)
namespace wseq
/-- Turn a sequence into a weak sequence -/
def of_seq {α : Type u} : seq α → wseq α := Functor.map some
/-- Turn a list into a weak sequence -/
def of_list {α : Type u} (l : List α) : wseq α := of_seq ↑l
/-- Turn a stream into a weak sequence -/
def of_stream {α : Type u} (l : stream α) : wseq α := of_seq ↑l
protected instance coe_seq {α : Type u} : has_coe (seq α) (wseq α) := has_coe.mk of_seq
protected instance coe_list {α : Type u} : has_coe (List α) (wseq α) := has_coe.mk of_list
protected instance coe_stream {α : Type u} : has_coe (stream α) (wseq α) := has_coe.mk of_stream
/-- The empty weak sequence -/
def nil {α : Type u} : wseq α := seq.nil
protected instance inhabited {α : Type u} : Inhabited (wseq α) := { default := nil }
/-- Prepend an element to a weak sequence -/
def cons {α : Type u} (a : α) : wseq α → wseq α := seq.cons (some a)
/-- Compute for one tick, without producing any elements -/
def think {α : Type u} : wseq α → wseq α := seq.cons none
/-- Destruct a weak sequence, to (eventually possibly) produce either
`none` for `nil` or `some (a, s)` if an element is produced. -/
def destruct {α : Type u} : wseq α → computation (Option (α × wseq α)) :=
computation.corec fun (s : wseq α) => sorry
def cases_on {α : Type u} {C : wseq α → Sort v} (s : wseq α) (h1 : C nil)
(h2 : (x : α) → (s : wseq α) → C (cons x s)) (h3 : (s : wseq α) → C (think s)) : C s :=
seq.cases_on s h1 fun (o : Option α) => option.cases_on o h3 h2
protected def mem {α : Type u} (a : α) (s : wseq α) := seq.mem (some a) s
protected instance has_mem {α : Type u} : has_mem α (wseq α) := has_mem.mk wseq.mem
theorem not_mem_nil {α : Type u} (a : α) : ¬a ∈ nil := seq.not_mem_nil ↑a
/-- Get the head of a weak sequence. This involves a possibly
infinite computation. -/
def head {α : Type u} (s : wseq α) : computation (Option α) :=
computation.map (Functor.map prod.fst) (destruct s)
/-- Encode a computation yielding a weak sequence into additional
`think` constructors in a weak sequence -/
def flatten {α : Type u} : computation (wseq α) → wseq α :=
seq.corec fun (c : computation (wseq α)) => sorry
/-- Get the tail of a weak sequence. This doesn't need a `computation`
wrapper, unlike `head`, because `flatten` allows us to hide this
in the construction of the weak sequence itself. -/
def tail {α : Type u} (s : wseq α) : wseq α :=
flatten ((fun (o : Option (α × wseq α)) => option.rec_on o nil prod.snd) <$> destruct s)
/-- drop the first `n` elements from `s`. -/
@[simp] def drop {α : Type u} (s : wseq α) : ℕ → wseq α := sorry
/-- Get the nth element of `s`. -/
def nth {α : Type u} (s : wseq α) (n : ℕ) : computation (Option α) := head (drop s n)
/-- Convert `s` to a list (if it is finite and completes in finite time). -/
def to_list {α : Type u} (s : wseq α) : computation (List α) :=
computation.corec (fun (_x : List α × wseq α) => sorry) ([], s)
/-- Get the length of `s` (if it is finite and completes in finite time). -/
def length {α : Type u} (s : wseq α) : computation ℕ :=
computation.corec (fun (_x : ℕ × wseq α) => sorry) (0, s)
/-- A weak sequence is finite if `to_list s` terminates. Equivalently,
it is a finite number of `think` and `cons` applied to `nil`. -/
def is_finite {α : Type u} (s : wseq α) := computation.terminates (to_list s)
protected instance to_list_terminates {α : Type u} (s : wseq α) [h : is_finite s] :
computation.terminates (to_list s) :=
h
/-- Get the list corresponding to a finite weak sequence. -/
def get {α : Type u} (s : wseq α) [is_finite s] : List α := computation.get (to_list s)
/-- A weak sequence is *productive* if it never stalls forever - there are
always a finite number of `think`s between `cons` constructors.
The sequence itself is allowed to be infinite though. -/
def productive {α : Type u} (s : wseq α) := ∀ (n : ℕ), computation.terminates (nth s n)
protected instance nth_terminates {α : Type u} (s : wseq α) [h : productive s] (n : ℕ) :
computation.terminates (nth s n) :=
h
protected instance head_terminates {α : Type u} (s : wseq α) [h : productive s] :
computation.terminates (head s) :=
h 0
/-- Replace the `n`th element of `s` with `a`. -/
def update_nth {α : Type u} (s : wseq α) (n : ℕ) (a : α) : wseq α :=
seq.corec (fun (_x : ℕ × wseq α) => sorry) (n + 1, s)
/-- Remove the `n`th element of `s`. -/
def remove_nth {α : Type u} (s : wseq α) (n : ℕ) : wseq α :=
seq.corec (fun (_x : ℕ × wseq α) => sorry) (n + 1, s)
/-- Map the elements of `s` over `f`, removing any values that yield `none`. -/
def filter_map {α : Type u} {β : Type v} (f : α → Option β) : wseq α → wseq β :=
seq.corec fun (s : wseq α) => sorry
/-- Select the elements of `s` that satisfy `p`. -/
def filter {α : Type u} (p : α → Prop) [decidable_pred p] : wseq α → wseq α :=
filter_map fun (a : α) => ite (p a) (some a) none
-- example of infinite list manipulations
/-- Get the first element of `s` satisfying `p`. -/
def find {α : Type u} (p : α → Prop) [decidable_pred p] (s : wseq α) : computation (Option α) :=
head (filter p s)
/-- Zip a function over two weak sequences -/
def zip_with {α : Type u} {β : Type v} {γ : Type w} (f : α → β → γ) (s1 : wseq α) (s2 : wseq β) :
wseq γ :=
seq.corec (fun (_x : wseq α × wseq β) => sorry) (s1, s2)
/-- Zip two weak sequences into a single sequence of pairs -/
def zip {α : Type u} {β : Type v} : wseq α → wseq β → wseq (α × β) := zip_with Prod.mk
/-- Get the list of indexes of elements of `s` satisfying `p` -/
def find_indexes {α : Type u} (p : α → Prop) [decidable_pred p] (s : wseq α) : wseq ℕ :=
filter_map (fun (_x : α × ℕ) => sorry) (zip s ↑stream.nats)
/-- Get the index of the first element of `s` satisfying `p` -/
def find_index {α : Type u} (p : α → Prop) [decidable_pred p] (s : wseq α) : computation ℕ :=
(fun (o : Option ℕ) => option.get_or_else o 0) <$> head (find_indexes p s)
/-- Get the index of the first occurrence of `a` in `s` -/
def index_of {α : Type u} [DecidableEq α] (a : α) : wseq α → computation ℕ := find_index (Eq a)
/-- Get the indexes of occurrences of `a` in `s` -/
def indexes_of {α : Type u} [DecidableEq α] (a : α) : wseq α → wseq ℕ := find_indexes (Eq a)
/-- `union s1 s2` is a weak sequence which interleaves `s1` and `s2` in
some order (nondeterministically). -/
def union {α : Type u} (s1 : wseq α) (s2 : wseq α) : wseq α :=
seq.corec (fun (_x : wseq α × wseq α) => sorry) (s1, s2)
/-- Returns `tt` if `s` is `nil` and `ff` if `s` has an element -/
def is_empty {α : Type u} (s : wseq α) : computation Bool := computation.map option.is_none (head s)
/-- Calculate one step of computation -/
def compute {α : Type u} (s : wseq α) : wseq α := sorry
/-- Get the first `n` elements of a weak sequence -/
def take {α : Type u} (s : wseq α) (n : ℕ) : wseq α :=
seq.corec (fun (_x : ℕ × wseq α) => sorry) (n, s)
/-- Split the sequence at position `n` into a finite initial segment
and the weak sequence tail -/
def split_at {α : Type u} (s : wseq α) (n : ℕ) : computation (List α × wseq α) :=
computation.corec (fun (_x : ℕ × List α × wseq α) => sorry) (n, [], s)
/-- Returns `tt` if any element of `s` satisfies `p` -/
def any {α : Type u} (s : wseq α) (p : α → Bool) : computation Bool :=
computation.corec (fun (s : wseq α) => sorry) s
/-- Returns `tt` if every element of `s` satisfies `p` -/
def all {α : Type u} (s : wseq α) (p : α → Bool) : computation Bool :=
computation.corec (fun (s : wseq α) => sorry) s
/-- Apply a function to the elements of the sequence to produce a sequence
of partial results. (There is no `scanr` because this would require
working from the end of the sequence, which may not exist.) -/
def scanl {α : Type u} {β : Type v} (f : α → β → α) (a : α) (s : wseq β) : wseq α :=
cons a (seq.corec (fun (_x : α × wseq β) => sorry) (a, s))
/-- Get the weak sequence of initial segments of the input sequence -/
def inits {α : Type u} (s : wseq α) : wseq (List α) :=
cons [] (seq.corec (fun (_x : dlist α × wseq α) => sorry) (dlist.empty, s))
/-- Like take, but does not wait for a result. Calculates `n` steps of
computation and returns the sequence computed so far -/
def collect {α : Type u} (s : wseq α) (n : ℕ) : List α := list.filter_map id (seq.take n s)
/-- Append two weak sequences. As with `seq.append`, this may not use
the second sequence if the first one takes forever to compute -/
def append {α : Type u} : wseq α → wseq α → wseq α := seq.append
/-- Map a function over a weak sequence -/
def map {α : Type u} {β : Type v} (f : α → β) : wseq α → wseq β := seq.map (option.map f)
/-- Flatten a sequence of weak sequences. (Note that this allows
empty sequences, unlike `seq.join`.) -/
def join {α : Type u} (S : wseq (wseq α)) : wseq α :=
seq.join ((fun (o : Option (wseq α)) => sorry) <$> S)
/-- Monadic bind operator for weak sequences -/
def bind {α : Type u} {β : Type v} (s : wseq α) (f : α → wseq β) : wseq β := join (map f s)
@[simp] def lift_rel_o {α : Type u} {β : Type v} (R : α → β → Prop) (C : wseq α → wseq β → Prop) :
Option (α × wseq α) → Option (β × wseq β) → Prop :=
sorry
theorem lift_rel_o.imp {α : Type u} {β : Type v} {R : α → β → Prop} {S : α → β → Prop}
{C : wseq α → wseq β → Prop} {D : wseq α → wseq β → Prop}
(H1 : ∀ (a : α) (b : β), R a b → S a b) (H2 : ∀ (s : wseq α) (t : wseq β), C s t → D s t)
{o : Option (α × wseq α)} {p : Option (β × wseq β)} : lift_rel_o R C o p → lift_rel_o S D o p :=
sorry
theorem lift_rel_o.imp_right {α : Type u} {β : Type v} (R : α → β → Prop)
{C : wseq α → wseq β → Prop} {D : wseq α → wseq β → Prop}
(H : ∀ (s : wseq α) (t : wseq β), C s t → D s t) {o : Option (α × wseq α)}
{p : Option (β × wseq β)} : lift_rel_o R C o p → lift_rel_o R D o p :=
lift_rel_o.imp (fun (_x : α) (_x_1 : β) => id) H
@[simp] def bisim_o {α : Type u} (R : wseq α → wseq α → Prop) :
Option (α × wseq α) → Option (α × wseq α) → Prop :=
lift_rel_o Eq R
theorem bisim_o.imp {α : Type u} {R : wseq α → wseq α → Prop} {S : wseq α → wseq α → Prop}
(H : ∀ (s t : wseq α), R s t → S s t) {o : Option (α × wseq α)} {p : Option (α × wseq α)} :
bisim_o R o p → bisim_o S o p :=
lift_rel_o.imp_right Eq H
/-- Two weak sequences are `lift_rel R` related if they are either both empty,
or they are both nonempty and the heads are `R` related and the tails are
`lift_rel R` related. (This is a coinductive definition.) -/
def lift_rel {α : Type u} {β : Type v} (R : α → β → Prop) (s : wseq α) (t : wseq β) :=
∃ (C : wseq α → wseq β → Prop),
C s t ∧
∀ {s : wseq α} {t : wseq β},
C s t → computation.lift_rel (lift_rel_o R C) (destruct s) (destruct t)
/-- If two sequences are equivalent, then they have the same values and
the same computational behavior (i.e. if one loops forever then so does
the other), although they may differ in the number of `think`s needed to
arrive at the answer. -/
def equiv {α : Type u} : wseq α → wseq α → Prop := lift_rel Eq
theorem lift_rel_destruct {α : Type u} {β : Type v} {R : α → β → Prop} {s : wseq α} {t : wseq β} :
lift_rel R s t → computation.lift_rel (lift_rel_o R (lift_rel R)) (destruct s) (destruct t) :=
sorry
theorem lift_rel_destruct_iff {α : Type u} {β : Type v} {R : α → β → Prop} {s : wseq α}
{t : wseq β} :
lift_rel R s t ↔ computation.lift_rel (lift_rel_o R (lift_rel R)) (destruct s) (destruct t) :=
sorry
infixl:50 " ~ " => Mathlib.wseq.equiv
theorem destruct_congr {α : Type u} {s : wseq α} {t : wseq α} :
s ~ t → computation.lift_rel (bisim_o equiv) (destruct s) (destruct t) :=
lift_rel_destruct
theorem destruct_congr_iff {α : Type u} {s : wseq α} {t : wseq α} :
s ~ t ↔ computation.lift_rel (bisim_o equiv) (destruct s) (destruct t) :=
lift_rel_destruct_iff
theorem lift_rel.refl {α : Type u} (R : α → α → Prop) (H : reflexive R) : reflexive (lift_rel R) :=
sorry
theorem lift_rel_o.swap {α : Type u} {β : Type v} (R : α → β → Prop) (C : wseq α → wseq β → Prop) :
function.swap (lift_rel_o R C) = lift_rel_o (function.swap R) (function.swap C) :=
sorry
theorem lift_rel.swap_lem {α : Type u} {β : Type v} {R : α → β → Prop} {s1 : wseq α} {s2 : wseq β}
(h : lift_rel R s1 s2) : lift_rel (function.swap R) s2 s1 :=
sorry
theorem lift_rel.swap {α : Type u} {β : Type v} (R : α → β → Prop) :
function.swap (lift_rel R) = lift_rel (function.swap R) :=
funext
fun (x : wseq β) =>
funext fun (y : wseq α) => propext { mp := lift_rel.swap_lem, mpr := lift_rel.swap_lem }
theorem lift_rel.symm {α : Type u} (R : α → α → Prop) (H : symmetric R) : symmetric (lift_rel R) :=
sorry
theorem lift_rel.trans {α : Type u} (R : α → α → Prop) (H : transitive R) :
transitive (lift_rel R) :=
sorry
theorem lift_rel.equiv {α : Type u} (R : α → α → Prop) : equivalence R → equivalence (lift_rel R) :=
sorry
theorem equiv.refl {α : Type u} (s : wseq α) : s ~ s := lift_rel.refl Eq Eq.refl
theorem equiv.symm {α : Type u} {s : wseq α} {t : wseq α} : s ~ t → t ~ s :=
lift_rel.symm Eq Eq.symm
theorem equiv.trans {α : Type u} {s : wseq α} {t : wseq α} {u : wseq α} : s ~ t → t ~ u → s ~ u :=
lift_rel.trans Eq Eq.trans
theorem equiv.equivalence {α : Type u} : equivalence equiv :=
{ left := equiv.refl, right := { left := equiv.symm, right := equiv.trans } }
@[simp] theorem destruct_nil {α : Type u} : destruct nil = computation.return none :=
computation.destruct_eq_ret rfl
@[simp] theorem destruct_cons {α : Type u} (a : α) (s : wseq α) :
destruct (cons a s) = computation.return (some (a, s)) :=
sorry
@[simp] theorem destruct_think {α : Type u} (s : wseq α) :
destruct (think s) = computation.think (destruct s) :=
sorry
@[simp] theorem seq_destruct_nil {α : Type u} : seq.destruct nil = none := seq.destruct_nil
@[simp] theorem seq_destruct_cons {α : Type u} (a : α) (s : wseq α) :
seq.destruct (cons a s) = some (some a, s) :=
seq.destruct_cons (some a) s
@[simp] theorem seq_destruct_think {α : Type u} (s : wseq α) :
seq.destruct (think s) = some (none, s) :=
seq.destruct_cons none s
@[simp] theorem head_nil {α : Type u} : head nil = computation.return none := sorry
@[simp] theorem head_cons {α : Type u} (a : α) (s : wseq α) :
head (cons a s) = computation.return (some a) :=
sorry
@[simp] theorem head_think {α : Type u} (s : wseq α) :
head (think s) = computation.think (head s) :=
sorry
@[simp] theorem flatten_ret {α : Type u} (s : wseq α) : flatten (computation.return s) = s := sorry
@[simp] theorem flatten_think {α : Type u} (c : computation (wseq α)) :
flatten (computation.think c) = think (flatten c) :=
sorry
@[simp] theorem destruct_flatten {α : Type u} (c : computation (wseq α)) :
destruct (flatten c) = c >>= destruct :=
sorry
theorem head_terminates_iff {α : Type u} (s : wseq α) :
computation.terminates (head s) ↔ computation.terminates (destruct s) :=
computation.terminates_map_iff (Functor.map prod.fst) (destruct s)
@[simp] theorem tail_nil {α : Type u} : tail nil = nil := sorry
@[simp] theorem tail_cons {α : Type u} (a : α) (s : wseq α) : tail (cons a s) = s := sorry
@[simp] theorem tail_think {α : Type u} (s : wseq α) : tail (think s) = think (tail s) := sorry
@[simp] theorem dropn_nil {α : Type u} (n : ℕ) : drop nil n = nil := sorry
@[simp] theorem dropn_cons {α : Type u} (a : α) (s : wseq α) (n : ℕ) :
drop (cons a s) (n + 1) = drop s n :=
sorry
@[simp] theorem dropn_think {α : Type u} (s : wseq α) (n : ℕ) :
drop (think s) n = think (drop s n) :=
sorry
theorem dropn_add {α : Type u} (s : wseq α) (m : ℕ) (n : ℕ) : drop s (m + n) = drop (drop s m) n :=
sorry
theorem dropn_tail {α : Type u} (s : wseq α) (n : ℕ) : drop (tail s) n = drop s (n + 1) :=
eq.mpr (id (Eq._oldrec (Eq.refl (drop (tail s) n = drop s (n + 1))) (add_comm n 1)))
(Eq.symm (dropn_add s 1 n))
theorem nth_add {α : Type u} (s : wseq α) (m : ℕ) (n : ℕ) : nth s (m + n) = nth (drop s m) n :=
congr_arg head (dropn_add s m n)
theorem nth_tail {α : Type u} (s : wseq α) (n : ℕ) : nth (tail s) n = nth s (n + 1) :=
congr_arg head (dropn_tail s n)
@[simp] theorem join_nil {α : Type u} : join nil = nil := seq.join_nil
@[simp] theorem join_think {α : Type u} (S : wseq (wseq α)) : join (think S) = think (join S) :=
sorry
@[simp] theorem join_cons {α : Type u} (s : wseq α) (S : wseq (wseq α)) :
join (cons s S) = think (append s (join S)) :=
sorry
@[simp] theorem nil_append {α : Type u} (s : wseq α) : append nil s = s := seq.nil_append s
@[simp] theorem cons_append {α : Type u} (a : α) (s : wseq α) (t : wseq α) :
append (cons a s) t = cons a (append s t) :=
seq.cons_append (some a) s t
@[simp] theorem think_append {α : Type u} (s : wseq α) (t : wseq α) :
append (think s) t = think (append s t) :=
seq.cons_append none s t
@[simp] theorem append_nil {α : Type u} (s : wseq α) : append s nil = s := seq.append_nil s
@[simp] theorem append_assoc {α : Type u} (s : wseq α) (t : wseq α) (u : wseq α) :
append (append s t) u = append s (append t u) :=
seq.append_assoc s t u
@[simp] def tail.aux {α : Type u} : Option (α × wseq α) → computation (Option (α × wseq α)) := sorry
theorem destruct_tail {α : Type u} (s : wseq α) : destruct (tail s) = destruct s >>= tail.aux :=
sorry
@[simp] def drop.aux {α : Type u} : ℕ → Option (α × wseq α) → computation (Option (α × wseq α)) :=
sorry
theorem drop.aux_none {α : Type u} (n : ℕ) : drop.aux n none = computation.return none := sorry
theorem destruct_dropn {α : Type u} (s : wseq α) (n : ℕ) :
destruct (drop s n) = destruct s >>= drop.aux n :=
sorry
theorem head_terminates_of_head_tail_terminates {α : Type u} (s : wseq α)
[T : computation.terminates (head (tail s))] : computation.terminates (head s) :=
sorry
theorem destruct_some_of_destruct_tail_some {α : Type u} {s : wseq α} {a : α × wseq α}
(h : some a ∈ destruct (tail s)) : ∃ (a' : α × wseq α), some a' ∈ destruct s :=
sorry
theorem head_some_of_head_tail_some {α : Type u} {s : wseq α} {a : α} (h : some a ∈ head (tail s)) :
∃ (a' : α), some a' ∈ head s :=
sorry
theorem head_some_of_nth_some {α : Type u} {s : wseq α} {a : α} {n : ℕ} (h : some a ∈ nth s n) :
∃ (a' : α), some a' ∈ head s :=
sorry
protected instance productive_tail {α : Type u} (s : wseq α) [productive s] : productive (tail s) :=
fun (n : ℕ) =>
eq.mpr (id (Eq._oldrec (Eq.refl (computation.terminates (nth (tail s) n))) (nth_tail s n)))
(wseq.nth_terminates s (n + 1))
protected instance productive_dropn {α : Type u} (s : wseq α) [productive s] (n : ℕ) :
productive (drop s n) :=
fun (m : ℕ) =>
eq.mpr
(id
(Eq._oldrec (Eq.refl (computation.terminates (nth (drop s n) m)))
(Eq.symm (nth_add s n m))))
(wseq.nth_terminates s (n + m))
/-- Given a productive weak sequence, we can collapse all the `think`s to
produce a sequence. -/
def to_seq {α : Type u} (s : wseq α) [productive s] : seq α :=
{ val := fun (n : ℕ) => computation.get (nth s n), property := sorry }
theorem nth_terminates_le {α : Type u} {s : wseq α} {m : ℕ} {n : ℕ} (h : m ≤ n) :
computation.terminates (nth s n) → computation.terminates (nth s m) :=
sorry
theorem head_terminates_of_nth_terminates {α : Type u} {s : wseq α} {n : ℕ} :
computation.terminates (nth s n) → computation.terminates (head s) :=
nth_terminates_le (nat.zero_le n)
theorem destruct_terminates_of_nth_terminates {α : Type u} {s : wseq α} {n : ℕ}
(T : computation.terminates (nth s n)) : computation.terminates (destruct s) :=
iff.mp (head_terminates_iff s) (head_terminates_of_nth_terminates T)
theorem mem_rec_on {α : Type u} {C : wseq α → Prop} {a : α} {s : wseq α} (M : a ∈ s)
(h1 : ∀ (b : α) (s' : wseq α), a = b ∨ C s' → C (cons b s'))
(h2 : ∀ (s : wseq α), C s → C (think s)) : C s :=
sorry
@[simp] theorem mem_think {α : Type u} (s : wseq α) (a : α) : a ∈ think s ↔ a ∈ s := sorry
theorem eq_or_mem_iff_mem {α : Type u} {s : wseq α} {a : α} {a' : α} {s' : wseq α} :
some (a', s') ∈ destruct s → (a ∈ s ↔ a = a' ∨ a ∈ s') :=
sorry
@[simp] theorem mem_cons_iff {α : Type u} (s : wseq α) (b : α) {a : α} :
a ∈ cons b s ↔ a = b ∨ a ∈ s :=
sorry
theorem mem_cons_of_mem {α : Type u} {s : wseq α} (b : α) {a : α} (h : a ∈ s) : a ∈ cons b s :=
iff.mpr (mem_cons_iff s b) (Or.inr h)
theorem mem_cons {α : Type u} (s : wseq α) (a : α) : a ∈ cons a s :=
iff.mpr (mem_cons_iff s a) (Or.inl rfl)
theorem mem_of_mem_tail {α : Type u} {s : wseq α} {a : α} : a ∈ tail s → a ∈ s := sorry
theorem mem_of_mem_dropn {α : Type u} {s : wseq α} {a : α} {n : ℕ} : a ∈ drop s n → a ∈ s := sorry
theorem nth_mem {α : Type u} {s : wseq α} {a : α} {n : ℕ} : some a ∈ nth s n → a ∈ s := sorry
theorem exists_nth_of_mem {α : Type u} {s : wseq α} {a : α} (h : a ∈ s) :
∃ (n : ℕ), some a ∈ nth s n :=
sorry
theorem exists_dropn_of_mem {α : Type u} {s : wseq α} {a : α} (h : a ∈ s) :
∃ (n : ℕ), ∃ (s' : wseq α), some (a, s') ∈ destruct (drop s n) :=
sorry
theorem lift_rel_dropn_destruct {α : Type u} {β : Type v} {R : α → β → Prop} {s : wseq α}
{t : wseq β} (H : lift_rel R s t) (n : ℕ) :
computation.lift_rel (lift_rel_o R (lift_rel R)) (destruct (drop s n)) (destruct (drop t n)) :=
sorry
theorem exists_of_lift_rel_left {α : Type u} {β : Type v} {R : α → β → Prop} {s : wseq α}
{t : wseq β} (H : lift_rel R s t) {a : α} (h : a ∈ s) : Exists fun {b : β} => b ∈ t ∧ R a b :=
sorry
theorem exists_of_lift_rel_right {α : Type u} {β : Type v} {R : α → β → Prop} {s : wseq α}
{t : wseq β} (H : lift_rel R s t) {b : β} (h : b ∈ t) : Exists fun {a : α} => a ∈ s ∧ R a b :=
exists_of_lift_rel_left
(eq.mp
(Eq._oldrec (Eq.refl (lift_rel R s t)) (Eq.symm (lift_rel.swap fun (x : β) (y : α) => R y x)))
H)
h
theorem head_terminates_of_mem {α : Type u} {s : wseq α} {a : α} (h : a ∈ s) :
computation.terminates (head s) :=
sorry
theorem of_mem_append {α : Type u} {s₁ : wseq α} {s₂ : wseq α} {a : α} :
a ∈ append s₁ s₂ → a ∈ s₁ ∨ a ∈ s₂ :=
seq.of_mem_append
theorem mem_append_left {α : Type u} {s₁ : wseq α} {s₂ : wseq α} {a : α} :
a ∈ s₁ → a ∈ append s₁ s₂ :=
seq.mem_append_left
theorem exists_of_mem_map {α : Type u} {β : Type v} {f : α → β} {b : β} {s : wseq α} :
b ∈ map f s → ∃ (a : α), a ∈ s ∧ f a = b :=
sorry
@[simp] theorem lift_rel_nil {α : Type u} {β : Type v} (R : α → β → Prop) : lift_rel R nil nil :=
sorry
@[simp] theorem lift_rel_cons {α : Type u} {β : Type v} (R : α → β → Prop) (a : α) (b : β)
(s : wseq α) (t : wseq β) : lift_rel R (cons a s) (cons b t) ↔ R a b ∧ lift_rel R s t :=
sorry
@[simp] theorem lift_rel_think_left {α : Type u} {β : Type v} (R : α → β → Prop) (s : wseq α)
(t : wseq β) : lift_rel R (think s) t ↔ lift_rel R s t :=
sorry
@[simp] theorem lift_rel_think_right {α : Type u} {β : Type v} (R : α → β → Prop) (s : wseq α)
(t : wseq β) : lift_rel R s (think t) ↔ lift_rel R s t :=
sorry
theorem cons_congr {α : Type u} {s : wseq α} {t : wseq α} (a : α) (h : s ~ t) :
cons a s ~ cons a t :=
sorry
theorem think_equiv {α : Type u} (s : wseq α) : think s ~ s :=
eq.mpr (id (congr_fun (congr_fun equiv.equations._eqn_1 (think s)) s))
(eq.mpr (id (propext (lift_rel_think_left Eq s s))) (equiv.refl s))
theorem think_congr {α : Type u} {s : wseq α} {t : wseq α} (a : α) (h : s ~ t) :
think s ~ think t :=
eq.mpr (id (congr_fun (congr_fun equiv.equations._eqn_1 (think s)) (think t)))
(eq.mpr
(id
(Eq.trans (propext (lift_rel_think_right Eq (think s) t))
(propext (lift_rel_think_left Eq s t))))
h)
theorem head_congr {α : Type u} {s : wseq α} {t : wseq α} : s ~ t → head s ~ head t := sorry
theorem flatten_equiv {α : Type u} {c : computation (wseq α)} {s : wseq α} (h : s ∈ c) :
flatten c ~ s :=
sorry
theorem lift_rel_flatten {α : Type u} {β : Type v} {R : α → β → Prop} {c1 : computation (wseq α)}
{c2 : computation (wseq β)} (h : computation.lift_rel (lift_rel R) c1 c2) :
lift_rel R (flatten c1) (flatten c2) :=
sorry
theorem flatten_congr {α : Type u} {c1 : computation (wseq α)} {c2 : computation (wseq α)} :
computation.lift_rel equiv c1 c2 → flatten c1 ~ flatten c2 :=
lift_rel_flatten
theorem tail_congr {α : Type u} {s : wseq α} {t : wseq α} (h : s ~ t) : tail s ~ tail t := sorry
theorem dropn_congr {α : Type u} {s : wseq α} {t : wseq α} (h : s ~ t) (n : ℕ) :
drop s n ~ drop t n :=
sorry
theorem nth_congr {α : Type u} {s : wseq α} {t : wseq α} (h : s ~ t) (n : ℕ) : nth s n ~ nth t n :=
head_congr (dropn_congr h n)
theorem mem_congr {α : Type u} {s : wseq α} {t : wseq α} (h : s ~ t) (a : α) : a ∈ s ↔ a ∈ t :=
sorry
theorem productive_congr {α : Type u} {s : wseq α} {t : wseq α} (h : s ~ t) :
productive s ↔ productive t :=
forall_congr fun (n : ℕ) => computation.terminates_congr (nth_congr h n)
theorem equiv.ext {α : Type u} {s : wseq α} {t : wseq α} (h : ∀ (n : ℕ), nth s n ~ nth t n) :
s ~ t :=
sorry
theorem length_eq_map {α : Type u} (s : wseq α) :
length s = computation.map list.length (to_list s) :=
sorry
@[simp] theorem of_list_nil {α : Type u} : of_list [] = nil := rfl
@[simp] theorem of_list_cons {α : Type u} (a : α) (l : List α) :
of_list (a :: l) = cons a (of_list l) :=
sorry
@[simp] theorem to_list'_nil {α : Type u} (l : List α) :
computation.corec to_list._match_2 (l, nil) = computation.return (list.reverse l) :=
computation.destruct_eq_ret rfl
@[simp] theorem to_list'_cons {α : Type u} (l : List α) (s : wseq α) (a : α) :
computation.corec to_list._match_2 (l, cons a s) =
computation.think (computation.corec to_list._match_2 (a :: l, s)) :=
sorry
@[simp] theorem to_list'_think {α : Type u} (l : List α) (s : wseq α) :
computation.corec to_list._match_2 (l, think s) =
computation.think (computation.corec to_list._match_2 (l, s)) :=
sorry
theorem to_list'_map {α : Type u} (l : List α) (s : wseq α) :
computation.corec to_list._match_2 (l, s) = append (list.reverse l) <$> to_list s :=
sorry
@[simp] theorem to_list_cons {α : Type u} (a : α) (s : wseq α) :
to_list (cons a s) = computation.think (List.cons a <$> to_list s) :=
sorry
@[simp] theorem to_list_nil {α : Type u} : to_list nil = computation.return [] :=
computation.destruct_eq_ret rfl
theorem to_list_of_list {α : Type u} (l : List α) : l ∈ to_list (of_list l) := sorry
@[simp] theorem destruct_of_seq {α : Type u} (s : seq α) :
destruct (of_seq s) =
computation.return (option.map (fun (a : α) => (a, of_seq (seq.tail s))) (seq.head s)) :=
sorry
@[simp] theorem head_of_seq {α : Type u} (s : seq α) :
head (of_seq s) = computation.return (seq.head s) :=
sorry
@[simp] theorem tail_of_seq {α : Type u} (s : seq α) : tail (of_seq s) = of_seq (seq.tail s) :=
sorry
@[simp] theorem dropn_of_seq {α : Type u} (s : seq α) (n : ℕ) :
drop (of_seq s) n = of_seq (seq.drop s n) :=
sorry
theorem nth_of_seq {α : Type u} (s : seq α) (n : ℕ) :
nth (of_seq s) n = computation.return (seq.nth s n) :=
sorry
protected instance productive_of_seq {α : Type u} (s : seq α) : productive (of_seq s) :=
fun (n : ℕ) =>
eq.mpr (id (Eq._oldrec (Eq.refl (computation.terminates (nth (of_seq s) n))) (nth_of_seq s n)))
(computation.ret_terminates (seq.nth s n))
theorem to_seq_of_seq {α : Type u} (s : seq α) : to_seq (of_seq s) = s := sorry
/-- The monadic `return a` is a singleton list containing `a`. -/
def ret {α : Type u} (a : α) : wseq α := of_list [a]
@[simp] theorem map_nil {α : Type u} {β : Type v} (f : α → β) : map f nil = nil := rfl
@[simp] theorem map_cons {α : Type u} {β : Type v} (f : α → β) (a : α) (s : wseq α) :
map f (cons a s) = cons (f a) (map f s) :=
seq.map_cons (option.map f) (some a) s
@[simp] theorem map_think {α : Type u} {β : Type v} (f : α → β) (s : wseq α) :
map f (think s) = think (map f s) :=
seq.map_cons (option.map f) none s
@[simp] theorem map_id {α : Type u} (s : wseq α) : map id s = s := sorry
@[simp] theorem map_ret {α : Type u} {β : Type v} (f : α → β) (a : α) : map f (ret a) = ret (f a) :=
sorry
@[simp] theorem map_append {α : Type u} {β : Type v} (f : α → β) (s : wseq α) (t : wseq α) :
map f (append s t) = append (map f s) (map f t) :=
seq.map_append (option.map f) s t
theorem map_comp {α : Type u} {β : Type v} {γ : Type w} (f : α → β) (g : β → γ) (s : wseq α) :
map (g ∘ f) s = map g (map f s) :=
sorry
theorem mem_map {α : Type u} {β : Type v} (f : α → β) {a : α} {s : wseq α} :
a ∈ s → f a ∈ map f s :=
seq.mem_map (option.map f)
-- The converse is not true without additional assumptions
theorem exists_of_mem_join {α : Type u} {a : α} {S : wseq (wseq α)} :
a ∈ join S → ∃ (s : wseq α), s ∈ S ∧ a ∈ s :=
sorry
theorem exists_of_mem_bind {α : Type u} {β : Type v} {s : wseq α} {f : α → wseq β} {b : β}
(h : b ∈ bind s f) : ∃ (a : α), ∃ (H : a ∈ s), b ∈ f a :=
sorry
theorem destruct_map {α : Type u} {β : Type v} (f : α → β) (s : wseq α) :
destruct (map f s) = computation.map (option.map (prod.map f (map f))) (destruct s) :=
sorry
theorem lift_rel_map {α : Type u} {β : Type v} {γ : Type w} {δ : Type u_1} (R : α → β → Prop)
(S : γ → δ → Prop) {s1 : wseq α} {s2 : wseq β} {f1 : α → γ} {f2 : β → δ} (h1 : lift_rel R s1 s2)
(h2 : ∀ {a : α} {b : β}, R a b → S (f1 a) (f2 b)) : lift_rel S (map f1 s1) (map f2 s2) :=
sorry
theorem map_congr {α : Type u} {β : Type v} (f : α → β) {s : wseq α} {t : wseq α} (h : s ~ t) :
map f s ~ map f t :=
lift_rel_map Eq Eq h fun (_x _x_1 : α) => congr_arg fun (_x : α) => f _x
@[simp] def destruct_append.aux {α : Type u} (t : wseq α) :
Option (α × wseq α) → computation (Option (α × wseq α)) :=
sorry
theorem destruct_append {α : Type u} (s : wseq α) (t : wseq α) :
destruct (append s t) = computation.bind (destruct s) (destruct_append.aux t) :=
sorry
@[simp] def destruct_join.aux {α : Type u} :
Option (wseq α × wseq (wseq α)) → computation (Option (α × wseq α)) :=
sorry
theorem destruct_join {α : Type u} (S : wseq (wseq α)) :
destruct (join S) = computation.bind (destruct S) destruct_join.aux :=
sorry
theorem lift_rel_append {α : Type u} {β : Type v} (R : α → β → Prop) {s1 : wseq α} {s2 : wseq α}
{t1 : wseq β} {t2 : wseq β} (h1 : lift_rel R s1 t1) (h2 : lift_rel R s2 t2) :
lift_rel R (append s1 s2) (append t1 t2) :=
sorry
theorem lift_rel_join.lem {α : Type u} {β : Type v} (R : α → β → Prop) {S : wseq (wseq α)}
{T : wseq (wseq β)} {U : wseq α → wseq β → Prop} (ST : lift_rel (lift_rel R) S T)
(HU :
∀ (s1 : wseq α) (s2 : wseq β),
(∃ (s : wseq α),
∃ (t : wseq β),
∃ (S : wseq (wseq α)),
∃ (T : wseq (wseq β)),
s1 = append s (join S) ∧
s2 = append t (join T) ∧ lift_rel R s t ∧ lift_rel (lift_rel R) S T) →
U s1 s2)
{a : Option (α × wseq α)} (ma : a ∈ destruct (join S)) :
Exists fun {b : Option (β × wseq β)} => b ∈ destruct (join T) ∧ lift_rel_o R U a b :=
sorry
theorem lift_rel_join {α : Type u} {β : Type v} (R : α → β → Prop) {S : wseq (wseq α)}
{T : wseq (wseq β)} (h : lift_rel (lift_rel R) S T) : lift_rel R (join S) (join T) :=
sorry
theorem join_congr {α : Type u} {S : wseq (wseq α)} {T : wseq (wseq α)} (h : lift_rel equiv S T) :
join S ~ join T :=
lift_rel_join Eq h
theorem lift_rel_bind {α : Type u} {β : Type v} {γ : Type w} {δ : Type u_1} (R : α → β → Prop)
(S : γ → δ → Prop) {s1 : wseq α} {s2 : wseq β} {f1 : α → wseq γ} {f2 : β → wseq δ}
(h1 : lift_rel R s1 s2) (h2 : ∀ {a : α} {b : β}, R a b → lift_rel S (f1 a) (f2 b)) :
lift_rel S (bind s1 f1) (bind s2 f2) :=
lift_rel_join S (lift_rel_map R (lift_rel S) h1 h2)
theorem bind_congr {α : Type u} {β : Type v} {s1 : wseq α} {s2 : wseq α} {f1 : α → wseq β}
{f2 : α → wseq β} (h1 : s1 ~ s2) (h2 : ∀ (a : α), f1 a ~ f2 a) : bind s1 f1 ~ bind s2 f2 :=
lift_rel_bind Eq Eq h1
fun (a b : α) (h : a = b) =>
eq.mpr (id (Eq._oldrec (Eq.refl (lift_rel Eq (f1 a) (f2 b))) h)) (h2 b)
@[simp] theorem join_ret {α : Type u} (s : wseq α) : join (ret s) ~ s := sorry
@[simp] theorem join_map_ret {α : Type u} (s : wseq α) : join (map ret s) ~ s := sorry
@[simp] theorem join_append {α : Type u} (S : wseq (wseq α)) (T : wseq (wseq α)) :
join (append S T) ~ append (join S) (join T) :=
sorry
@[simp] theorem bind_ret {α : Type u} {β : Type v} (f : α → β) (s : wseq α) :
bind s (ret ∘ f) ~ map f s :=
id
(eq.mpr (id (Eq._oldrec (Eq.refl (join (map (ret ∘ f) s) ~ map f s)) (map_comp f ret s)))
(join_map_ret (map f s)))
@[simp] theorem ret_bind {α : Type u} {β : Type v} (a : α) (f : α → wseq β) :
bind (ret a) f ~ f a :=
sorry
@[simp] theorem map_join {α : Type u} {β : Type v} (f : α → β) (S : wseq (wseq α)) :
map f (join S) = join (map (map f) S) :=
sorry
@[simp] theorem join_join {α : Type u} (SS : wseq (wseq (wseq α))) :
join (join SS) ~ join (map join SS) :=
sorry
@[simp] theorem bind_assoc {α : Type u} {β : Type v} {γ : Type w} (s : wseq α) (f : α → wseq β)
(g : β → wseq γ) : bind (bind s f) g ~ bind s fun (x : α) => bind (f x) g :=
sorry
protected instance monad : Monad wseq :=
{ toApplicative :=
{ toFunctor := { map := map, mapConst := fun (α β : Type u_1) => map ∘ function.const β },
toPure := { pure := ret },
toSeq :=
{ seq :=
fun (α β : Type u_1) (f : wseq (α → β)) (x : wseq α) =>
bind f fun (_x : α → β) => map _x x },
toSeqLeft :=
{ seqLeft :=
fun (α β : Type u_1) (a : wseq α) (b : wseq β) =>
(fun (α β : Type u_1) (f : wseq (α → β)) (x : wseq α) =>
bind f fun (_x : α → β) => map _x x)
β α (map (function.const β) a) b },
toSeqRight :=
{ seqRight :=
fun (α β : Type u_1) (a : wseq α) (b : wseq β) =>
(fun (α β : Type u_1) (f : wseq (α → β)) (x : wseq α) =>
bind f fun (_x : α → β) => map _x x)
β β (map (function.const α id) a) b } },
toBind := { bind := bind } }
end Mathlib |
55e4247bca273e5e9689badca20817216c5a6aef | 618003631150032a5676f229d13a079ac875ff77 | /src/analysis/calculus/local_extr.lean | d98995589126ea33a7b1edd90d8c2d4b230ce719 | [
"Apache-2.0"
] | permissive | awainverse/mathlib | 939b68c8486df66cfda64d327ad3d9165248c777 | ea76bd8f3ca0a8bf0a166a06a475b10663dec44a | refs/heads/master | 1,659,592,962,036 | 1,590,987,592,000 | 1,590,987,592,000 | 268,436,019 | 1 | 0 | Apache-2.0 | 1,590,990,500,000 | 1,590,990,500,000 | null | UTF-8 | Lean | false | false | 14,853 | lean | /-
Copyright (c) 2019 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import topology.local_extr
import analysis.calculus.deriv
/-!
# Local extrema of smooth functions
## Main definitions
In a real normed space `E` we define `pos_tangent_cone_at (s : set E) (x : E)`.
This would be the same as `tangent_cone_at ℝ≥0 s x` if we had a theory of normed semifields.
This set is used in the proof of Fermat's Theorem (see below), and can be used to formalize
[Lagrange multipliers](https://en.wikipedia.org/wiki/Lagrange_multiplier) and/or
[Karush–Kuhn–Tucker conditions](https://en.wikipedia.org/wiki/Karush–Kuhn–Tucker_conditions).
## Main statements
For each theorem name listed below, we also prove similar theorems for `min`, `extr` (if applicable)`,
and `(f)deriv` instead of `has_fderiv`.
* `is_local_max_on.has_fderiv_within_at_nonpos` : `f' y ≤ 0` whenever `a` is a local maximum
of `f` on `s`, `f` has derivative `f'` at `a` within `s`, and `y` belongs to the positive tangent
cone of `s` at `a`.
* `is_local_max_on.has_fderiv_within_at_eq_zero` : In the settings of the previous theorem, if both
`y` and `-y` belong to the positive tangent cone, then `f' y = 0`.
* `is_local_max.has_fderiv_at_eq_zero` :
[Fermat's Theorem](https://en.wikipedia.org/wiki/Fermat's_theorem_(stationary_points)),
the derivative of a differentiable function at a local extremum point equals zero.
* `exists_has_deriv_at_eq_zero` :
[Rolle's Theorem](https://en.wikipedia.org/wiki/Rolle's_theorem): given a function `f` continuous
on `[a, b]` and differentiable on `(a, b)`, there exists `c ∈ (a, b)` such that `f' c = 0`.
## Implementation notes
For each mathematical fact we prove several versions of its formalization:
* for maxima and minima;
* using `has_fderiv*`/`has_deriv*` or `fderiv*`/`deriv*`.
For the `fderiv*`/`deriv*` versions we omit the differentiability condition whenever it is possible
due to the fact that `fderiv` and `deriv` are defined to be zero for non-differentiable functions.
## References
* [Fermat's Theorem](https://en.wikipedia.org/wiki/Fermat's_theorem_(stationary_points));
* [Rolle's Theorem](https://en.wikipedia.org/wiki/Rolle's_theorem);
* [Tangent cone](https://en.wikipedia.org/wiki/Tangent_cone);
## Tags
local extremum, Fermat's Theorem, Rolle's Theorem
-/
universes u v
open filter set
open_locale topological_space classical
section vector_space
variables {E : Type u} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {a : E}
{f' : E →L[ℝ] ℝ}
/-- "Positive" tangent cone to `s` at `x`; the only difference from `tangent_cone_at`
is that we require `c n → ∞` instead of `∥c n∥ → ∞`. One can think about `pos_tangent_cone_at`
as `tangent_cone_at nnreal` but we have no theory of normed semifields yet. -/
def pos_tangent_cone_at (s : set E) (x : E) : set E :=
{y : E | ∃(c : ℕ → ℝ) (d : ℕ → E), (∀ᶠ n in at_top, x + d n ∈ s) ∧
(tendsto c at_top at_top) ∧ (tendsto (λn, c n • d n) at_top (𝓝 y))}
lemma pos_tangent_cone_at_mono : monotone (λ s, pos_tangent_cone_at s a) :=
begin
rintros s t hst y ⟨c, d, hd, hc, hcd⟩,
exact ⟨c, d, mem_sets_of_superset hd $ λ h hn, hst hn, hc, hcd⟩
end
lemma mem_pos_tangent_cone_at_of_segment_subset {s : set E} {x y : E} (h : segment x y ⊆ s) :
y - x ∈ pos_tangent_cone_at s x :=
begin
let c := λn:ℕ, (2:ℝ)^n,
let d := λn:ℕ, (c n)⁻¹ • (y-x),
refine ⟨c, d, filter.univ_mem_sets' (λn, h _), _, _⟩,
show x + d n ∈ segment x y,
{ rw segment_eq_image,
refine ⟨(c n)⁻¹, ⟨_, _⟩, _⟩,
{ rw inv_nonneg, apply pow_nonneg, norm_num },
{ apply inv_le_one, apply one_le_pow_of_one_le, norm_num },
{ simp only [d, sub_smul, smul_sub, one_smul], abel } },
show tendsto c at_top at_top,
{ exact tendsto_pow_at_top_at_top_of_gt_1 one_lt_two },
show filter.tendsto (λ (n : ℕ), c n • d n) filter.at_top (𝓝 (y - x)),
{ have : (λ (n : ℕ), c n • d n) = (λn, y - x),
{ ext n,
simp only [d, smul_smul],
rw [mul_inv_cancel, one_smul],
exact pow_ne_zero _ (by norm_num) },
rw this,
apply tendsto_const_nhds }
end
lemma pos_tangent_cone_at_univ : pos_tangent_cone_at univ a = univ :=
eq_univ_iff_forall.2
begin
assume x,
rw [← add_sub_cancel x a],
exact mem_pos_tangent_cone_at_of_segment_subset (subset_univ _)
end
/-- If `f` has a local max on `s` at `a`, `f'` is the derivative of `f` at `a` within `s`, and
`y` belongs to the positive tangent cone of `s` at `a`, then `f' y ≤ 0`. -/
lemma is_local_max_on.has_fderiv_within_at_nonpos {s : set E} (h : is_local_max_on f s a)
(hf : has_fderiv_within_at f f' s a) {y} (hy : y ∈ pos_tangent_cone_at s a) :
f' y ≤ 0 :=
begin
rcases hy with ⟨c, d, hd, hc, hcd⟩,
have hc' : tendsto (λ n, ∥c n∥) at_top at_top,
from tendsto_at_top_mono _ (λ n, le_abs_self _) hc,
refine le_of_tendsto at_top_ne_bot (hf.lim at_top hd hc' hcd) _,
replace hd : tendsto (λ n, a + d n) at_top (nhds_within (a + 0) s),
from tendsto_inf.2 ⟨tendsto_const_nhds.add (tangent_cone_at.lim_zero _ hc' hcd),
by rwa tendsto_principal⟩,
rw [add_zero] at hd,
replace h : ∀ᶠ n in at_top, f (a + d n) ≤ f a, from mem_map.1 (hd h),
replace hc : ∀ᶠ n in at_top, 0 ≤ c n, from mem_map.1 (hc (mem_at_top (0:ℝ))),
filter_upwards [h, hc],
simp only [mem_set_of_eq, smul_eq_mul, mem_preimage, subset_def],
assume n hnf hn,
exact mul_nonpos_of_nonneg_of_nonpos hn (sub_nonpos.2 hnf)
end
/-- If `f` has a local max on `s` at `a` and `y` belongs to the positive tangent cone
of `s` at `a`, then `f' y ≤ 0`. -/
lemma is_local_max_on.fderiv_within_nonpos {s : set E} (h : is_local_max_on f s a)
{y} (hy : y ∈ pos_tangent_cone_at s a) :
(fderiv_within ℝ f s a : E → ℝ) y ≤ 0 :=
if hf : differentiable_within_at ℝ f s a
then h.has_fderiv_within_at_nonpos hf.has_fderiv_within_at hy
else by { rw fderiv_within_zero_of_not_differentiable_within_at hf, refl }
/-- If `f` has a local max on `s` at `a`, `f'` is a derivative of `f` at `a` within `s`, and
both `y` and `-y` belong to the positive tangent cone of `s` at `a`, then `f' y ≤ 0`. -/
lemma is_local_max_on.has_fderiv_within_at_eq_zero {s : set E} (h : is_local_max_on f s a)
(hf : has_fderiv_within_at f f' s a) {y} (hy : y ∈ pos_tangent_cone_at s a)
(hy' : -y ∈ pos_tangent_cone_at s a) :
f' y = 0 :=
le_antisymm (h.has_fderiv_within_at_nonpos hf hy) $
by simpa using h.has_fderiv_within_at_nonpos hf hy'
/-- If `f` has a local max on `s` at `a` and both `y` and `-y` belong to the positive tangent cone
of `s` at `a`, then `f' y = 0`. -/
lemma is_local_max_on.fderiv_within_eq_zero {s : set E} (h : is_local_max_on f s a)
{y} (hy : y ∈ pos_tangent_cone_at s a) (hy' : -y ∈ pos_tangent_cone_at s a) :
(fderiv_within ℝ f s a : E → ℝ) y = 0 :=
if hf : differentiable_within_at ℝ f s a
then h.has_fderiv_within_at_eq_zero hf.has_fderiv_within_at hy hy'
else by { rw fderiv_within_zero_of_not_differentiable_within_at hf, refl }
/-- If `f` has a local min on `s` at `a`, `f'` is the derivative of `f` at `a` within `s`, and
`y` belongs to the positive tangent cone of `s` at `a`, then `0 ≤ f' y`. -/
lemma is_local_min_on.has_fderiv_within_at_nonneg {s : set E} (h : is_local_min_on f s a)
(hf : has_fderiv_within_at f f' s a) {y} (hy : y ∈ pos_tangent_cone_at s a) :
0 ≤ f' y :=
by simpa using h.neg.has_fderiv_within_at_nonpos hf.neg hy
/-- If `f` has a local min on `s` at `a` and `y` belongs to the positive tangent cone
of `s` at `a`, then `0 ≤ f' y`. -/
lemma is_local_min_on.fderiv_within_nonneg {s : set E} (h : is_local_min_on f s a)
{y} (hy : y ∈ pos_tangent_cone_at s a) :
(0:ℝ) ≤ (fderiv_within ℝ f s a : E → ℝ) y :=
if hf : differentiable_within_at ℝ f s a
then h.has_fderiv_within_at_nonneg hf.has_fderiv_within_at hy
else by { rw [fderiv_within_zero_of_not_differentiable_within_at hf], refl }
/-- If `f` has a local max on `s` at `a`, `f'` is a derivative of `f` at `a` within `s`, and
both `y` and `-y` belong to the positive tangent cone of `s` at `a`, then `f' y ≤ 0`. -/
lemma is_local_min_on.has_fderiv_within_at_eq_zero {s : set E} (h : is_local_min_on f s a)
(hf : has_fderiv_within_at f f' s a) {y} (hy : y ∈ pos_tangent_cone_at s a)
(hy' : -y ∈ pos_tangent_cone_at s a) :
f' y = 0 :=
by simpa using h.neg.has_fderiv_within_at_eq_zero hf.neg hy hy'
/-- If `f` has a local min on `s` at `a` and both `y` and `-y` belong to the positive tangent cone
of `s` at `a`, then `f' y = 0`. -/
lemma is_local_min_on.fderiv_within_eq_zero {s : set E} (h : is_local_min_on f s a)
{y} (hy : y ∈ pos_tangent_cone_at s a) (hy' : -y ∈ pos_tangent_cone_at s a) :
(fderiv_within ℝ f s a : E → ℝ) y = 0 :=
if hf : differentiable_within_at ℝ f s a
then h.has_fderiv_within_at_eq_zero hf.has_fderiv_within_at hy hy'
else by { rw fderiv_within_zero_of_not_differentiable_within_at hf, refl }
/-- Fermat's Theorem: the derivative of a function at a local minimum equals zero. -/
lemma is_local_min.has_fderiv_at_eq_zero (h : is_local_min f a) (hf : has_fderiv_at f f' a) :
f' = 0 :=
begin
ext y,
apply (h.on univ).has_fderiv_within_at_eq_zero hf.has_fderiv_within_at;
rw pos_tangent_cone_at_univ; apply mem_univ
end
/-- Fermat's Theorem: the derivative of a function at a local minimum equals zero. -/
lemma is_local_min.fderiv_eq_zero (h : is_local_min f a) : fderiv ℝ f a = 0 :=
if hf : differentiable_at ℝ f a then h.has_fderiv_at_eq_zero hf.has_fderiv_at
else fderiv_zero_of_not_differentiable_at hf
/-- Fermat's Theorem: the derivative of a function at a local maximum equals zero. -/
lemma is_local_max.has_fderiv_at_eq_zero (h : is_local_max f a) (hf : has_fderiv_at f f' a) :
f' = 0 :=
neg_eq_zero.1 $ h.neg.has_fderiv_at_eq_zero hf.neg
/-- Fermat's Theorem: the derivative of a function at a local maximum equals zero. -/
lemma is_local_max.fderiv_eq_zero (h : is_local_max f a) : fderiv ℝ f a = 0 :=
if hf : differentiable_at ℝ f a then h.has_fderiv_at_eq_zero hf.has_fderiv_at
else fderiv_zero_of_not_differentiable_at hf
/-- Fermat's Theorem: the derivative of a function at a local extremum equals zero. -/
lemma is_local_extr.has_fderiv_at_eq_zero (h : is_local_extr f a) :
has_fderiv_at f f' a → f' = 0 :=
h.elim is_local_min.has_fderiv_at_eq_zero is_local_max.has_fderiv_at_eq_zero
/-- Fermat's Theorem: the derivative of a function at a local extremum equals zero. -/
lemma is_local_extr.fderiv_eq_zero (h : is_local_extr f a) : fderiv ℝ f a = 0 :=
h.elim is_local_min.fderiv_eq_zero is_local_max.fderiv_eq_zero
end vector_space
section real
variables {f : ℝ → ℝ} {f' : ℝ} {a b : ℝ}
/-- Fermat's Theorem: the derivative of a function at a local minimum equals zero. -/
lemma is_local_min.has_deriv_at_eq_zero (h : is_local_min f a) (hf : has_deriv_at f f' a) :
f' = 0 :=
by simpa using continuous_linear_map.ext_iff.1
(h.has_fderiv_at_eq_zero (has_deriv_at_iff_has_fderiv_at.1 hf)) 1
/-- Fermat's Theorem: the derivative of a function at a local minimum equals zero. -/
lemma is_local_min.deriv_eq_zero (h : is_local_min f a) : deriv f a = 0 :=
if hf : differentiable_at ℝ f a then h.has_deriv_at_eq_zero hf.has_deriv_at
else deriv_zero_of_not_differentiable_at hf
/-- Fermat's Theorem: the derivative of a function at a local maximum equals zero. -/
lemma is_local_max.has_deriv_at_eq_zero (h : is_local_max f a) (hf : has_deriv_at f f' a) :
f' = 0 :=
neg_eq_zero.1 $ h.neg.has_deriv_at_eq_zero hf.neg
/-- Fermat's Theorem: the derivative of a function at a local maximum equals zero. -/
lemma is_local_max.deriv_eq_zero (h : is_local_max f a) : deriv f a = 0 :=
if hf : differentiable_at ℝ f a then h.has_deriv_at_eq_zero hf.has_deriv_at
else deriv_zero_of_not_differentiable_at hf
/-- Fermat's Theorem: the derivative of a function at a local extremum equals zero. -/
lemma is_local_extr.has_deriv_at_eq_zero (h : is_local_extr f a) :
has_deriv_at f f' a → f' = 0 :=
h.elim is_local_min.has_deriv_at_eq_zero is_local_max.has_deriv_at_eq_zero
/-- Fermat's Theorem: the derivative of a function at a local extremum equals zero. -/
lemma is_local_extr.deriv_eq_zero (h : is_local_extr f a) : deriv f a = 0 :=
h.elim is_local_min.deriv_eq_zero is_local_max.deriv_eq_zero
end real
section Rolle
variables (f f' : ℝ → ℝ) {a b : ℝ} (hab : a < b) (hfc : continuous_on f (Icc a b)) (hfI : f a = f b)
include hab hfc hfI
/-- A continuous function on a closed interval with `f a = f b` takes either its maximum
or its minimum value at a point in the interior of the interval. -/
lemma exists_Ioo_extr_on_Icc : ∃ c ∈ Ioo a b, is_extr_on f (Icc a b) c :=
begin
have ne : (Icc a b).nonempty, from nonempty_Icc.2 (le_of_lt hab),
-- Consider absolute min and max points
obtain ⟨c, cmem, cle⟩ : ∃ c ∈ Icc a b, ∀ x ∈ Icc a b, f c ≤ f x,
from compact_Icc.exists_forall_le ne hfc,
obtain ⟨C, Cmem, Cge⟩ : ∃ C ∈ Icc a b, ∀ x ∈ Icc a b, f x ≤ f C,
from compact_Icc.exists_forall_ge ne hfc,
by_cases hc : f c = f a,
{ by_cases hC : f C = f a,
{ have : ∀ x ∈ Icc a b, f x = f a,
from λ x hx, le_antisymm (hC ▸ Cge x hx) (hc ▸ cle x hx),
-- `f` is a constant, so we can take any point in `Ioo a b`
rcases dense hab with ⟨c', hc'⟩,
refine ⟨c', hc', or.inl _⟩,
assume x hx,
rw [mem_set_of_eq, this x hx, ← hC],
exact Cge c' ⟨le_of_lt hc'.1, le_of_lt hc'.2⟩ },
{ refine ⟨C, ⟨lt_of_le_of_ne Cmem.1 $ mt _ hC, lt_of_le_of_ne Cmem.2 $ mt _ hC⟩, or.inr Cge⟩,
exacts [λ h, by rw h, λ h, by rw [h, hfI]] } },
{ refine ⟨c, ⟨lt_of_le_of_ne cmem.1 $ mt _ hc, lt_of_le_of_ne cmem.2 $ mt _ hc⟩, or.inl cle⟩,
exacts [λ h, by rw h, λ h, by rw [h, hfI]] }
end
/-- A continuous function on a closed interval with `f a = f b` has a local extremum at some
point of the corresponding open interval. -/
lemma exists_local_extr_Ioo : ∃ c ∈ Ioo a b, is_local_extr f c :=
let ⟨c, cmem, hc⟩ := exists_Ioo_extr_on_Icc f hab hfc hfI
in ⟨c, cmem, hc.is_local_extr $ mem_nhds_sets_iff.2 ⟨Ioo a b, Ioo_subset_Icc_self, is_open_Ioo, cmem⟩⟩
/-- Rolle's Theorem `has_deriv_at` version -/
lemma exists_has_deriv_at_eq_zero (hff' : ∀ x ∈ Ioo a b, has_deriv_at f (f' x) x) :
∃ c ∈ Ioo a b, f' c = 0 :=
let ⟨c, cmem, hc⟩ := exists_local_extr_Ioo f hab hfc hfI in
⟨c, cmem, hc.has_deriv_at_eq_zero $ hff' c cmem⟩
/-- Rolle's Theorem `deriv` version -/
lemma exists_deriv_eq_zero : ∃ c ∈ Ioo a b, deriv f c = 0 :=
let ⟨c, cmem, hc⟩ := exists_local_extr_Ioo f hab hfc hfI in
⟨c, cmem, hc.deriv_eq_zero⟩
end Rolle
|
9f9b13f36102a83a6858db25ed2e2e66a0172ce0 | 592ee40978ac7604005a4e0d35bbc4b467389241 | /Library/generated/mathscheme-lean/AntiAbsorbent.lean | e8d54f61fd20dc6f6852181603e1ebc95756ad64 | [] | no_license | ysharoda/Deriving-Definitions | 3e149e6641fae440badd35ac110a0bd705a49ad2 | dfecb27572022de3d4aa702cae8db19957523a59 | refs/heads/master | 1,679,127,857,700 | 1,615,939,007,000 | 1,615,939,007,000 | 229,785,731 | 4 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,943 | lean | import init.data.nat.basic
import init.data.fin.basic
import data.vector
import .Prelude
open Staged
open nat
open fin
open vector
section AntiAbsorbent
structure AntiAbsorbent (A : Type) : Type :=
(op : (A → (A → A)))
(antiAbsorbent : (∀ {x y : A} , (op x (op x y)) = y))
open AntiAbsorbent
structure Sig (AS : Type) : Type :=
(opS : (AS → (AS → AS)))
structure Product (A : Type) : Type :=
(opP : ((Prod A A) → ((Prod A A) → (Prod A A))))
(antiAbsorbentP : (∀ {xP yP : (Prod A A)} , (opP xP (opP xP yP)) = yP))
structure Hom {A1 : Type} {A2 : Type} (An1 : (AntiAbsorbent A1)) (An2 : (AntiAbsorbent A2)) : Type :=
(hom : (A1 → A2))
(pres_op : (∀ {x1 x2 : A1} , (hom ((op An1) x1 x2)) = ((op An2) (hom x1) (hom x2))))
structure RelInterp {A1 : Type} {A2 : Type} (An1 : (AntiAbsorbent A1)) (An2 : (AntiAbsorbent A2)) : Type 1 :=
(interp : (A1 → (A2 → Type)))
(interp_op : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((op An1) x1 x2) ((op An2) y1 y2))))))
inductive AntiAbsorbentTerm : Type
| opL : (AntiAbsorbentTerm → (AntiAbsorbentTerm → AntiAbsorbentTerm))
open AntiAbsorbentTerm
inductive ClAntiAbsorbentTerm (A : Type) : Type
| sing : (A → ClAntiAbsorbentTerm)
| opCl : (ClAntiAbsorbentTerm → (ClAntiAbsorbentTerm → ClAntiAbsorbentTerm))
open ClAntiAbsorbentTerm
inductive OpAntiAbsorbentTerm (n : ℕ) : Type
| v : ((fin n) → OpAntiAbsorbentTerm)
| opOL : (OpAntiAbsorbentTerm → (OpAntiAbsorbentTerm → OpAntiAbsorbentTerm))
open OpAntiAbsorbentTerm
inductive OpAntiAbsorbentTerm2 (n : ℕ) (A : Type) : Type
| v2 : ((fin n) → OpAntiAbsorbentTerm2)
| sing2 : (A → OpAntiAbsorbentTerm2)
| opOL2 : (OpAntiAbsorbentTerm2 → (OpAntiAbsorbentTerm2 → OpAntiAbsorbentTerm2))
open OpAntiAbsorbentTerm2
def simplifyCl {A : Type} : ((ClAntiAbsorbentTerm A) → (ClAntiAbsorbentTerm A))
| (opCl x1 x2) := (opCl (simplifyCl x1) (simplifyCl x2))
| (sing x1) := (sing x1)
def simplifyOpB {n : ℕ} : ((OpAntiAbsorbentTerm n) → (OpAntiAbsorbentTerm n))
| (opOL x1 x2) := (opOL (simplifyOpB x1) (simplifyOpB x2))
| (v x1) := (v x1)
def simplifyOp {n : ℕ} {A : Type} : ((OpAntiAbsorbentTerm2 n A) → (OpAntiAbsorbentTerm2 n A))
| (opOL2 x1 x2) := (opOL2 (simplifyOp x1) (simplifyOp x2))
| (v2 x1) := (v2 x1)
| (sing2 x1) := (sing2 x1)
def evalB {A : Type} : ((AntiAbsorbent A) → (AntiAbsorbentTerm → A))
| An (opL x1 x2) := ((op An) (evalB An x1) (evalB An x2))
def evalCl {A : Type} : ((AntiAbsorbent A) → ((ClAntiAbsorbentTerm A) → A))
| An (sing x1) := x1
| An (opCl x1 x2) := ((op An) (evalCl An x1) (evalCl An x2))
def evalOpB {A : Type} {n : ℕ} : ((AntiAbsorbent A) → ((vector A n) → ((OpAntiAbsorbentTerm n) → A)))
| An vars (v x1) := (nth vars x1)
| An vars (opOL x1 x2) := ((op An) (evalOpB An vars x1) (evalOpB An vars x2))
def evalOp {A : Type} {n : ℕ} : ((AntiAbsorbent A) → ((vector A n) → ((OpAntiAbsorbentTerm2 n A) → A)))
| An vars (v2 x1) := (nth vars x1)
| An vars (sing2 x1) := x1
| An vars (opOL2 x1 x2) := ((op An) (evalOp An vars x1) (evalOp An vars x2))
def inductionB {P : (AntiAbsorbentTerm → Type)} : ((∀ (x1 x2 : AntiAbsorbentTerm) , ((P x1) → ((P x2) → (P (opL x1 x2))))) → (∀ (x : AntiAbsorbentTerm) , (P x)))
| popl (opL x1 x2) := (popl _ _ (inductionB popl x1) (inductionB popl x2))
def inductionCl {A : Type} {P : ((ClAntiAbsorbentTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((∀ (x1 x2 : (ClAntiAbsorbentTerm A)) , ((P x1) → ((P x2) → (P (opCl x1 x2))))) → (∀ (x : (ClAntiAbsorbentTerm A)) , (P x))))
| psing popcl (sing x1) := (psing x1)
| psing popcl (opCl x1 x2) := (popcl _ _ (inductionCl psing popcl x1) (inductionCl psing popcl x2))
def inductionOpB {n : ℕ} {P : ((OpAntiAbsorbentTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((∀ (x1 x2 : (OpAntiAbsorbentTerm n)) , ((P x1) → ((P x2) → (P (opOL x1 x2))))) → (∀ (x : (OpAntiAbsorbentTerm n)) , (P x))))
| pv popol (v x1) := (pv x1)
| pv popol (opOL x1 x2) := (popol _ _ (inductionOpB pv popol x1) (inductionOpB pv popol x2))
def inductionOp {n : ℕ} {A : Type} {P : ((OpAntiAbsorbentTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((∀ (x1 x2 : (OpAntiAbsorbentTerm2 n A)) , ((P x1) → ((P x2) → (P (opOL2 x1 x2))))) → (∀ (x : (OpAntiAbsorbentTerm2 n A)) , (P x)))))
| pv2 psing2 popol2 (v2 x1) := (pv2 x1)
| pv2 psing2 popol2 (sing2 x1) := (psing2 x1)
| pv2 psing2 popol2 (opOL2 x1 x2) := (popol2 _ _ (inductionOp pv2 psing2 popol2 x1) (inductionOp pv2 psing2 popol2 x2))
def stageB : (AntiAbsorbentTerm → (Staged AntiAbsorbentTerm))
| (opL x1 x2) := (stage2 opL (codeLift2 opL) (stageB x1) (stageB x2))
def stageCl {A : Type} : ((ClAntiAbsorbentTerm A) → (Staged (ClAntiAbsorbentTerm A)))
| (sing x1) := (Now (sing x1))
| (opCl x1 x2) := (stage2 opCl (codeLift2 opCl) (stageCl x1) (stageCl x2))
def stageOpB {n : ℕ} : ((OpAntiAbsorbentTerm n) → (Staged (OpAntiAbsorbentTerm n)))
| (v x1) := (const (code (v x1)))
| (opOL x1 x2) := (stage2 opOL (codeLift2 opOL) (stageOpB x1) (stageOpB x2))
def stageOp {n : ℕ} {A : Type} : ((OpAntiAbsorbentTerm2 n A) → (Staged (OpAntiAbsorbentTerm2 n A)))
| (sing2 x1) := (Now (sing2 x1))
| (v2 x1) := (const (code (v2 x1)))
| (opOL2 x1 x2) := (stage2 opOL2 (codeLift2 opOL2) (stageOp x1) (stageOp x2))
structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type :=
(opT : ((Repr A) → ((Repr A) → (Repr A))))
end AntiAbsorbent |
5d1ac35a382a6878621b57403888530a98718e98 | f3849be5d845a1cb97680f0bbbe03b85518312f0 | /library/init/data/string/lemmas.lean | 5cac68a0269d86cdbbb20fb8e230cd24edc02565 | [
"Apache-2.0"
] | permissive | bjoeris/lean | 0ed95125d762b17bfcb54dad1f9721f953f92eeb | 4e496b78d5e73545fa4f9a807155113d8e6b0561 | refs/heads/master | 1,611,251,218,281 | 1,495,337,658,000 | 1,495,337,658,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 809 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
prelude
import init.meta
namespace string
lemma empty_ne_str (c : char) (s : string) : empty ≠ str c s :=
begin intro h, contradiction end
lemma str_ne_empty (c : char) (s : string) : str c s ≠ empty :=
begin intro h, contradiction end
lemma str_ne_str_left {c₁ c₂ : char} (s₁ s₂ : string) : c₁ ≠ c₂ → str c₁ s₁ ≠ str c₂ s₂ :=
begin intros h₁ h₂, unfold str at h₂, injection h₂, contradiction end
lemma str_ne_str_right (c₁ c₂ : char) {s₁ s₂ : string} : s₁ ≠ s₂ → str c₁ s₁ ≠ str c₂ s₂ :=
begin intros h₁ h₂, unfold str at h₂, injection h₂, contradiction end
end string
|
87de7a7af7718c0f8be71e98a08f5cf0891a96f9 | 968e2f50b755d3048175f176376eff7139e9df70 | /examples/prop_logic_lean_summary/unnamed_249.lean | 71911ffc89da41a6e89250949d6530d18ab41df1 | [] | no_license | gihanmarasingha/mth1001_sphinx | 190a003269ba5e54717b448302a27ca26e31d491 | 05126586cbf5786e521be1ea2ef5b4ba3c44e74a | refs/heads/master | 1,672,913,933,677 | 1,604,516,583,000 | 1,604,516,583,000 | 309,245,750 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 109 | lean | variables p q : Prop
-- BEGIN
example (h₁ : p → q) (h₂ : p) : q :=
begin
exact h₁ h₂,
end
-- END |
884153f20b4b8d1ad6b97abdc61d4c7ddf71d0dd | c777c32c8e484e195053731103c5e52af26a25d1 | /src/number_theory/cyclotomic/primitive_roots.lean | 802553dac26679dfe39498f22c4fbd2451133e38 | [
"Apache-2.0"
] | permissive | kbuzzard/mathlib | 2ff9e85dfe2a46f4b291927f983afec17e946eb8 | 58537299e922f9c77df76cb613910914a479c1f7 | refs/heads/master | 1,685,313,702,744 | 1,683,974,212,000 | 1,683,974,212,000 | 128,185,277 | 1 | 0 | null | 1,522,920,600,000 | 1,522,920,600,000 | null | UTF-8 | Lean | false | false | 25,488 | lean | /-
Copyright (c) 2022 Riccardo Brasca. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Alex Best, Riccardo Brasca, Eric Rodriguez
-/
import data.pnat.prime
import algebra.is_prime_pow
import number_theory.cyclotomic.basic
import ring_theory.adjoin.power_basis
import ring_theory.polynomial.cyclotomic.eval
import ring_theory.norm
/-!
# Primitive roots in cyclotomic fields
If `is_cyclotomic_extension {n} A B`, we define an element `zeta n A B : B` that is (under certain
assumptions) a primitive `n`-root of unity in `B` and we study its properties. We also prove related
theorems under the more general assumption of just being a primitive root, for reasons described
in the implementation details section.
## Main definitions
* `is_cyclotomic_extension.zeta n A B`: if `is_cyclotomic_extension {n} A B`, than `zeta n A B`
is an element of `B` that plays the role of a primitive `n`-th root of unity.
* `is_primitive_root.power_basis`: if `K` and `L` are fields such that
`is_cyclotomic_extension {n} K L`, then `is_primitive_root.power_basis`
gives a K-power basis for L given a primitive root `ζ`.
* `is_primitive_root.embeddings_equiv_primitive_roots`: the equivalence between `L →ₐ[K] A`
and `primitive_roots n A` given by the choice of `ζ`.
## Main results
* `is_cyclotomic_extension.zeta_spec`: `zeta n A B` is a primitive `n`-th root of unity.
* `is_cyclotomic_extension.finrank`: if `irreducible (cyclotomic n K)` (in particular for
`K = ℚ`), then the `finrank` of a cyclotomic extension is `n.totient`.
* `is_primitive_root.norm_eq_one`: if `irreducible (cyclotomic n K)` (in particular for `K = ℚ`),
the norm of a primitive root is `1` if `n ≠ 2`.
* `is_primitive_root.sub_one_norm_eq_eval_cyclotomic`: if `irreducible (cyclotomic n K)`
(in particular for `K = ℚ`), then the norm of `ζ - 1` is `eval 1 (cyclotomic n ℤ)`, for a
primitive root ζ. We also prove the analogous of this result for `zeta`.
* `is_primitive_root.pow_sub_one_norm_prime_pow_ne_two` : if
`irreducible (cyclotomic (p ^ (k + 1)) K)` (in particular for `K = ℚ`) and `p` is a prime,
then the norm of `ζ ^ (p ^ s) - 1` is `p ^ (p ^ s)` `p ^ (k - s + 1) ≠ 2`. See the following
lemmas for similar results. We also prove the analogous of this result for `zeta`.
* `is_primitive_root.sub_one_norm_prime_ne_two` : if `irreducible (cyclotomic (p ^ (k + 1)) K)`
(in particular for `K = ℚ`) and `p` is an odd prime, then the norm of `ζ - 1` is `p`. We also
prove the analogous of this result for `zeta`.
* `is_primitive_root.embeddings_equiv_primitive_roots`: the equivalence between `L →ₐ[K] A`
and `primitive_roots n A` given by the choice of `ζ`.
## Implementation details
`zeta n A B` is defined as any primitive root of unity in `B`, that exists by definition. It is not
true in general that it is a root of `cyclotomic n B`, but this holds if `is_domain B` and
`ne_zero (↑n : B)`.
`zeta n A B` is defined using `exists.some`, which means we cannot control it.
For example, in normal mathematics, we can demand that `(zeta p ℤ ℤ[ζₚ] : ℚ(ζₚ))` is equal to
`zeta p ℚ ℚ(ζₚ)`, as we are just choosing "an arbitrary primitive root" and we can internally
specify that our choices agree. This is not the case here, and it is indeed impossible to prove that
these two are equal. Therefore, whenever possible, we prove our results for any primitive root,
and only at the "final step", when we need to provide an "explicit" primitive root, we use `zeta`.
-/
open polynomial algebra finset finite_dimensional is_cyclotomic_extension nat pnat set
universes u v w z
variables {p n : ℕ+} (A : Type w) (B : Type z) (K : Type u) {L : Type v} (C : Type w)
variables [comm_ring A] [comm_ring B] [algebra A B] [is_cyclotomic_extension {n} A B]
section zeta
namespace is_cyclotomic_extension
variables (n)
/-- If `B` is a `n`-th cyclotomic extension of `A`, then `zeta n A B` is a primitive root of
unity in `B`. -/
noncomputable def zeta : B :=
(exists_prim_root A $ set.mem_singleton n : ∃ r : B, is_primitive_root r n).some
/-- `zeta n A B` is a primitive `n`-th root of unity. -/
@[simp] lemma zeta_spec : is_primitive_root (zeta n A B) n :=
classical.some_spec (exists_prim_root A (set.mem_singleton n) : ∃ r : B, is_primitive_root r n)
lemma aeval_zeta [is_domain B] [ne_zero ((n : ℕ) : B)] :
aeval (zeta n A B) (cyclotomic n A) = 0 :=
begin
rw [aeval_def, ← eval_map, ← is_root.def, map_cyclotomic, is_root_cyclotomic_iff],
exact zeta_spec n A B
end
lemma zeta_is_root [is_domain B] [ne_zero ((n : ℕ) : B)] :
is_root (cyclotomic n B) (zeta n A B) :=
by { convert aeval_zeta n A B, rw [is_root.def, aeval_def, eval₂_eq_eval_map, map_cyclotomic] }
lemma zeta_pow : (zeta n A B) ^ (n : ℕ) = 1 :=
(zeta_spec n A B).pow_eq_one
end is_cyclotomic_extension
end zeta
section no_order
variables [field K] [comm_ring L] [is_domain L] [algebra K L] [is_cyclotomic_extension {n} K L]
{ζ : L} (hζ : is_primitive_root ζ n)
namespace is_primitive_root
variable {C}
/-- The `power_basis` given by a primitive root `η`. -/
@[simps] protected noncomputable def power_basis : power_basis K L :=
power_basis.map (algebra.adjoin.power_basis $ integral {n} K L ζ) $
(subalgebra.equiv_of_eq _ _ (is_cyclotomic_extension.adjoin_primitive_root_eq_top hζ)).trans
subalgebra.top_equiv
lemma power_basis_gen_mem_adjoin_zeta_sub_one :
(hζ.power_basis K).gen ∈ adjoin K ({ζ - 1} : set L) :=
begin
rw [power_basis_gen, adjoin_singleton_eq_range_aeval, alg_hom.mem_range],
exact ⟨X + 1, by simp⟩
end
/-- The `power_basis` given by `η - 1`. -/
@[simps] noncomputable def sub_one_power_basis : power_basis K L :=
(hζ.power_basis K).of_gen_mem_adjoin
(is_integral_sub (is_cyclotomic_extension.integral {n} K L ζ) is_integral_one)
(hζ.power_basis_gen_mem_adjoin_zeta_sub_one _)
variables {K} (C)
-- We are not using @[simps] to avoid a timeout.
/-- The equivalence between `L →ₐ[K] C` and `primitive_roots n C` given by a primitive root `ζ`. -/
noncomputable def embeddings_equiv_primitive_roots (C : Type*) [comm_ring C] [is_domain C]
[algebra K C] (hirr : irreducible (cyclotomic n K)) : (L →ₐ[K] C) ≃ primitive_roots n C :=
((hζ.power_basis K).lift_equiv).trans
{ to_fun := λ x,
begin
haveI := is_cyclotomic_extension.ne_zero' n K L,
haveI hn := ne_zero.of_no_zero_smul_divisors K C n,
refine ⟨x.1, _⟩,
cases x,
rwa [mem_primitive_roots n.pos, ←is_root_cyclotomic_iff, is_root.def,
←map_cyclotomic _ (algebra_map K C), hζ.minpoly_eq_cyclotomic_of_irreducible hirr,
←eval₂_eq_eval_map, ←aeval_def]
end,
inv_fun := λ x,
begin
haveI := is_cyclotomic_extension.ne_zero' n K L,
haveI hn := ne_zero.of_no_zero_smul_divisors K C n,
refine ⟨x.1, _⟩,
cases x,
rwa [aeval_def, eval₂_eq_eval_map, hζ.power_basis_gen K,
←hζ.minpoly_eq_cyclotomic_of_irreducible hirr, map_cyclotomic, ←is_root.def,
is_root_cyclotomic_iff, ← mem_primitive_roots n.pos]
end,
left_inv := λ x, subtype.ext rfl,
right_inv := λ x, subtype.ext rfl }
@[simp]
lemma embeddings_equiv_primitive_roots_apply_coe (C : Type*) [comm_ring C] [is_domain C]
[algebra K C] (hirr : irreducible (cyclotomic n K)) (φ : L →ₐ[K] C) :
(hζ.embeddings_equiv_primitive_roots C hirr φ : C) = φ ζ := rfl
end is_primitive_root
namespace is_cyclotomic_extension
variables {K} (L)
/-- If `irreducible (cyclotomic n K)` (in particular for `K = ℚ`), then the `finrank` of a
cyclotomic extension is `n.totient`. -/
lemma finrank (hirr : irreducible (cyclotomic n K)) :
finrank K L = (n : ℕ).totient :=
begin
haveI := is_cyclotomic_extension.ne_zero' n K L,
rw [((zeta_spec n K L).power_basis K).finrank, is_primitive_root.power_basis_dim,
←(zeta_spec n K L).minpoly_eq_cyclotomic_of_irreducible hirr, nat_degree_cyclotomic]
end
end is_cyclotomic_extension
end no_order
section norm
namespace is_primitive_root
section comm_ring
variables [comm_ring L] {ζ : L} (hζ : is_primitive_root ζ n)
variables {K} [field K] [algebra K L]
/-- This mathematically trivial result is complementary to `norm_eq_one` below. -/
lemma norm_eq_neg_one_pow (hζ : is_primitive_root ζ 2) [is_domain L] :
norm K ζ = (-1) ^ finrank K L :=
by rw [hζ.eq_neg_one_of_two_right, show -1 = algebra_map K L (-1), by simp,
algebra.norm_algebra_map]
include hζ
/-- If `irreducible (cyclotomic n K)` (in particular for `K = ℚ`), the norm of a primitive root is
`1` if `n ≠ 2`. -/
lemma norm_eq_one [is_domain L] [is_cyclotomic_extension {n} K L] (hn : n ≠ 2)
(hirr : irreducible (cyclotomic n K)) : norm K ζ = 1 :=
begin
haveI := is_cyclotomic_extension.ne_zero' n K L,
by_cases h1 : n = 1,
{ rw [h1, one_coe, one_right_iff] at hζ,
rw [hζ, show 1 = algebra_map K L 1, by simp, algebra.norm_algebra_map, one_pow] },
{ replace h1 : 2 ≤ n,
{ by_contra' h,
exact h1 (pnat.eq_one_of_lt_two h) },
rw [← hζ.power_basis_gen K, power_basis.norm_gen_eq_coeff_zero_minpoly, hζ.power_basis_gen K,
← hζ.minpoly_eq_cyclotomic_of_irreducible hirr, cyclotomic_coeff_zero _ h1, mul_one,
hζ.power_basis_dim K, ← hζ.minpoly_eq_cyclotomic_of_irreducible hirr, nat_degree_cyclotomic],
exact (totient_even $ h1.lt_of_ne hn.symm).neg_one_pow }
end
/-- If `K` is linearly ordered, the norm of a primitive root is `1` if `n` is odd. -/
lemma norm_eq_one_of_linearly_ordered {K : Type*} [linear_ordered_field K] [algebra K L]
(hodd : odd (n : ℕ)) : norm K ζ = 1 :=
begin
have hz := congr_arg (norm K) ((is_primitive_root.iff_def _ n).1 hζ).1,
rw [←(algebra_map K L).map_one , algebra.norm_algebra_map, one_pow, map_pow, ←one_pow ↑n] at hz,
exact strict_mono.injective hodd.strict_mono_pow hz
end
lemma norm_of_cyclotomic_irreducible [is_domain L] [is_cyclotomic_extension {n} K L]
(hirr : irreducible (cyclotomic n K)) : norm K ζ = ite (n = 2) (-1) 1 :=
begin
split_ifs with hn,
{ unfreezingI {subst hn},
convert norm_eq_neg_one_pow hζ,
erw [is_cyclotomic_extension.finrank _ hirr, totient_two, pow_one],
all_goals { apply_instance } },
{ exact hζ.norm_eq_one hn hirr }
end
end comm_ring
section field
variables [field L] {ζ : L} (hζ : is_primitive_root ζ n)
variables {K} [field K] [algebra K L]
include hζ
/-- If `irreducible (cyclotomic n K)` (in particular for `K = ℚ`), then the norm of
`ζ - 1` is `eval 1 (cyclotomic n ℤ)`. -/
lemma sub_one_norm_eq_eval_cyclotomic [is_cyclotomic_extension {n} K L]
(h : 2 < (n : ℕ)) (hirr : irreducible (cyclotomic n K)) :
norm K (ζ - 1) = ↑(eval 1 (cyclotomic n ℤ)) :=
begin
haveI := is_cyclotomic_extension.ne_zero' n K L,
let E := algebraic_closure L,
obtain ⟨z, hz⟩ := is_alg_closed.exists_root _ (degree_cyclotomic_pos n E n.pos).ne.symm,
apply (algebra_map K E).injective,
letI := finite_dimensional {n} K L,
letI := is_galois n K L,
rw [norm_eq_prod_embeddings],
conv_lhs { congr, skip, funext,
rw [← neg_sub, alg_hom.map_neg, alg_hom.map_sub, alg_hom.map_one, neg_eq_neg_one_mul] },
rw [prod_mul_distrib, prod_const, card_univ, alg_hom.card, is_cyclotomic_extension.finrank L hirr,
(totient_even h).neg_one_pow, one_mul],
have : finset.univ.prod (λ (σ : L →ₐ[K] E), 1 - σ ζ) = eval 1 (cyclotomic' n E),
{ rw [cyclotomic', eval_prod, ← @finset.prod_attach E E, ← univ_eq_attach],
refine fintype.prod_equiv (hζ.embeddings_equiv_primitive_roots E hirr) _ _ (λ σ, _),
simp },
haveI : ne_zero ((n : ℕ) : E) := (ne_zero.of_no_zero_smul_divisors K _ (n : ℕ)),
rw [this, cyclotomic', ← cyclotomic_eq_prod_X_sub_primitive_roots (is_root_cyclotomic_iff.1 hz),
← map_cyclotomic_int, _root_.map_int_cast, ←int.cast_one, eval_int_cast_map, eq_int_cast,
int.cast_id]
end
/-- If `is_prime_pow (n : ℕ)`, `n ≠ 2` and `irreducible (cyclotomic n K)` (in particular for
`K = ℚ`), then the norm of `ζ - 1` is `(n : ℕ).min_fac`. -/
lemma sub_one_norm_is_prime_pow (hn : is_prime_pow (n : ℕ)) [is_cyclotomic_extension {n} K L]
(hirr : irreducible (cyclotomic (n : ℕ) K)) (h : n ≠ 2) :
norm K (ζ - 1) = (n : ℕ).min_fac :=
begin
have := (coe_lt_coe 2 _).1 (lt_of_le_of_ne (succ_le_of_lt (is_prime_pow.one_lt hn))
(function.injective.ne pnat.coe_injective h).symm),
letI hprime : fact ((n : ℕ).min_fac.prime) := ⟨min_fac_prime (is_prime_pow.ne_one hn)⟩,
rw [sub_one_norm_eq_eval_cyclotomic hζ this hirr],
nth_rewrite 0 [← is_prime_pow.min_fac_pow_factorization_eq hn],
obtain ⟨k, hk⟩ : ∃ k, ((n : ℕ).factorization) (n : ℕ).min_fac = k + 1 :=
exists_eq_succ_of_ne_zero (((n : ℕ).factorization.mem_support_to_fun (n : ℕ).min_fac).1 $
factor_iff_mem_factorization.2 $ (mem_factors (is_prime_pow.ne_zero hn)).2
⟨hprime.out, min_fac_dvd _⟩),
simp [hk, sub_one_norm_eq_eval_cyclotomic hζ this hirr],
end
omit hζ
variable {A}
lemma minpoly_sub_one_eq_cyclotomic_comp [algebra K A] [is_domain A] {ζ : A}
[is_cyclotomic_extension {n} K A] (hζ : is_primitive_root ζ n)
(h : irreducible (polynomial.cyclotomic n K)) :
minpoly K (ζ - 1) = (cyclotomic n K).comp (X + 1) :=
begin
haveI := is_cyclotomic_extension.ne_zero' n K A,
rw [show ζ - 1 = ζ + (algebra_map K A (-1)), by simp [sub_eq_add_neg], minpoly.add_algebra_map
(is_cyclotomic_extension.integral {n} K A ζ), hζ.minpoly_eq_cyclotomic_of_irreducible h],
simp
end
local attribute [instance] is_cyclotomic_extension.finite_dimensional
local attribute [instance] is_cyclotomic_extension.is_galois
/-- If `irreducible (cyclotomic (p ^ (k + 1)) K)` (in particular for `K = ℚ`) and `p` is a prime,
then the norm of `ζ ^ (p ^ s) - 1` is `p ^ (p ^ s)` if `p ^ (k - s + 1) ≠ 2`. See the next lemmas
for similar results. -/
lemma pow_sub_one_norm_prime_pow_ne_two {k s : ℕ} (hζ : is_primitive_root ζ ↑(p ^ (k + 1)))
[hpri : fact (p : ℕ).prime] [is_cyclotomic_extension {p ^ (k + 1)} K L]
(hirr : irreducible (cyclotomic (↑(p ^ (k + 1)) : ℕ) K)) (hs : s ≤ k)
(htwo : p ^ (k - s + 1) ≠ 2) : norm K (ζ ^ ((p : ℕ) ^ s) - 1) = p ^ ((p : ℕ) ^ s) :=
begin
have hirr₁ : irreducible (cyclotomic (p ^ (k - s + 1)) K) :=
cyclotomic_irreducible_pow_of_irreducible_pow hpri.1 (by linarith) hirr,
rw ←pnat.pow_coe at hirr₁,
let η := ζ ^ ((p : ℕ) ^ s) - 1,
let η₁ : K⟮η⟯ := intermediate_field.adjoin_simple.gen K η,
have hη : is_primitive_root (η + 1) (p ^ (k + 1 - s)),
{ rw [sub_add_cancel],
refine is_primitive_root.pow (p ^ (k + 1)).pos hζ _,
rw [pnat.pow_coe, ← pow_add, add_comm s, nat.sub_add_cancel (le_trans hs (nat.le_succ k))] },
haveI : is_cyclotomic_extension {p ^ (k - s + 1)} K K⟮η⟯,
{ suffices : is_cyclotomic_extension {p ^ (k - s + 1)} K K⟮η + 1⟯.to_subalgebra,
{ have H : K⟮η + 1⟯.to_subalgebra = K⟮η⟯.to_subalgebra,
{ simp only [intermediate_field.adjoin_simple_to_subalgebra_of_integral
(is_cyclotomic_extension.integral {p ^ (k + 1)} K L _)],
refine subalgebra.ext (λ x, ⟨λ hx, adjoin_le _ hx, λ hx, adjoin_le _ hx⟩),
{ simp only [set.singleton_subset_iff, set_like.mem_coe],
exact subalgebra.add_mem _ (subset_adjoin (mem_singleton η)) (subalgebra.one_mem _) },
{ simp only [set.singleton_subset_iff, set_like.mem_coe],
nth_rewrite 0 [← add_sub_cancel η 1],
refine subalgebra.sub_mem _ (subset_adjoin (mem_singleton _)) (subalgebra.one_mem _) } },
rw [H] at this,
exact this },
rw [intermediate_field.adjoin_simple_to_subalgebra_of_integral
(is_cyclotomic_extension.integral {p ^ (k + 1)} K L _)],
have hη' : is_primitive_root (η + 1) ↑(p ^ (k + 1 - s)) := by simpa using hη,
convert hη'.adjoin_is_cyclotomic_extension K,
rw [nat.sub_add_comm hs] },
replace hη : is_primitive_root (η₁ + 1) ↑(p ^ (k - s + 1)),
{ apply coe_submonoid_class_iff.1,
convert hη,
rw [nat.sub_add_comm hs, pow_coe] },
rw [norm_eq_norm_adjoin K],
{ have H := hη.sub_one_norm_is_prime_pow _ hirr₁ htwo,
swap, { rw [pnat.pow_coe], exact hpri.1.is_prime_pow.pow (nat.succ_ne_zero _) },
rw [add_sub_cancel] at H,
rw [H, coe_coe],
congr,
{ rw [pnat.pow_coe, nat.pow_min_fac, hpri.1.min_fac_eq], exact nat.succ_ne_zero _ },
have := finite_dimensional.finrank_mul_finrank K K⟮η⟯ L,
rw [is_cyclotomic_extension.finrank L hirr, is_cyclotomic_extension.finrank K⟮η⟯ hirr₁,
pnat.pow_coe, pnat.pow_coe, nat.totient_prime_pow hpri.out (k - s).succ_pos,
nat.totient_prime_pow hpri.out k.succ_pos, mul_comm _ (↑p - 1), mul_assoc,
mul_comm (↑p ^ (k.succ - 1))] at this,
replace this := mul_left_cancel₀ (tsub_pos_iff_lt.2 hpri.out.one_lt).ne' this,
have Hex : k.succ - 1 = (k - s).succ - 1 + s,
{ simp only [nat.succ_sub_succ_eq_sub, tsub_zero],
exact (nat.sub_add_cancel hs).symm },
rw [Hex, pow_add] at this,
exact mul_left_cancel₀ (pow_ne_zero _ hpri.out.ne_zero) this },
all_goals { apply_instance }
end
/-- If `irreducible (cyclotomic (p ^ (k + 1)) K)` (in particular for `K = ℚ`) and `p` is a prime,
then the norm of `ζ ^ (p ^ s) - 1` is `p ^ (p ^ s)` if `p ≠ 2`. -/
lemma pow_sub_one_norm_prime_ne_two {k : ℕ} (hζ : is_primitive_root ζ ↑(p ^ (k + 1)))
[hpri : fact (p : ℕ).prime] [is_cyclotomic_extension {p ^ (k + 1)} K L]
(hirr : irreducible (cyclotomic (↑(p ^ (k + 1)) : ℕ) K)) {s : ℕ} (hs : s ≤ k)
(hodd : p ≠ 2) : norm K (ζ ^ ((p : ℕ) ^ s) - 1) = p ^ ((p : ℕ) ^ s) :=
begin
refine hζ.pow_sub_one_norm_prime_pow_ne_two hirr hs (λ h, _),
rw [← pnat.coe_inj, pnat.coe_bit0, pnat.one_coe, pnat.pow_coe, ← pow_one 2] at h,
replace h := eq_of_prime_pow_eq (prime_iff.1 hpri.out) (prime_iff.1 nat.prime_two)
((k - s).succ_pos) h,
rw [← pnat.one_coe, ← pnat.coe_bit0, pnat.coe_inj] at h,
exact hodd h
end
/-- If `irreducible (cyclotomic (p ^ (k + 1)) K)` (in particular for `K = ℚ`) and `p` is an odd
prime, then the norm of `ζ - 1` is `p`. -/
lemma sub_one_norm_prime_ne_two {k : ℕ} (hζ : is_primitive_root ζ ↑(p ^ (k + 1)))
[hpri : fact (p : ℕ).prime] [is_cyclotomic_extension {p ^ (k + 1)} K L]
(hirr : irreducible (cyclotomic (↑(p ^ (k + 1)) : ℕ) K)) (h : p ≠ 2) :
norm K (ζ - 1) = p :=
by simpa using hζ.pow_sub_one_norm_prime_ne_two hirr k.zero_le h
/-- If `irreducible (cyclotomic p K)` (in particular for `K = ℚ`) and `p` is an odd prime,
then the norm of `ζ - 1` is `p`. -/
lemma sub_one_norm_prime [hpri : fact (p : ℕ).prime] [hcyc : is_cyclotomic_extension {p} K L]
(hζ: is_primitive_root ζ p) (hirr : irreducible (cyclotomic p K)) (h : p ≠ 2) :
norm K (ζ - 1) = p :=
begin
replace hirr : irreducible (cyclotomic (↑(p ^ (0 + 1)) : ℕ) K) := by simp [hirr],
replace hζ : is_primitive_root ζ (↑(p ^ (0 + 1)) : ℕ) := by simp [hζ],
haveI : is_cyclotomic_extension {p ^ (0 + 1)} K L := by simp [hcyc],
simpa using sub_one_norm_prime_ne_two hζ hirr h
end
/-- If `irreducible (cyclotomic (2 ^ (k + 1)) K)` (in particular for `K = ℚ`), then the norm of
`ζ ^ (2 ^ k) - 1` is `(-2) ^ (2 ^ k)`. -/
lemma pow_sub_one_norm_two {k : ℕ} (hζ : is_primitive_root ζ (2 ^ (k + 1)))
[is_cyclotomic_extension {2 ^ (k + 1)} K L]
(hirr : irreducible (cyclotomic (2 ^ (k + 1)) K)) :
norm K (ζ ^ (2 ^ k) - 1) = (-2) ^ (2 ^ k) :=
begin
have := hζ.pow_of_dvd (λ h, two_ne_zero (pow_eq_zero h)) (pow_dvd_pow 2 (le_succ k)),
rw [nat.pow_div (le_succ k) zero_lt_two, nat.succ_sub (le_refl k), nat.sub_self, pow_one] at this,
have H : (-1 : L) - (1 : L) = algebra_map K L (-2),
{ simp only [_root_.map_neg, map_bit0, _root_.map_one],
ring },
replace hirr : irreducible (cyclotomic (2 ^ (k + 1) : ℕ+) K) := by simp [hirr],
rw [this.eq_neg_one_of_two_right, H, algebra.norm_algebra_map,
is_cyclotomic_extension.finrank L hirr,
pow_coe, pnat.coe_bit0, one_coe, totient_prime_pow nat.prime_two (zero_lt_succ k),
succ_sub_succ_eq_sub, tsub_zero, mul_one]
end
/-- If `irreducible (cyclotomic (2 ^ k) K)` (in particular for `K = ℚ`) and `k` is at least `2`,
then the norm of `ζ - 1` is `2`. -/
lemma sub_one_norm_two {k : ℕ} (hζ : is_primitive_root ζ (2 ^ k)) (hk : 2 ≤ k)
[H : is_cyclotomic_extension {2 ^ k} K L] (hirr : irreducible (cyclotomic (2 ^ k) K)) :
norm K (ζ - 1) = 2 :=
begin
have : 2 < (2 ^ k : ℕ+),
{ simp only [← coe_lt_coe, pnat.coe_bit0, one_coe, pow_coe],
nth_rewrite 0 [← pow_one 2],
exact pow_lt_pow one_lt_two (lt_of_lt_of_le one_lt_two hk) },
replace hirr : irreducible (cyclotomic (2 ^ k : ℕ+) K) := by simp [hirr],
replace hζ : is_primitive_root ζ (2 ^ k : ℕ+) := by simp [hζ],
obtain ⟨k₁, hk₁⟩ := exists_eq_succ_of_ne_zero ((lt_of_lt_of_le zero_lt_two hk).ne.symm),
simpa [hk₁] using sub_one_norm_eq_eval_cyclotomic hζ this hirr,
end
/-- If `irreducible (cyclotomic (p ^ (k + 1)) K)` (in particular for `K = ℚ`) and `p` is a prime,
then the norm of `ζ ^ (p ^ s) - 1` is `p ^ (p ^ s)` if `k ≠ 0` and `s ≤ k`. -/
lemma pow_sub_one_norm_prime_pow_of_ne_zero {k s : ℕ} (hζ : is_primitive_root ζ ↑(p ^ (k + 1)))
[hpri : fact (p : ℕ).prime] [hcycl : is_cyclotomic_extension {p ^ (k + 1)} K L]
(hirr : irreducible (cyclotomic (↑(p ^ (k + 1)) : ℕ) K)) (hs : s ≤ k)
(hk : k ≠ 0) : norm K (ζ ^ ((p : ℕ) ^ s) - 1) = p ^ ((p : ℕ) ^ s) :=
begin
by_cases htwo : p ^ (k - s + 1) = 2,
{ have hp : p = 2,
{ rw [← pnat.coe_inj, pnat.coe_bit0, pnat.one_coe, pnat.pow_coe, ← pow_one 2] at htwo,
replace htwo := eq_of_prime_pow_eq (prime_iff.1 hpri.out) (prime_iff.1 nat.prime_two)
(succ_pos _) htwo,
rwa [show 2 = ((2 : ℕ+) : ℕ), by simp, pnat.coe_inj] at htwo },
replace hs : s = k,
{ rw [hp, ← pnat.coe_inj, pnat.pow_coe, pnat.coe_bit0, pnat.one_coe] at htwo,
nth_rewrite 1 [← pow_one 2] at htwo,
replace htwo := nat.pow_right_injective rfl.le htwo,
rw [add_left_eq_self, nat.sub_eq_zero_iff_le] at htwo,
refine le_antisymm hs htwo },
simp only [hs, hp, pnat.coe_bit0, one_coe, coe_coe, cast_bit0, cast_one,
pow_coe] at ⊢ hζ hirr hcycl,
haveI := hcycl,
obtain ⟨k₁, hk₁⟩ := nat.exists_eq_succ_of_ne_zero hk,
rw [hζ.pow_sub_one_norm_two hirr],
rw [hk₁, pow_succ, pow_mul, neg_eq_neg_one_mul, mul_pow, neg_one_sq, one_mul, ← pow_mul,
← pow_succ] },
{ exact hζ.pow_sub_one_norm_prime_pow_ne_two hirr hs htwo }
end
end field
end is_primitive_root
namespace is_cyclotomic_extension
open is_primitive_root
variables {K} (L) [field K] [field L] [algebra K L]
/-- If `irreducible (cyclotomic n K)` (in particular for `K = ℚ`), the norm of `zeta n K L` is `1`
if `n` is odd. -/
lemma norm_zeta_eq_one [is_cyclotomic_extension {n} K L] (hn : n ≠ 2)
(hirr : irreducible (cyclotomic n K)) : norm K (zeta n K L) = 1 :=
(zeta_spec n K L).norm_eq_one hn hirr
/-- If `is_prime_pow (n : ℕ)`, `n ≠ 2` and `irreducible (cyclotomic n K)` (in particular for
`K = ℚ`), then the norm of `zeta n K L - 1` is `(n : ℕ).min_fac`. -/
lemma is_prime_pow_norm_zeta_sub_one (hn : is_prime_pow (n : ℕ))
[is_cyclotomic_extension {n} K L]
(hirr : irreducible (cyclotomic (n : ℕ) K)) (h : n ≠ 2) :
norm K (zeta n K L - 1) = (n : ℕ).min_fac :=
(zeta_spec n K L).sub_one_norm_is_prime_pow hn hirr h
/-- If `irreducible (cyclotomic (p ^ (k + 1)) K)` (in particular for `K = ℚ`) and `p` is a prime,
then the norm of `(zeta (p ^ (k + 1)) K L) ^ (p ^ s) - 1` is `p ^ (p ^ s)`
if `p ^ (k - s + 1) ≠ 2`. -/
lemma prime_ne_two_pow_norm_zeta_pow_sub_one {k : ℕ} [hpri : fact (p : ℕ).prime]
[is_cyclotomic_extension {p ^ (k + 1)} K L]
(hirr : irreducible (cyclotomic (↑(p ^ (k + 1)) : ℕ) K)) {s : ℕ} (hs : s ≤ k)
(htwo : p ^ (k - s + 1) ≠ 2) :
norm K ((zeta (p ^ (k + 1)) K L) ^ ((p : ℕ) ^ s) - 1) = p ^ ((p : ℕ) ^ s) :=
(zeta_spec _ K L).pow_sub_one_norm_prime_pow_ne_two hirr hs htwo
/-- If `irreducible (cyclotomic (p ^ (k + 1)) K)` (in particular for `K = ℚ`) and `p` is an odd
prime, then the norm of `zeta (p ^ (k + 1)) K L - 1` is `p`. -/
lemma prime_ne_two_pow_norm_zeta_sub_one {k : ℕ} [hpri : fact (p : ℕ).prime]
[is_cyclotomic_extension {p ^ (k + 1)} K L]
(hirr : irreducible (cyclotomic (↑(p ^ (k + 1)) : ℕ) K)) (h : p ≠ 2) :
norm K (zeta (p ^ (k + 1)) K L - 1) = p :=
(zeta_spec _ K L).sub_one_norm_prime_ne_two hirr h
/-- If `irreducible (cyclotomic p K)` (in particular for `K = ℚ`) and `p` is an odd prime,
then the norm of `zeta p K L - 1` is `p`. -/
lemma prime_ne_two_norm_zeta_sub_one [hpri : fact (p : ℕ).prime]
[hcyc : is_cyclotomic_extension {p} K L] (hirr : irreducible (cyclotomic p K)) (h : p ≠ 2) :
norm K (zeta p K L - 1) = p :=
(zeta_spec _ K L).sub_one_norm_prime hirr h
/-- If `irreducible (cyclotomic (2 ^ k) K)` (in particular for `K = ℚ`) and `k` is at least `2`,
then the norm of `zeta (2 ^ k) K L - 1` is `2`. -/
lemma two_pow_norm_zeta_sub_one {k : ℕ} (hk : 2 ≤ k)
[is_cyclotomic_extension {2 ^ k} K L] (hirr : irreducible (cyclotomic (2 ^ k) K)) :
norm K (zeta (2 ^ k) K L - 1) = 2 :=
sub_one_norm_two (zeta_spec (2 ^ k) K L) hk hirr
end is_cyclotomic_extension
end norm
|
83714fe86dde35aee2c51e066ba5fef42337e42b | dac4e6671410f506c880986cbb2212dd7f5b3dfd | /hanoi_project/hello.lean | 650e7e3712d9d0e1020737a096b4683ae4ebc94e | [
"CC-BY-4.0"
] | permissive | thalesant/formalabstracts-2018 | e6ddfe8b3ce5c6f055ddcccf345bf55c41f850c1 | d206dfa32a6b4a84aacc3a5500a144757e6d3454 | refs/heads/master | 1,642,678,879,231 | 1,561,648,713,000 | 1,561,648,713,000 | 97,608,420 | 1 | 0 | null | 1,564,063,995,000 | 1,500,388,250,000 | Lean | UTF-8 | Lean | false | false | 22 | lean | #print "Hello teacher" |
6a3367c3d7a8baa86aa6d0b687259791f30bd7aa | 57fdc8de88f5ea3bfde4325e6ecd13f93a274ab5 | /data/equiv.lean | 5356bca1917b2a2ddccd1bcd1ea89132a92bbfc0 | [
"Apache-2.0"
] | permissive | louisanu/mathlib | 11f56f2d40dc792bc05ee2f78ea37d73e98ecbfe | 2bd5e2159d20a8f20d04fc4d382e65eea775ed39 | refs/heads/master | 1,617,706,993,439 | 1,523,163,654,000 | 1,523,163,654,000 | 124,519,997 | 0 | 0 | Apache-2.0 | 1,520,588,283,000 | 1,520,588,283,000 | null | UTF-8 | Lean | false | false | 28,483 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Mario Carneiro
In the standard library we cannot assume the univalence axiom.
We say two types are equivalent if they are isomorphic.
Two equivalent types have the same cardinality.
-/
import data.prod data.nat.pairing logic.function tactic data.set.lattice
import algebra.group
open function
universes u v w
variables {α : Sort u} {β : Sort v} {γ : Sort w}
namespace subtype
/-- Restriction of a function to a function on subtypes. -/
def map {p : α → Prop} {q : β → Prop} (f : α → β) (h : ∀a, p a → q (f a)) :
subtype p → subtype q
| ⟨v, hv⟩ := ⟨f v, h v hv⟩
theorem map_comp {p : α → Prop} {q : β → Prop} {r : γ → Prop} {x : subtype p}
(f : α → β) (h : ∀a, p a → q (f a)) (g : β → γ) (l : ∀a, q a → r (g a)) :
map g l (map f h x) = map (g ∘ f) (assume a ha, l (f a) $ h a ha) x :=
by cases x with v h; refl
theorem map_id {p : α → Prop} {h : ∀a, p a → p (id a)} : map (@id α) h = id :=
funext $ assume ⟨v, h⟩, rfl
end subtype
namespace function
theorem left_inverse.f_g_eq_id {f : α → β} {g : β → α} (h : left_inverse f g) : f ∘ g = id :=
funext $ h
theorem right_inverse.g_f_eq_id {f : α → β} {g : β → α} (h : right_inverse f g) : g ∘ f = id :=
funext $ h
theorem left_inverse.comp {f : α → β} {g : β → α} {h : β → γ} {i : γ → β}
(hf : left_inverse f g) (hh : left_inverse h i) : left_inverse (h ∘ f) (g ∘ i) :=
assume a, show h (f (g (i a))) = a, by rw [hf (i a), hh a]
theorem right_inverse.comp {f : α → β} {g : β → α} {h : β → γ} {i : γ → β}
(hf : right_inverse f g) (hh : right_inverse h i) : right_inverse (h ∘ f) (g ∘ i) :=
left_inverse.comp hh hf
end function
/-- `α ≃ β` is the type of functions from `α → β` with a two-sided inverse. -/
structure equiv (α : Sort*) (β : Sort*) :=
(to_fun : α → β)
(inv_fun : β → α)
(left_inv : left_inverse inv_fun to_fun)
(right_inv : right_inverse inv_fun to_fun)
namespace equiv
/-- `perm α` is the type of bijections from `α` to itself. -/
@[reducible] def perm (α : Sort*) := equiv α α
infix ` ≃ `:50 := equiv
instance : has_coe_to_fun (α ≃ β) :=
⟨_, to_fun⟩
@[simp] theorem coe_fn_mk (f : α → β) (g l r) : (equiv.mk f g l r : α → β) = f :=
rfl
theorem eq_of_to_fun_eq : ∀ {e₁ e₂ : equiv α β}, (e₁ : α → β) = e₂ → e₁ = e₂
| ⟨f₁, g₁, l₁, r₁⟩ ⟨f₂, g₂, l₂, r₂⟩ h :=
have f₁ = f₂, from h,
have g₁ = g₂, from funext $ assume x,
have f₁ (g₁ x) = f₂ (g₂ x), from (r₁ x).trans (r₂ x).symm,
have f₁ (g₁ x) = f₁ (g₂ x), by subst f₂; exact this,
show g₁ x = g₂ x, from injective_of_left_inverse l₁ this,
by simp *
lemma ext (f g : equiv α β) (H : ∀ x, f x = g x) : f = g :=
eq_of_to_fun_eq (funext H)
@[refl] protected def refl (α : Sort*) : α ≃ α := ⟨id, id, λ x, rfl, λ x, rfl⟩
@[symm] protected def symm (e : α ≃ β) : β ≃ α := ⟨e.inv_fun, e.to_fun, e.right_inv, e.left_inv⟩
@[trans] protected def trans (e₁ : α ≃ β) (e₂ : β ≃ γ) : α ≃ γ :=
⟨e₂.to_fun ∘ e₁.to_fun, e₁.inv_fun ∘ e₂.inv_fun,
e₂.left_inv.comp e₁.left_inv, e₂.right_inv.comp e₁.right_inv⟩
protected theorem bijective : ∀ f : α ≃ β, bijective f
| ⟨f, g, h₁, h₂⟩ :=
⟨injective_of_left_inverse h₁, surjective_of_has_right_inverse ⟨_, h₂⟩⟩
protected theorem subsingleton (e : α ≃ β) : ∀ [subsingleton β], subsingleton α
| ⟨H⟩ := ⟨λ a b, e.bijective.1 (H _ _)⟩
protected def decidable_eq (e : α ≃ β) [H : decidable_eq β] : decidable_eq α
| a b := decidable_of_iff _ e.bijective.1.eq_iff
protected def cast {α β : Sort*} (h : α = β) : α ≃ β :=
⟨cast h, cast h.symm, λ x, by cases h; refl, λ x, by cases h; refl⟩
@[simp] theorem coe_fn_symm_mk (f : α → β) (g l r) : ((equiv.mk f g l r).symm : β → α) = g :=
rfl
@[simp] theorem refl_apply (x : α) : equiv.refl α x = x := rfl
@[simp] theorem trans_apply : ∀ (f : α ≃ β) (g : β ≃ γ) (a : α), (f.trans g) a = g (f a)
| ⟨f₁, g₁, l₁, r₁⟩ ⟨f₂, g₂, l₂, r₂⟩ a := rfl
@[simp] theorem apply_inverse_apply : ∀ (e : α ≃ β) (x : β), e (e.symm x) = x
| ⟨f₁, g₁, l₁, r₁⟩ x := by simp [equiv.symm]; rw r₁
@[simp] theorem inverse_apply_apply : ∀ (e : α ≃ β) (x : α), e.symm (e x) = x
| ⟨f₁, g₁, l₁, r₁⟩ x := by simp [equiv.symm]; rw l₁
@[simp] theorem apply_eq_iff_eq : ∀ (f : α ≃ β) (x y : α), f x = f y ↔ x = y
| ⟨f₁, g₁, l₁, r₁⟩ x y := (injective_of_left_inverse l₁).eq_iff
@[simp] theorem cast_apply {α β} (h : α = β) (x : α) : equiv.cast h x = cast h x := rfl
theorem apply_eq_iff_eq_inverse_apply : ∀ (f : α ≃ β) (x : α) (y : β), f x = y ↔ x = f.symm y
| ⟨f₁, g₁, l₁, r₁⟩ x y := by simp [equiv.symm];
show f₁ x = y ↔ x = g₁ y; from
⟨λ e : f₁ x = y, e ▸ (l₁ x).symm,
λ e : x = g₁ y, e.symm ▸ r₁ y⟩
/- The group of permutations (self-equivalences) of a type `α` -/
instance perm_group {α : Type u} : group (perm α) :=
begin
refine { mul := λ f g, equiv.trans g f, one := equiv.refl α, inv:= equiv.symm, ..};
intros; apply equiv.ext; try { apply trans_apply },
apply inverse_apply_apply
end
def equiv_empty (h : α → false) : α ≃ empty :=
⟨λ x, (h x).elim, λ e, e.rec _, λ x, (h x).elim, λ e, e.rec _⟩
def false_equiv_empty : false ≃ empty :=
equiv_empty _root_.id
def empty_of_not_nonempty {α : Sort*} (h : ¬ nonempty α) : α ≃ empty :=
⟨assume a, (h ⟨a⟩).elim, assume e, e.rec_on _, assume a, (h ⟨a⟩).elim, assume e, e.rec_on _⟩
protected def ulift {α : Type u} : ulift α ≃ α :=
⟨ulift.down, ulift.up, ulift.up_down, λ a, rfl⟩
protected def plift : plift α ≃ α :=
⟨plift.down, plift.up, plift.up_down, plift.down_up⟩
@[congr] def arrow_congr {α₁ β₁ α₂ β₂ : Sort*} : α₁ ≃ α₂ → β₁ ≃ β₂ → (α₁ → β₁) ≃ (α₂ → β₂)
| ⟨f₁, g₁, l₁, r₁⟩ ⟨f₂, g₂, l₂, r₂⟩ :=
⟨λ (h : α₁ → β₁) (a : α₂), f₂ (h (g₁ a)),
λ (h : α₂ → β₂) (a : α₁), g₂ (h (f₁ a)),
λ h, by funext a; dsimp; rw [l₁, l₂],
λ h, by funext a; dsimp; rw [r₁, r₂]⟩
def punit_equiv_punit : punit.{v} ≃ punit.{w} :=
⟨λ _, punit.star, λ _, punit.star, λ u, by cases u; refl, λ u, by cases u; reflexivity⟩
section
@[simp] def arrow_unit_equiv_unit (α : Sort*) : (α → punit.{v}) ≃ punit.{w} :=
⟨λ f, punit.star, λ u f, punit.star, λ f, by funext x; cases f x; refl, λ u, by cases u; reflexivity⟩
@[simp] def unit_arrow_equiv (α : Sort*) : (punit.{u} → α) ≃ α :=
⟨λ f, f punit.star, λ a u, a, λ f, by funext x; cases x; refl, λ u, rfl⟩
@[simp] def empty_arrow_equiv_unit (α : Sort*) : (empty → α) ≃ punit.{u} :=
⟨λ f, punit.star, λ u e, e.rec _, λ f, funext $ λ x, x.rec _, λ u, by cases u; refl⟩
@[simp] def false_arrow_equiv_unit (α : Sort*) : (false → α) ≃ punit.{u} :=
calc (false → α) ≃ (empty → α) : arrow_congr false_equiv_empty (equiv.refl _)
... ≃ punit : empty_arrow_equiv_unit _
def arrow_empty_unit {α : Sort*} : (empty → α) ≃ punit.{u} :=
⟨λf, punit.star, λu e, e.rec_on _, assume f, funext $ assume e, e.rec_on _, assume u, punit_eq _ _⟩
end
@[congr] def prod_congr {α₁ β₁ α₂ β₂ : Sort*} : α₁ ≃ α₂ → β₁ ≃ β₂ → (α₁ × β₁) ≃ (α₂ × β₂)
| ⟨f₁, g₁, l₁, r₁⟩ ⟨f₂, g₂, l₂, r₂⟩ :=
⟨λ ⟨a, b⟩, (f₁ a, f₂ b), λ ⟨a, b⟩, (g₁ a, g₂ b),
λ ⟨a, b⟩, show (g₁ (f₁ a), g₂ (f₂ b)) = (a, b), by rw [l₁ a, l₂ b],
λ ⟨a, b⟩, show (f₁ (g₁ a), f₂ (g₂ b)) = (a, b), by rw [r₁ a, r₂ b]⟩
@[simp] theorem prod_congr_apply {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) (a : α₁) (b : β₁) :
prod_congr e₁ e₂ (a, b) = (e₁ a, e₂ b) :=
by cases e₁; cases e₂; refl
@[simp] def prod_comm (α β : Sort*) : (α × β) ≃ (β × α) :=
⟨λ p, (p.2, p.1), λ p, (p.2, p.1), λ⟨a, b⟩, rfl, λ⟨a, b⟩, rfl⟩
@[simp] def prod_assoc (α β γ : Sort*) : ((α × β) × γ) ≃ (α × (β × γ)) :=
⟨λ p, ⟨p.1.1, ⟨p.1.2, p.2⟩⟩, λp, ⟨⟨p.1, p.2.1⟩, p.2.2⟩, λ ⟨⟨a, b⟩, c⟩, rfl, λ ⟨a, ⟨b, c⟩⟩, rfl⟩
@[simp] theorem prod_assoc_apply {α β γ : Sort*} (p : (α × β) × γ) :
prod_assoc α β γ p = ⟨p.1.1, ⟨p.1.2, p.2⟩⟩ := rfl
section
@[simp] def prod_unit (α : Sort*) : (α × punit.{u+1}) ≃ α :=
⟨λ p, p.1, λ a, (a, punit.star), λ ⟨_, punit.star⟩, rfl, λ a, rfl⟩
@[simp] theorem prod_unit_apply {α : Sort*} (a : α × punit.{u+1}) : prod_unit α a = a.1 := rfl
@[simp] def unit_prod (α : Sort*) : (punit.{u+1} × α) ≃ α :=
calc (punit × α) ≃ (α × punit) : prod_comm _ _
... ≃ α : prod_unit _
@[simp] theorem unit_prod_apply {α : Sort*} (a : punit.{u+1} × α) : unit_prod α a = a.2 := rfl
@[simp] def prod_empty (α : Sort*) : (α × empty) ≃ empty :=
equiv_empty (λ ⟨_, e⟩, e.rec _)
@[simp] def empty_prod (α : Sort*) : (empty × α) ≃ empty :=
equiv_empty (λ ⟨e, _⟩, e.rec _)
end
section
open sum
def psum_equiv_sum (α β : Sort*) : psum α β ≃ (α ⊕ β) :=
⟨λ s, psum.cases_on s inl inr,
λ s, sum.cases_on s psum.inl psum.inr,
λ s, by cases s; refl,
λ s, by cases s; refl⟩
def sum_congr {α₁ β₁ α₂ β₂ : Sort*} : α₁ ≃ α₂ → β₁ ≃ β₂ → (α₁ ⊕ β₁) ≃ (α₂ ⊕ β₂)
| ⟨f₁, g₁, l₁, r₁⟩ ⟨f₂, g₂, l₂, r₂⟩ :=
⟨λ s, match s with inl a₁ := inl (f₁ a₁) | inr b₁ := inr (f₂ b₁) end,
λ s, match s with inl a₂ := inl (g₁ a₂) | inr b₂ := inr (g₂ b₂) end,
λ s, match s with inl a := congr_arg inl (l₁ a) | inr a := congr_arg inr (l₂ a) end,
λ s, match s with inl a := congr_arg inl (r₁ a) | inr a := congr_arg inr (r₂ a) end⟩
@[simp] theorem sum_congr_apply_inl {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) (a : α₁) :
sum_congr e₁ e₂ (inl a) = inl (e₁ a) :=
by cases e₁; cases e₂; refl
@[simp] theorem sum_congr_apply_inr {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) (b : β₁) :
sum_congr e₁ e₂ (inr b) = inr (e₂ b) :=
by cases e₁; cases e₂; refl
def bool_equiv_unit_sum_unit : bool ≃ (punit.{u+1} ⊕ punit.{v+1}) :=
⟨λ b, cond b (inl punit.star) (inr punit.star),
λ s, sum.rec_on s (λ_, tt) (λ_, ff),
λ b, by cases b; refl,
λ s, by rcases s with ⟨⟨⟩⟩ | ⟨⟨⟩⟩; refl⟩
noncomputable def Prop_equiv_bool : Prop ≃ bool :=
⟨λ p, @to_bool p (classical.prop_decidable _),
λ b, b, λ p, by simp, λ b, by simp⟩
@[simp] def sum_comm (α β : Sort*) : (α ⊕ β) ≃ (β ⊕ α) :=
⟨λ s, match s with inl a := inr a | inr b := inl b end,
λ s, match s with inl b := inr b | inr a := inl a end,
λ s, by cases s; refl,
λ s, by cases s; refl⟩
@[simp] def sum_assoc (α β γ : Sort*) : ((α ⊕ β) ⊕ γ) ≃ (α ⊕ (β ⊕ γ)) :=
⟨λ s, match s with inl (inl a) := inl a | inl (inr b) := inr (inl b) | inr c := inr (inr c) end,
λ s, match s with inl a := inl (inl a) | inr (inl b) := inl (inr b) | inr (inr c) := inr c end,
λ s, by rcases s with ⟨_ | _⟩ | _; refl,
λ s, by rcases s with _ | _ | _; refl⟩
@[simp] theorem sum_assoc_apply_in1 {α β γ} (a) : sum_assoc α β γ (inl (inl a)) = inl a := rfl
@[simp] theorem sum_assoc_apply_in2 {α β γ} (b) : sum_assoc α β γ (inl (inr b)) = inr (inl b) := rfl
@[simp] theorem sum_assoc_apply_in3 {α β γ} (c) : sum_assoc α β γ (inr c) = inr (inr c) := rfl
@[simp] def sum_empty (α : Sort*) : (α ⊕ empty) ≃ α :=
⟨λ s, match s with inl a := a | inr e := empty.rec _ e end,
inl,
λ s, by rcases s with _ | ⟨⟨⟩⟩; refl,
λ a, rfl⟩
@[simp] def empty_sum (α : Sort*) : (empty ⊕ α) ≃ α :=
(sum_comm _ _).trans $ sum_empty _
@[simp] def option_equiv_sum_unit (α : Sort*) : option α ≃ (α ⊕ punit.{u+1}) :=
⟨λ o, match o with none := inr punit.star | some a := inl a end,
λ s, match s with inr _ := none | inl a := some a end,
λ o, by cases o; refl,
λ s, by rcases s with _ | ⟨⟨⟩⟩; refl⟩
def sum_equiv_sigma_bool (α β : Sort*) : (α ⊕ β) ≃ (Σ b: bool, cond b α β) :=
⟨λ s, match s with inl a := ⟨tt, a⟩ | inr b := ⟨ff, b⟩ end,
λ s, match s with ⟨tt, a⟩ := inl a | ⟨ff, b⟩ := inr b end,
λ s, by cases s; refl,
λ s, by rcases s with ⟨_|_, _⟩; refl⟩
end
section
def Pi_congr_right {α} {β₁ β₂ : α → Sort*} (F : ∀ a, β₁ a ≃ β₂ a) : (Π a, β₁ a) ≃ (Π a, β₂ a) :=
⟨λ H a, F a (H a), λ H a, (F a).symm (H a),
λ H, funext $ by simp, λ H, funext $ by simp⟩
end
section
def psigma_equiv_sigma {α} (β : α → Sort*) : psigma β ≃ sigma β :=
⟨λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, rfl, λ ⟨a, b⟩, rfl⟩
def sigma_congr_right {α} {β₁ β₂ : α → Sort*} (F : ∀ a, β₁ a ≃ β₂ a) : sigma β₁ ≃ sigma β₂ :=
⟨λ ⟨a, b⟩, ⟨a, F a b⟩, λ ⟨a, b⟩, ⟨a, (F a).symm b⟩,
λ ⟨a, b⟩, congr_arg (sigma.mk a) $ inverse_apply_apply (F a) b,
λ ⟨a, b⟩, congr_arg (sigma.mk a) $ apply_inverse_apply (F a) b⟩
def sigma_congr_left {α₁ α₂} {β : α₂ → Sort*} : ∀ f : α₁ ≃ α₂, (Σ a:α₁, β (f a)) ≃ (Σ a:α₂, β a)
| ⟨f, g, l, r⟩ :=
⟨λ ⟨a, b⟩, ⟨f a, b⟩, λ ⟨a, b⟩, ⟨g a, @@eq.rec β b (r a).symm⟩,
λ ⟨a, b⟩, match g (f a), l a : ∀ a' (h : a' = a),
@sigma.mk _ (β ∘ f) _ (@@eq.rec β b (congr_arg f h.symm)) = ⟨a, b⟩ with
| _, rfl := rfl end,
λ ⟨a, b⟩, match f (g a), _ : ∀ a' (h : a' = a), sigma.mk a' (@@eq.rec β b h.symm) = ⟨a, b⟩ with
| _, rfl := rfl end⟩
def sigma_equiv_prod (α β : Sort*) : (Σ_:α, β) ≃ (α × β) :=
⟨λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, rfl, λ ⟨a, b⟩, rfl⟩
def sigma_equiv_prod_of_equiv {α β} {β₁ : α → Sort*} (F : ∀ a, β₁ a ≃ β) : sigma β₁ ≃ (α × β) :=
(sigma_congr_right F).trans (sigma_equiv_prod α β)
end
section
def arrow_prod_equiv_prod_arrow (α β γ : Type*) : (γ → α × β) ≃ ((γ → α) × (γ → β)) :=
⟨λ f, (λ c, (f c).1, λ c, (f c).2),
λ p c, (p.1 c, p.2 c),
λ f, funext $ λ c, prod.mk.eta,
λ p, by cases p; refl⟩
def arrow_arrow_equiv_prod_arrow (α β γ : Sort*) : (α → β → γ) ≃ (α × β → γ) :=
⟨λ f, λ p, f p.1 p.2,
λ f, λ a b, f (a, b),
λ f, rfl,
λ f, by funext p; cases p; refl⟩
open sum
def sum_arrow_equiv_prod_arrow (α β γ : Type*) : ((α ⊕ β) → γ) ≃ ((α → γ) × (β → γ)) :=
⟨λ f, (f ∘ inl, f ∘ inr),
λ p s, sum.rec_on s p.1 p.2,
λ f, by funext s; cases s; refl,
λ p, by cases p; refl⟩
def sum_prod_distrib (α β γ : Sort*) : ((α ⊕ β) × γ) ≃ ((α × γ) ⊕ (β × γ)) :=
⟨λ p, match p with (inl a, c) := inl (a, c) | (inr b, c) := inr (b, c) end,
λ s, match s with inl (a, c) := (inl a, c) | inr (b, c) := (inr b, c) end,
λ p, by rcases p with ⟨_ | _, _⟩; refl,
λ s, by rcases s with ⟨_, _⟩ | ⟨_, _⟩; refl⟩
@[simp] theorem sum_prod_distrib_apply_left {α β γ} (a : α) (c : γ) :
sum_prod_distrib α β γ (sum.inl a, c) = sum.inl (a, c) := rfl
@[simp] theorem sum_prod_distrib_apply_right {α β γ} (b : β) (c : γ) :
sum_prod_distrib α β γ (sum.inr b, c) = sum.inr (b, c) := rfl
def prod_sum_distrib (α β γ : Sort*) : (α × (β ⊕ γ)) ≃ ((α × β) ⊕ (α × γ)) :=
calc (α × (β ⊕ γ)) ≃ ((β ⊕ γ) × α) : prod_comm _ _
... ≃ ((β × α) ⊕ (γ × α)) : sum_prod_distrib _ _ _
... ≃ ((α × β) ⊕ (α × γ)) : sum_congr (prod_comm _ _) (prod_comm _ _)
@[simp] theorem prod_sum_distrib_apply_left {α β γ} (a : α) (b : β) :
prod_sum_distrib α β γ (a, sum.inl b) = sum.inl (a, b) := rfl
@[simp] theorem prod_sum_distrib_apply_right {α β γ} (a : α) (c : γ) :
prod_sum_distrib α β γ (a, sum.inr c) = sum.inr (a, c) := rfl
def bool_prod_equiv_sum (α : Type u) : (bool × α) ≃ (α ⊕ α) :=
calc (bool × α) ≃ ((unit ⊕ unit) × α) : prod_congr bool_equiv_unit_sum_unit (equiv.refl _)
... ≃ (α × (unit ⊕ unit)) : prod_comm _ _
... ≃ ((α × unit) ⊕ (α × unit)) : prod_sum_distrib _ _ _
... ≃ (α ⊕ α) : sum_congr (prod_unit _) (prod_unit _)
end
section
open sum nat
def nat_equiv_nat_sum_unit : ℕ ≃ (ℕ ⊕ punit.{u+1}) :=
⟨λ n, match n with zero := inr punit.star | succ a := inl a end,
λ s, match s with inl n := succ n | inr punit.star := zero end,
λ n, begin cases n, repeat { refl } end,
λ s, begin cases s with a u, { refl }, {cases u, { refl }} end⟩
@[simp] def nat_sum_unit_equiv_nat : (ℕ ⊕ punit.{u+1}) ≃ ℕ :=
nat_equiv_nat_sum_unit.symm
@[simp] def nat_prod_nat_equiv_nat : (ℕ × ℕ) ≃ ℕ :=
⟨λ p, nat.mkpair p.1 p.2,
nat.unpair,
λ p, begin cases p, apply nat.unpair_mkpair end,
nat.mkpair_unpair⟩
@[simp] def nat_sum_bool_equiv_nat : (ℕ ⊕ bool) ≃ ℕ :=
calc (ℕ ⊕ bool) ≃ (ℕ ⊕ (unit ⊕ unit)) : sum_congr (equiv.refl _) bool_equiv_unit_sum_unit
... ≃ ((ℕ ⊕ unit) ⊕ unit) : (sum_assoc ℕ unit unit).symm
... ≃ (ℕ ⊕ unit) : sum_congr nat_sum_unit_equiv_nat (equiv.refl _)
... ≃ ℕ : nat_sum_unit_equiv_nat
@[simp] def bool_prod_nat_equiv_nat : (bool × ℕ) ≃ ℕ :=
⟨λ ⟨b, n⟩, bit b n, bodd_div2,
λ ⟨b, n⟩, by simp [bool_prod_nat_equiv_nat._match_1, bodd_bit, div2_bit],
λ n, by simp [bool_prod_nat_equiv_nat._match_1, bit_decomp]⟩
@[simp] def nat_sum_nat_equiv_nat : (ℕ ⊕ ℕ) ≃ ℕ :=
(bool_prod_equiv_sum ℕ).symm.trans bool_prod_nat_equiv_nat
def int_equiv_nat_sum_nat : ℤ ≃ (ℕ ⊕ ℕ) :=
by refine ⟨_, _, _, _⟩; intro z; {cases z; [left, right]; assumption} <|> {cases z; refl}
def int_equiv_nat : ℤ ≃ ℕ :=
int_equiv_nat_sum_nat.trans nat_sum_nat_equiv_nat
def prod_equiv_of_equiv_nat {α : Sort*} (e : α ≃ ℕ) : (α × α) ≃ α :=
calc (α × α) ≃ (ℕ × ℕ) : prod_congr e e
... ≃ ℕ : nat_prod_nat_equiv_nat
... ≃ α : e.symm
end
def list_equiv_of_equiv {α β : Type*} : α ≃ β → list α ≃ list β
| ⟨f, g, l, r⟩ :=
by refine ⟨list.map f, list.map g, λ x, _, λ x, _⟩;
simp [id_of_left_inverse l, id_of_right_inverse r]
section
open nat list
private def list.to_nat : list ℕ → ℕ
| [] := 0
| (a::l) := succ (mkpair l.to_nat a)
private def list.of_nat : ℕ → list ℕ
| 0 := []
| (succ v) := match unpair v, unpair_le v with
| (v₂, v₁), h :=
have v₂ < succ v, from lt_succ_of_le h,
v₁ :: list.of_nat v₂
end
private theorem list.of_nat_to_nat : ∀ l : list ℕ, list.of_nat (list.to_nat l) = l
| [] := rfl
| (a::l) := by simp [list.to_nat, list.of_nat, unpair_mkpair, *]
private theorem list.to_nat_of_nat : ∀ n : ℕ, list.to_nat (list.of_nat n) = n
| 0 := rfl
| (succ v) := begin
cases e : unpair v with v₁ v₂,
have := lt_succ_of_le (unpair_le v),
have IH := have v₁ < succ v, by rwa e at this, list.to_nat_of_nat v₁,
simp [list.of_nat, e, list.to_nat, IH, mkpair_unpair' e]
end
def list_nat_equiv_nat : list ℕ ≃ ℕ :=
⟨list.to_nat, list.of_nat, list.of_nat_to_nat, list.to_nat_of_nat⟩
def list_equiv_self_of_equiv_nat {α : Type} (e : α ≃ ℕ) : list α ≃ α :=
calc list α ≃ list ℕ : list_equiv_of_equiv e
... ≃ ℕ : list_nat_equiv_nat
... ≃ α : e.symm
end
section
def decidable_eq_of_equiv [h : decidable_eq α] : α ≃ β → decidable_eq β
| ⟨f, g, l, r⟩ b₁ b₂ :=
match h (g b₁) (g b₂) with
| (is_true he) := is_true $ have f (g b₁) = f (g b₂), from congr_arg f he, by rwa [r, r] at this
| (is_false hn) := is_false $ λeq, hn.elim $ by rw [eq]
end
end
def inhabited_of_equiv [inhabited α] : α ≃ β → inhabited β
| ⟨f, g, l, r⟩ := ⟨f (default _)⟩
section
open subtype
def subtype_equiv_of_subtype {p : α → Prop} : Π (e : α ≃ β), {a : α // p a} ≃ {b : β // p (e.symm b)}
| ⟨f, g, l, r⟩ :=
⟨subtype.map f $ assume a ha, show p (g (f a)), by rwa [l],
subtype.map g $ assume a ha, ha,
assume p, by simp [map_comp, l.f_g_eq_id]; rw [map_id]; refl,
assume p, by simp [map_comp, r.f_g_eq_id]; rw [map_id]; refl⟩
def subtype_subtype_equiv_subtype {α : Type u} (p : α → Prop) (q : subtype p → Prop) :
subtype q ≃ {a : α // ∃h:p a, q ⟨a, h⟩ } :=
⟨λ⟨⟨a, ha⟩, ha'⟩, ⟨a, ha, ha'⟩,
λ⟨a, ha⟩, ⟨⟨a, ha.cases_on $ assume h _, h⟩, by cases ha; exact ha_h⟩,
assume ⟨⟨a, ha⟩, h⟩, rfl, assume ⟨a, h₁, h₂⟩, rfl⟩
end
namespace set
open set
protected def univ (α) : @univ α ≃ α :=
⟨subtype.val, λ a, ⟨a, trivial⟩, λ ⟨a, _⟩, rfl, λ a, rfl⟩
protected def empty (α) : (∅ : set α) ≃ empty :=
equiv_empty $ λ ⟨x, h⟩, not_mem_empty x h
protected def union {α} {s t : set α} [decidable_pred s] (H : s ∩ t = ∅) :
(s ∪ t : set α) ≃ (s ⊕ t) :=
⟨λ ⟨x, h⟩, if hs : x ∈ s then sum.inl ⟨_, hs⟩ else sum.inr ⟨_, h.resolve_left hs⟩,
λ o, match o with
| (sum.inl ⟨x, h⟩) := ⟨x, or.inl h⟩
| (sum.inr ⟨x, h⟩) := ⟨x, or.inr h⟩
end,
λ ⟨x, h'⟩, by by_cases x ∈ s; simp [union._match_1, union._match_2, h]; congr,
λ o, by rcases o with ⟨x, h⟩ | ⟨x, h⟩; simp [union._match_1, union._match_2, h];
simp [show x ∉ s, from λ h', eq_empty_iff_forall_not_mem.1 H _ ⟨h', h⟩]⟩
protected def singleton {α} (a : α) : ({a} : set α) ≃ punit.{u} :=
⟨λ _, punit.star, λ _, ⟨a, mem_singleton _⟩,
λ ⟨x, h⟩, by simp at h; subst x,
λ ⟨⟩, rfl⟩
protected def insert {α} {s : set.{u} α} [decidable_pred s] {a : α} (H : a ∉ s) :
(insert a s : set α) ≃ (s ⊕ punit.{u+1}) :=
by rw ← union_singleton; exact
(set.union $ inter_singleton_eq_empty.2 H).trans
(sum_congr (equiv.refl _) (set.singleton _))
protected def sum_compl {α} (s : set α) [decidable_pred s] :
(s ⊕ (-s : set α)) ≃ α :=
(set.union (inter_compl_self _)).symm.trans
(by rw union_compl_self; exact set.univ _)
protected def prod {α β} (s : set α) (t : set β) :
(s.prod t) ≃ (s × t) :=
⟨λ ⟨⟨x, y⟩, ⟨h₁, h₂⟩⟩, ⟨⟨x, h₁⟩, ⟨y, h₂⟩⟩,
λ ⟨⟨x, h₁⟩, ⟨y, h₂⟩⟩, ⟨⟨x, y⟩, ⟨h₁, h₂⟩⟩,
λ ⟨⟨x, y⟩, ⟨h₁, h₂⟩⟩, rfl,
λ ⟨⟨x, h₁⟩, ⟨y, h₂⟩⟩, rfl⟩
protected noncomputable def image {α β} (f : α → β) (s : set α) (H : injective f) :
s ≃ (f '' s) :=
⟨λ ⟨x, h⟩, ⟨f x, mem_image_of_mem _ h⟩,
λ ⟨y, h⟩, ⟨classical.some h, (classical.some_spec h).1⟩,
λ ⟨x, h⟩, subtype.eq (H (classical.some_spec (mem_image_of_mem f h)).2),
λ ⟨y, h⟩, subtype.eq (classical.some_spec h).2⟩
@[simp] theorem image_apply {α β} (f : α → β) (s : set α) (H : injective f) (a h) :
set.image f s H ⟨a, h⟩ = ⟨f a, mem_image_of_mem _ h⟩ := rfl
protected noncomputable def range {α β} (f : α → β) (H : injective f) :
α ≃ range f :=
(set.univ _).symm.trans $ (set.image f univ H).trans (equiv.cast $ by rw image_univ)
@[simp] theorem range_apply {α β} (f : α → β) (H : injective f) (a) :
set.range f H a = ⟨f a, set.mem_range_self _⟩ :=
by dunfold equiv.set.range equiv.set.univ;
simp [set_coe_cast, -image_univ, image_univ.symm]
end set
noncomputable def of_bijective {α β} {f : α → β} (hf : bijective f) : α ≃ β :=
begin
have hg := bijective_comp equiv.plift.symm.bijective
(bijective_comp hf equiv.plift.bijective),
refine equiv.plift.symm.trans (equiv.trans _ equiv.plift),
exact (set.range _ hg.1).trans
((equiv.cast (by rw set.range_iff_surjective.2 hg.2)).trans (set.univ _))
end
@[simp] theorem of_bijective_to_fun {α β} {f : α → β} (hf : bijective f) : (of_bijective hf : α → β) = f :=
begin
funext a, dunfold of_bijective equiv.set.univ,
have hg := bijective_comp equiv.plift.symm.bijective
(bijective_comp hf equiv.plift.bijective),
simp [set.set_coe_cast, (∘), set.range_iff_surjective.2 hg.2],
end
section
open set
set_option eqn_compiler.zeta true
noncomputable def set.bUnion_eq_sigma_of_disjoint {α β} {s : set α} {t : α → set β}
(h : pairwise_on s (disjoint on t)) : (⋃i∈s, t i) ≃ (Σi:s, t i.val) :=
let f : (Σi:s, t i.val) → (⋃i∈s, t i) := λ⟨⟨a, ha⟩, ⟨b, hb⟩⟩, ⟨b, mem_bUnion ha hb⟩ in
have injective f,
from assume ⟨⟨a₁, ha₁⟩, ⟨b₁, hb₁⟩⟩ ⟨⟨a₂, ha₂⟩, ⟨b₂, hb₂⟩⟩ eq,
have b_eq : b₁ = b₂, from congr_arg subtype.val eq,
have a_eq : a₁ = a₂, from classical.by_contradiction $ assume ne,
have b₁ ∈ t a₁ ∩ t a₂, from ⟨hb₁, b_eq.symm ▸ hb₂⟩,
have t a₁ ∩ t a₂ ≠ ∅, from ne_empty_of_mem this,
this $ h _ ha₁ _ ha₂ ne,
sigma.eq (subtype.eq a_eq) (subtype.eq $ by subst b_eq; subst a_eq),
have surjective f,
from assume ⟨b, hb⟩,
have ∃a∈s, b ∈ t a, by simpa using hb,
let ⟨a, ha, hb⟩ := this in ⟨⟨⟨a, ha⟩, ⟨b, hb⟩⟩, rfl⟩,
(equiv.of_bijective ⟨‹injective f›, ‹surjective f›⟩).symm
end
section swap
variable [decidable_eq α]
open decidable
def swap_core (a b r : α) : α :=
if r = a then b
else if r = b then a
else r
theorem swap_core_self (r a : α) : swap_core a a r = r :=
by by_cases r = a; simp [swap_core, *]
theorem swap_core_swap_core (r a b : α) : swap_core a b (swap_core a b r) = r :=
begin
by_cases hb : r = b,
{ by_cases ha : r = a,
{ simp [hb.symm, ha.symm, swap_core_self] },
{ have : b ≠ a, by rwa [hb] at ha,
simp [swap_core, *] } },
{ by_cases ha : r = a,
{ have : b ≠ a, begin rw [ha] at hb, exact ne.symm hb end,
simp [swap_core, *] },
simp [swap_core, *] }
end
theorem swap_core_comm (r a b : α) : swap_core a b r = swap_core b a r :=
begin
by_cases hb : r = b,
{ by_cases ha : r = a,
{ simp [hb.symm, ha.symm, swap_core_self] },
{ have : b ≠ a, by rwa [hb] at ha,
simp [swap_core, *] } },
{ by_cases ha : r = a,
{ have : a ≠ b, by rwa [ha] at hb,
simp [swap_core, *] },
simp [swap_core, *] }
end
/-- `swap a b` is the permutation that swaps `a` and `b` and
leaves other values as is. -/
def swap (a b : α) : perm α :=
⟨swap_core a b, swap_core a b, λr, swap_core_swap_core r a b, λr, swap_core_swap_core r a b⟩
theorem swap_self (a : α) : swap a a = equiv.refl _ :=
eq_of_to_fun_eq $ funext $ λ r, swap_core_self r a
theorem swap_comm (a b : α) : swap a b = swap b a :=
eq_of_to_fun_eq $ funext $ λ r, swap_core_comm r _ _
theorem swap_apply_def (a b x : α) : swap a b x = if x = a then b else if x = b then a else x :=
rfl
theorem swap_apply_left (a b : α) : swap a b a = b :=
if_pos rfl
theorem swap_apply_right (a b : α) : swap a b b = a :=
by by_cases b = a; simp [swap_apply_def, *]
theorem swap_apply_of_ne_of_ne {a b x : α} : x ≠ a → x ≠ b → swap a b x = x :=
by simp [swap_apply_def] {contextual := tt}
theorem swap_swap (a b : α) : (swap a b).trans (swap a b) = equiv.refl _ :=
eq_of_to_fun_eq $ funext $ λ x, swap_core_swap_core _ _ _
theorem swap_comp_apply {a b x : α} (π : perm α) :
π.trans (swap a b) x = if π x = a then b else if π x = b then a else π x :=
by cases π; refl
end swap
end equiv
instance {α} [subsingleton α] : subsingleton (ulift α) := equiv.ulift.subsingleton
instance {α} [subsingleton α] : subsingleton (plift α) := equiv.plift.subsingleton
instance {α} [decidable_eq α] : decidable_eq (ulift α) := equiv.ulift.decidable_eq
instance {α} [decidable_eq α] : decidable_eq (plift α) := equiv.plift.decidable_eq
|
e1c2b336ad00438dec698d0d066c82559876e25b | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /doc/examples/ICERM2022/meta.lean | b7082614fac3e182de141ad5713c44a2481b0f2f | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | leanprover/lean4 | 4bdf9790294964627eb9be79f5e8f6157780b4cc | f1f9dc0f2f531af3312398999d8b8303fa5f096b | refs/heads/master | 1,693,360,665,786 | 1,693,350,868,000 | 1,693,350,868,000 | 129,571,436 | 2,827 | 311 | Apache-2.0 | 1,694,716,156,000 | 1,523,760,560,000 | Lean | UTF-8 | Lean | false | false | 2,384 | lean | import Lean
open Lean Meta
def ex1 (declName : Name) : MetaM Unit := do
let info ← getConstInfo declName
IO.println s!"{declName} : {← ppExpr info.type}"
if let some val := info.value? then
IO.println s!"{declName} : {← ppExpr val}"
#eval ex1 ``Nat
def ex2 (declName : Name) : MetaM Unit := do
let info ← getConstInfo declName
trace[Meta.debug] "{declName} : {info.type}"
if let some val := info.value? then
trace[Meta.debug] "{declName} : {val}"
#eval ex2 ``Add.add
set_option trace.Meta.debug true in
#eval ex2 ``Add.add
def ex3 (declName : Name) : MetaM Unit := do
let info ← getConstInfo declName
forallTelescope info.type fun xs type => do
trace[Meta.debug] "hypotheses : {xs}"
trace[Meta.debug] "resultType : {type}"
for x in xs do
trace[Meta.debug] "{x} : {← inferType x}"
def myMin [LT α] [DecidableRel (α := α) (·<·)] (a b : α) : α :=
if a < b then
a
else
b
set_option trace.Meta.debug true in
#eval ex3 ``myMin
def ex4 : MetaM Unit := do
let nat := mkConst ``Nat
withLocalDeclD `a nat fun a =>
withLocalDeclD `b nat fun b => do
let e ← mkAppM ``HAdd.hAdd #[a, b]
trace[Meta.debug] "{e} : {← inferType e}"
let e ← mkAdd a (mkNatLit 5)
trace[Meta.debug] "added 5: {e}"
let e ← whnf e
trace[Meta.debug] "whnf: {e}"
let e ← reduce e
trace[Meta.debug] "reduced: {e}"
let a_plus_1 ← mkAdd a (mkNatLit 1)
let succ_a := mkApp (mkConst ``Nat.succ) a
trace[Meta.debug] "({a_plus_1} =?= {succ_a}) == {← isDefEq a_plus_1 succ_a}"
let m ← mkFreshExprMVar nat
let m_plus_1 ← mkAdd m (mkNatLit 1)
trace[Meta.debug] "m_plus_1: {m_plus_1}"
unless (← isDefEq m_plus_1 succ_a) do throwError "isDefEq failed"
trace[Meta.debug] "m_plus_1: {m_plus_1}"
set_option trace.Meta.debug true in
#eval ex4
open Elab Term
def ex5 : TermElabM Unit := do
let nat := Lean.mkConst ``Nat
withLocalDeclD `a nat fun a => do
withLocalDeclD `b nat fun b => do
let ab ← mkAppM ``HAdd.hAdd #[a, b]
let stx ← `(fun x => if x < 10 then $(← exprToSyntax ab) + x else x + $(← exprToSyntax a))
let e ← elabTerm stx none
trace[Meta.debug] "{e} : {← inferType e}"
let e := mkApp e (mkNatLit 5)
let e ← whnf e
trace[Meta.debug] "{e}"
set_option trace.Meta.debug true in
#eval ex5
|
e169896ec120acc860302a017506f144363d7063 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/measure_theory/constructions/pi.lean | a616ee6c52a4651293d55b34abeb4bb125581b8f | [
"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 | 33,212 | lean | /-
Copyright (c) 2020 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn
-/
import measure_theory.constructions.prod.basic
import measure_theory.group.measure
import topology.constructions
/-!
# Product measures
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
In this file we define and prove properties about finite products of measures
(and at some point, countable products of measures).
## Main definition
* `measure_theory.measure.pi`: The product of finitely many σ-finite measures.
Given `μ : Π i : ι, measure (α i)` for `[fintype ι]` it has type `measure (Π i : ι, α i)`.
To apply Fubini along some subset of the variables, use
`measure_theory.measure_preserving_pi_equiv_pi_subtype_prod` to reduce to the situation of a product
of two measures: this lemma states that the bijection
`measurable_equiv.pi_equiv_pi_subtype_prod α p` between `(Π i : ι, α i)` and
`(Π i : {i // p i}, α i) × (Π i : {i // ¬ p i}, α i)` maps a product measure to a direct product of
product measures, to which one can apply the usual Fubini for direct product of measures.
## Implementation Notes
We define `measure_theory.outer_measure.pi`, the product of finitely many outer measures, as the
maximal outer measure `n` with the property that `n (pi univ s) ≤ ∏ i, m i (s i)`,
where `pi univ s` is the product of the sets `{s i | i : ι}`.
We then show that this induces a product of measures, called `measure_theory.measure.pi`.
For a collection of σ-finite measures `μ` and a collection of measurable sets `s` we show that
`measure.pi μ (pi univ s) = ∏ i, m i (s i)`. To do this, we follow the following steps:
* We know that there is some ordering on `ι`, given by an element of `[countable ι]`.
* Using this, we have an equivalence `measurable_equiv.pi_measurable_equiv_tprod` between
`Π ι, α i` and an iterated product of `α i`, called `list.tprod α l` for some list `l`.
* On this iterated product we can easily define a product measure `measure_theory.measure.tprod`
by iterating `measure_theory.measure.prod`
* Using the previous two steps we construct `measure_theory.measure.pi'` on `Π ι, α i` for countable
`ι`.
* We know that `measure_theory.measure.pi'` sends products of sets to products of measures, and
since `measure_theory.measure.pi` is the maximal such measure (or at least, it comes from an outer
measure which is the maximal such outer measure), we get the same rule for
`measure_theory.measure.pi`.
## Tags
finitary product measure
-/
noncomputable theory
open function set measure_theory.outer_measure filter measurable_space encodable
open_locale classical big_operators topology ennreal
universes u v
variables {ι ι' : Type*} {α : ι → Type*}
/-! We start with some measurability properties -/
/-- Boxes formed by π-systems form a π-system. -/
lemma is_pi_system.pi {C : Π i, set (set (α i))} (hC : ∀ i, is_pi_system (C i)) :
is_pi_system (pi univ '' pi univ C) :=
begin
rintro _ ⟨s₁, hs₁, rfl⟩ _ ⟨s₂, hs₂, rfl⟩ hst,
rw [← pi_inter_distrib] at hst ⊢, rw [univ_pi_nonempty_iff] at hst,
exact mem_image_of_mem _ (λ i _, hC i _ (hs₁ i (mem_univ i)) _ (hs₂ i (mem_univ i)) (hst i))
end
/-- Boxes form a π-system. -/
lemma is_pi_system_pi [Π i, measurable_space (α i)] :
is_pi_system (pi univ '' pi univ (λ i, {s : set (α i) | measurable_set s})) :=
is_pi_system.pi (λ i, is_pi_system_measurable_set)
section finite
variables [finite ι] [finite ι']
/-- Boxes of countably spanning sets are countably spanning. -/
lemma is_countably_spanning.pi {C : Π i, set (set (α i))}
(hC : ∀ i, is_countably_spanning (C i)) :
is_countably_spanning (pi univ '' pi univ C) :=
begin
choose s h1s h2s using hC,
casesI nonempty_encodable (ι → ℕ),
let e : ℕ → (ι → ℕ) := λ n, (decode (ι → ℕ) n).iget,
refine ⟨λ n, pi univ (λ i, s i (e n i)), λ n, mem_image_of_mem _ (λ i _, h1s i _), _⟩,
simp_rw [(surjective_decode_iget (ι → ℕ)).Union_comp (λ x, pi univ (λ i, s i (x i))),
Union_univ_pi s, h2s, pi_univ]
end
/-- The product of generated σ-algebras is the one generated by boxes, if both generating sets
are countably spanning. -/
lemma generate_from_pi_eq {C : Π i, set (set (α i))}
(hC : ∀ i, is_countably_spanning (C i)) :
@measurable_space.pi _ _ (λ i, generate_from (C i)) = generate_from (pi univ '' pi univ C) :=
begin
casesI nonempty_encodable ι,
apply le_antisymm,
{ refine supr_le _, intro i, rw [comap_generate_from],
apply generate_from_le, rintro _ ⟨s, hs, rfl⟩, dsimp,
choose t h1t h2t using hC,
simp_rw [eval_preimage, ← h2t],
rw [← @Union_const _ ℕ _ s],
have : (pi univ (update (λ (i' : ι), Union (t i')) i (⋃ (i' : ℕ), s))) =
(pi univ (λ k, ⋃ j : ℕ, @update ι (λ i', set (α i')) _ (λ i', t i' j) i s k)),
{ ext, simp_rw [mem_univ_pi], apply forall_congr, intro i',
by_cases (i' = i), { subst h, simp }, { rw [← ne.def] at h, simp [h] }},
rw [this, ← Union_univ_pi],
apply measurable_set.Union,
intro n, apply measurable_set_generate_from,
apply mem_image_of_mem, intros j _, dsimp only,
by_cases h: j = i, subst h, rwa [update_same], rw [update_noteq h], apply h1t },
{ apply generate_from_le, rintro _ ⟨s, hs, rfl⟩,
rw [univ_pi_eq_Inter], apply measurable_set.Inter, intro i, apply measurable_pi_apply,
exact measurable_set_generate_from (hs i (mem_univ i)) }
end
/-- If `C` and `D` generate the σ-algebras on `α` resp. `β`, then rectangles formed by `C` and `D`
generate the σ-algebra on `α × β`. -/
lemma generate_from_eq_pi [h : Π i, measurable_space (α i)]
{C : Π i, set (set (α i))} (hC : ∀ i, generate_from (C i) = h i)
(h2C : ∀ i, is_countably_spanning (C i)) :
generate_from (pi univ '' pi univ C) = measurable_space.pi :=
by rw [← funext hC, generate_from_pi_eq h2C]
/-- The product σ-algebra is generated from boxes, i.e. `s ×ˢ t` for sets `s : set α` and
`t : set β`. -/
lemma generate_from_pi [Π i, measurable_space (α i)] :
generate_from (pi univ '' pi univ (λ i, { s : set (α i) | measurable_set s})) =
measurable_space.pi :=
generate_from_eq_pi (λ i, generate_from_measurable_set) (λ i, is_countably_spanning_measurable_set)
end finite
namespace measure_theory
variables [fintype ι] {m : Π i, outer_measure (α i)}
/-- An upper bound for the measure in a finite product space.
It is defined to by taking the image of the set under all projections, and taking the product
of the measures of these images.
For measurable boxes it is equal to the correct measure. -/
@[simp] def pi_premeasure (m : Π i, outer_measure (α i)) (s : set (Π i, α i)) : ℝ≥0∞ :=
∏ i, m i (eval i '' s)
lemma pi_premeasure_pi {s : Π i, set (α i)} (hs : (pi univ s).nonempty) :
pi_premeasure m (pi univ s) = ∏ i, m i (s i) :=
by simp [hs]
lemma pi_premeasure_pi' {s : Π i, set (α i)} :
pi_premeasure m (pi univ s) = ∏ i, m i (s i) :=
begin
casesI is_empty_or_nonempty ι,
{ simp, },
cases (pi univ s).eq_empty_or_nonempty with h h,
{ rcases univ_pi_eq_empty_iff.mp h with ⟨i, hi⟩,
have : ∃ i, m i (s i) = 0 := ⟨i, by simp [hi]⟩,
simpa [h, finset.card_univ, zero_pow (fintype.card_pos_iff.mpr ‹_›),
@eq_comm _ (0 : ℝ≥0∞), finset.prod_eq_zero_iff] },
{ simp [h] }
end
lemma pi_premeasure_pi_mono {s t : set (Π i, α i)} (h : s ⊆ t) :
pi_premeasure m s ≤ pi_premeasure m t :=
finset.prod_le_prod' (λ i _, (m i).mono' (image_subset _ h))
lemma pi_premeasure_pi_eval {s : set (Π i, α i)} :
pi_premeasure m (pi univ (λ i, eval i '' s)) = pi_premeasure m s :=
by simp [pi_premeasure_pi']
namespace outer_measure
/-- `outer_measure.pi m` is the finite product of the outer measures `{m i | i : ι}`.
It is defined to be the maximal outer measure `n` with the property that
`n (pi univ s) ≤ ∏ i, m i (s i)`, where `pi univ s` is the product of the sets
`{s i | i : ι}`. -/
protected def pi (m : Π i, outer_measure (α i)) : outer_measure (Π i, α i) :=
bounded_by (pi_premeasure m)
lemma pi_pi_le (m : Π i, outer_measure (α i)) (s : Π i, set (α i)) :
outer_measure.pi m (pi univ s) ≤ ∏ i, m i (s i) :=
by { cases (pi univ s).eq_empty_or_nonempty with h h, simp [h],
exact (bounded_by_le _).trans_eq (pi_premeasure_pi h) }
lemma le_pi {m : Π i, outer_measure (α i)} {n : outer_measure (Π i, α i)} :
n ≤ outer_measure.pi m ↔ ∀ (s : Π i, set (α i)), (pi univ s).nonempty →
n (pi univ s) ≤ ∏ i, m i (s i) :=
begin
rw [outer_measure.pi, le_bounded_by'], split,
{ intros h s hs, refine (h _ hs).trans_eq (pi_premeasure_pi hs) },
{ intros h s hs, refine le_trans (n.mono $ subset_pi_eval_image univ s) (h _ _),
simp [univ_pi_nonempty_iff, hs] }
end
end outer_measure
namespace measure
variables [Π i, measurable_space (α i)] (μ : Π i, measure (α i))
section tprod
open list
variables {δ : Type*} {π : δ → Type*} [∀ x, measurable_space (π x)]
/-- A product of measures in `tprod α l`. -/
-- for some reason the equation compiler doesn't like this definition
protected def tprod (l : list δ) (μ : Π i, measure (π i)) : measure (tprod π l) :=
by { induction l with i l ih, exact dirac punit.star, exact (μ i).prod ih }
@[simp] lemma tprod_nil (μ : Π i, measure (π i)) : measure.tprod [] μ = dirac punit.star := rfl
@[simp] lemma tprod_cons (i : δ) (l : list δ) (μ : Π i, measure (π i)) :
measure.tprod (i :: l) μ = (μ i).prod (measure.tprod l μ) := rfl
instance sigma_finite_tprod (l : list δ) (μ : Π i, measure (π i)) [∀ i, sigma_finite (μ i)] :
sigma_finite (measure.tprod l μ) :=
begin
induction l with i l ih,
{ rw [tprod_nil], apply_instance },
{ rw [tprod_cons], resetI, apply_instance }
end
lemma tprod_tprod (l : list δ) (μ : Π i, measure (π i)) [∀ i, sigma_finite (μ i)]
(s : Π i, set (π i)) :
measure.tprod l μ (set.tprod l s) = (l.map (λ i, (μ i) (s i))).prod :=
begin
induction l with i l ih, { simp },
rw [tprod_cons, set.tprod, prod_prod, map_cons, prod_cons, ih]
end
end tprod
section encodable
open list measurable_equiv
variables [encodable ι]
/-- The product measure on an encodable finite type, defined by mapping `measure.tprod` along the
equivalence `measurable_equiv.pi_measurable_equiv_tprod`.
The definition `measure_theory.measure.pi` should be used instead of this one. -/
def pi' : measure (Π i, α i) :=
measure.map (tprod.elim' mem_sorted_univ) (measure.tprod (sorted_univ ι) μ)
lemma pi'_pi [∀ i, sigma_finite (μ i)] (s : Π i, set (α i)) : pi' μ (pi univ s) = ∏ i, μ i (s i) :=
by rw [pi', ← measurable_equiv.pi_measurable_equiv_tprod_symm_apply, measurable_equiv.map_apply,
measurable_equiv.pi_measurable_equiv_tprod_symm_apply, elim_preimage_pi, tprod_tprod _ μ,
← list.prod_to_finset, sorted_univ_to_finset]; exact sorted_univ_nodup ι
end encodable
lemma pi_caratheodory :
measurable_space.pi ≤ (outer_measure.pi (λ i, (μ i).to_outer_measure)).caratheodory :=
begin
refine supr_le _,
intros i s hs,
rw [measurable_space.comap] at hs,
rcases hs with ⟨s, hs, rfl⟩,
apply bounded_by_caratheodory,
intro t,
simp_rw [pi_premeasure],
refine finset.prod_add_prod_le' (finset.mem_univ i) _ _ _,
{ simp [image_inter_preimage, image_diff_preimage, measure_inter_add_diff _ hs, le_refl] },
{ rintro j - hj, apply mono', apply image_subset, apply inter_subset_left },
{ rintro j - hj, apply mono', apply image_subset, apply diff_subset }
end
/-- `measure.pi μ` is the finite product of the measures `{μ i | i : ι}`.
It is defined to be measure corresponding to `measure_theory.outer_measure.pi`. -/
@[irreducible] protected def pi : measure (Π i, α i) :=
to_measure (outer_measure.pi (λ i, (μ i).to_outer_measure)) (pi_caratheodory μ)
lemma pi_pi_aux [∀ i, sigma_finite (μ i)] (s : Π i, set (α i)) (hs : ∀ i, measurable_set (s i)) :
measure.pi μ (pi univ s) = ∏ i, μ i (s i) :=
begin
refine le_antisymm _ _,
{ rw [measure.pi, to_measure_apply _ _ (measurable_set.pi countable_univ (λ i _, hs i))],
apply outer_measure.pi_pi_le },
{ haveI : encodable ι := fintype.to_encodable ι,
rw [← pi'_pi μ s],
simp_rw [← pi'_pi μ s, measure.pi, to_measure_apply _ _ (measurable_set.pi countable_univ
(λ i _, hs i)), ← to_outer_measure_apply],
suffices : (pi' μ).to_outer_measure ≤ outer_measure.pi (λ i, (μ i).to_outer_measure),
{ exact this _ },
clear hs s,
rw [outer_measure.le_pi],
intros s hs,
simp_rw [to_outer_measure_apply],
exact (pi'_pi μ s).le }
end
variable {μ}
/-- `measure.pi μ` has finite spanning sets in rectangles of finite spanning sets. -/
def finite_spanning_sets_in.pi {C : Π i, set (set (α i))}
(hμ : ∀ i, (μ i).finite_spanning_sets_in (C i)) :
(measure.pi μ).finite_spanning_sets_in (pi univ '' pi univ C) :=
begin
haveI := λ i, (hμ i).sigma_finite,
haveI := fintype.to_encodable ι,
refine ⟨λ n, pi univ (λ i, (hμ i).set ((decode (ι → ℕ) n).iget i)), λ n, _, λ n, _, _⟩;
-- TODO (kmill) If this let comes before the refine, while the noncomputability checker
-- correctly sees this definition is computable, the Lean VM fails to see the binding is
-- computationally irrelevant. The `noncomputable theory` doesn't help because all it does
-- is insert `noncomputable` for you when necessary.
let e : ℕ → (ι → ℕ) := λ n, (decode (ι → ℕ) n).iget,
{ refine mem_image_of_mem _ (λ i _, (hμ i).set_mem _) },
{ calc measure.pi μ (pi univ (λ i, (hμ i).set (e n i)))
≤ measure.pi μ (pi univ (λ i, to_measurable (μ i) ((hμ i).set (e n i)))) :
measure_mono (pi_mono $ λ i hi, subset_to_measurable _ _)
... = ∏ i, μ i (to_measurable (μ i) ((hμ i).set (e n i))) :
pi_pi_aux μ _ (λ i, measurable_set_to_measurable _ _)
... = ∏ i, μ i ((hμ i).set (e n i)) :
by simp only [measure_to_measurable]
... < ∞ : ennreal.prod_lt_top (λ i hi, ((hμ i).finite _).ne) },
{ simp_rw [(surjective_decode_iget (ι → ℕ)).Union_comp (λ x, pi univ (λ i, (hμ i).set (x i))),
Union_univ_pi (λ i, (hμ i).set), (hμ _).spanning, set.pi_univ] }
end
/-- A measure on a finite product space equals the product measure if they are equal on rectangles
with as sides sets that generate the corresponding σ-algebras. -/
lemma pi_eq_generate_from {C : Π i, set (set (α i))}
(hC : ∀ i, generate_from (C i) = by apply_assumption)
(h2C : ∀ i, is_pi_system (C i))
(h3C : ∀ i, (μ i).finite_spanning_sets_in (C i))
{μν : measure (Π i, α i)}
(h₁ : ∀ s : Π i, set (α i), (∀ i, s i ∈ C i) → μν (pi univ s) = ∏ i, μ i (s i)) :
measure.pi μ = μν :=
begin
have h4C : ∀ i (s : set (α i)), s ∈ C i → measurable_set s,
{ intros i s hs, rw [← hC], exact measurable_set_generate_from hs },
refine (finite_spanning_sets_in.pi h3C).ext
(generate_from_eq_pi hC (λ i, (h3C i).is_countably_spanning)).symm
(is_pi_system.pi h2C) _,
rintro _ ⟨s, hs, rfl⟩,
rw [mem_univ_pi] at hs,
haveI := λ i, (h3C i).sigma_finite,
simp_rw [h₁ s hs, pi_pi_aux μ s (λ i, h4C i _ (hs i))]
end
variables [∀ i, sigma_finite (μ i)]
/-- A measure on a finite product space equals the product measure if they are equal on
rectangles. -/
lemma pi_eq {μ' : measure (Π i, α i)}
(h : ∀ s : Π i, set (α i), (∀ i, measurable_set (s i)) → μ' (pi univ s) = ∏ i, μ i (s i)) :
measure.pi μ = μ' :=
pi_eq_generate_from (λ i, generate_from_measurable_set)
(λ i, is_pi_system_measurable_set)
(λ i, (μ i).to_finite_spanning_sets_in) h
variables (μ)
lemma pi'_eq_pi [encodable ι] : pi' μ = measure.pi μ :=
eq.symm $ pi_eq $ λ s hs, pi'_pi μ s
@[simp] lemma pi_pi (s : Π i, set (α i)) : measure.pi μ (pi univ s) = ∏ i, μ i (s i) :=
begin
haveI : encodable ι := fintype.to_encodable ι,
rw [← pi'_eq_pi, pi'_pi]
end
lemma pi_univ : measure.pi μ univ = ∏ i, μ i univ := by rw [← pi_univ, pi_pi μ]
lemma pi_ball [∀ i, metric_space (α i)] (x : Π i, α i) {r : ℝ}
(hr : 0 < r) :
measure.pi μ (metric.ball x r) = ∏ i, μ i (metric.ball (x i) r) :=
by rw [ball_pi _ hr, pi_pi]
lemma pi_closed_ball [∀ i, metric_space (α i)] (x : Π i, α i) {r : ℝ}
(hr : 0 ≤ r) :
measure.pi μ (metric.closed_ball x r) = ∏ i, μ i (metric.closed_ball (x i) r) :=
by rw [closed_ball_pi _ hr, pi_pi]
instance pi.sigma_finite : sigma_finite (measure.pi μ) :=
(finite_spanning_sets_in.pi (λ i, (μ i).to_finite_spanning_sets_in)).sigma_finite
lemma pi_of_empty {α : Type*} [is_empty α] {β : α → Type*} {m : Π a, measurable_space (β a)}
(μ : Π a : α, measure (β a)) (x : Π a, β a := is_empty_elim) :
measure.pi μ = dirac x :=
begin
haveI : ∀ a, sigma_finite (μ a) := is_empty_elim,
refine pi_eq (λ s hs, _),
rw [fintype.prod_empty, dirac_apply_of_mem],
exact is_empty_elim
end
lemma pi_eval_preimage_null {i : ι} {s : set (α i)} (hs : μ i s = 0) :
measure.pi μ (eval i ⁻¹' s) = 0 :=
begin
/- WLOG, `s` is measurable -/
rcases exists_measurable_superset_of_null hs with ⟨t, hst, htm, hμt⟩,
suffices : measure.pi μ (eval i ⁻¹' t) = 0,
from measure_mono_null (preimage_mono hst) this,
clear_dependent s,
/- Now rewrite it as `set.pi`, and apply `pi_pi` -/
rw [← univ_pi_update_univ, pi_pi],
apply finset.prod_eq_zero (finset.mem_univ i),
simp [hμt]
end
lemma pi_hyperplane (i : ι) [has_no_atoms (μ i)] (x : α i) :
measure.pi μ {f : Π i, α i | f i = x} = 0 :=
show measure.pi μ (eval i ⁻¹' {x}) = 0,
from pi_eval_preimage_null _ (measure_singleton x)
lemma ae_eval_ne (i : ι) [has_no_atoms (μ i)] (x : α i) :
∀ᵐ y : Π i, α i ∂measure.pi μ, y i ≠ x :=
compl_mem_ae_iff.2 (pi_hyperplane μ i x)
variable {μ}
lemma tendsto_eval_ae_ae {i : ι} : tendsto (eval i) (measure.pi μ).ae (μ i).ae :=
λ s hs, pi_eval_preimage_null μ hs
lemma ae_pi_le_pi : (measure.pi μ).ae ≤ filter.pi (λ i, (μ i).ae) :=
le_infi $ λ i, tendsto_eval_ae_ae.le_comap
lemma ae_eq_pi {β : ι → Type*} {f f' : Π i, α i → β i} (h : ∀ i, f i =ᵐ[μ i] f' i) :
(λ (x : Π i, α i) i, f i (x i)) =ᵐ[measure.pi μ] (λ x i, f' i (x i)) :=
(eventually_all.2 (λ i, tendsto_eval_ae_ae.eventually (h i))).mono $ λ x hx, funext hx
lemma ae_le_pi {β : ι → Type*} [Π i, preorder (β i)] {f f' : Π i, α i → β i}
(h : ∀ i, f i ≤ᵐ[μ i] f' i) :
(λ (x : Π i, α i) i, f i (x i)) ≤ᵐ[measure.pi μ] (λ x i, f' i (x i)) :=
(eventually_all.2 (λ i, tendsto_eval_ae_ae.eventually (h i))).mono $ λ x hx, hx
lemma ae_le_set_pi {I : set ι} {s t : Π i, set (α i)} (h : ∀ i ∈ I, s i ≤ᵐ[μ i] t i) :
(set.pi I s) ≤ᵐ[measure.pi μ] (set.pi I t) :=
((eventually_all_finite I.to_finite).2
(λ i hi, tendsto_eval_ae_ae.eventually (h i hi))).mono $
λ x hst hx i hi, hst i hi $ hx i hi
lemma ae_eq_set_pi {I : set ι} {s t : Π i, set (α i)} (h : ∀ i ∈ I, s i =ᵐ[μ i] t i) :
(set.pi I s) =ᵐ[measure.pi μ] (set.pi I t) :=
(ae_le_set_pi (λ i hi, (h i hi).le)).antisymm (ae_le_set_pi (λ i hi, (h i hi).symm.le))
section intervals
variables {μ} [Π i, partial_order (α i)] [∀ i, has_no_atoms (μ i)]
lemma pi_Iio_ae_eq_pi_Iic {s : set ι} {f : Π i, α i} :
pi s (λ i, Iio (f i)) =ᵐ[measure.pi μ] pi s (λ i, Iic (f i)) :=
ae_eq_set_pi $ λ i hi, Iio_ae_eq_Iic
lemma pi_Ioi_ae_eq_pi_Ici {s : set ι} {f : Π i, α i} :
pi s (λ i, Ioi (f i)) =ᵐ[measure.pi μ] pi s (λ i, Ici (f i)) :=
ae_eq_set_pi $ λ i hi, Ioi_ae_eq_Ici
lemma univ_pi_Iio_ae_eq_Iic {f : Π i, α i} :
pi univ (λ i, Iio (f i)) =ᵐ[measure.pi μ] Iic f :=
by { rw ← pi_univ_Iic, exact pi_Iio_ae_eq_pi_Iic }
lemma univ_pi_Ioi_ae_eq_Ici {f : Π i, α i} :
pi univ (λ i, Ioi (f i)) =ᵐ[measure.pi μ] Ici f :=
by { rw ← pi_univ_Ici, exact pi_Ioi_ae_eq_pi_Ici }
lemma pi_Ioo_ae_eq_pi_Icc {s : set ι} {f g : Π i, α i} :
pi s (λ i, Ioo (f i) (g i)) =ᵐ[measure.pi μ] pi s (λ i, Icc (f i) (g i)) :=
ae_eq_set_pi $ λ i hi, Ioo_ae_eq_Icc
lemma pi_Ioo_ae_eq_pi_Ioc {s : set ι} {f g : Π i, α i} :
pi s (λ i, Ioo (f i) (g i)) =ᵐ[measure.pi μ] pi s (λ i, Ioc (f i) (g i)) :=
ae_eq_set_pi $ λ i hi, Ioo_ae_eq_Ioc
lemma univ_pi_Ioo_ae_eq_Icc {f g : Π i, α i} :
pi univ (λ i, Ioo (f i) (g i)) =ᵐ[measure.pi μ] Icc f g :=
by { rw ← pi_univ_Icc, exact pi_Ioo_ae_eq_pi_Icc }
lemma pi_Ioc_ae_eq_pi_Icc {s : set ι} {f g : Π i, α i} :
pi s (λ i, Ioc (f i) (g i)) =ᵐ[measure.pi μ] pi s (λ i, Icc (f i) (g i)) :=
ae_eq_set_pi $ λ i hi, Ioc_ae_eq_Icc
lemma univ_pi_Ioc_ae_eq_Icc {f g : Π i, α i} :
pi univ (λ i, Ioc (f i) (g i)) =ᵐ[measure.pi μ] Icc f g :=
by { rw ← pi_univ_Icc, exact pi_Ioc_ae_eq_pi_Icc }
lemma pi_Ico_ae_eq_pi_Icc {s : set ι} {f g : Π i, α i} :
pi s (λ i, Ico (f i) (g i)) =ᵐ[measure.pi μ] pi s (λ i, Icc (f i) (g i)) :=
ae_eq_set_pi $ λ i hi, Ico_ae_eq_Icc
lemma univ_pi_Ico_ae_eq_Icc {f g : Π i, α i} :
pi univ (λ i, Ico (f i) (g i)) =ᵐ[measure.pi μ] Icc f g :=
by { rw ← pi_univ_Icc, exact pi_Ico_ae_eq_pi_Icc }
end intervals
/-- If one of the measures `μ i` has no atoms, them `measure.pi µ`
has no atoms. The instance below assumes that all `μ i` have no atoms. -/
lemma pi_has_no_atoms (i : ι) [has_no_atoms (μ i)] :
has_no_atoms (measure.pi μ) :=
⟨λ x, flip measure_mono_null (pi_hyperplane μ i (x i)) (singleton_subset_iff.2 rfl)⟩
instance [h : nonempty ι] [∀ i, has_no_atoms (μ i)] : has_no_atoms (measure.pi μ) :=
h.elim $ λ i, pi_has_no_atoms i
instance [Π i, topological_space (α i)] [∀ i, is_locally_finite_measure (μ i)] :
is_locally_finite_measure (measure.pi μ) :=
begin
refine ⟨λ x, _⟩,
choose s hxs ho hμ using λ i, (μ i).exists_is_open_measure_lt_top (x i),
refine ⟨pi univ s, set_pi_mem_nhds finite_univ (λ i hi, is_open.mem_nhds (ho i) (hxs i)), _⟩,
rw [pi_pi],
exact ennreal.prod_lt_top (λ i _, (hμ i).ne)
end
variable (μ)
@[to_additive] instance pi.is_mul_left_invariant [∀ i, group (α i)] [∀ i, has_measurable_mul (α i)]
[∀ i, is_mul_left_invariant (μ i)] : is_mul_left_invariant (measure.pi μ) :=
begin
refine ⟨λ v, (pi_eq $ λ s hs, _).symm⟩,
rw [map_apply (measurable_const_mul _) (measurable_set.univ_pi hs),
(show (*) v ⁻¹' univ.pi s = univ.pi (λ i, (*) (v i) ⁻¹' s i), by refl), pi_pi],
simp_rw measure_preimage_mul,
end
@[to_additive] instance pi.is_mul_right_invariant [Π i, group (α i)] [∀ i, has_measurable_mul (α i)]
[∀ i, is_mul_right_invariant (μ i)] : is_mul_right_invariant (measure.pi μ) :=
begin
refine ⟨λ v, (pi_eq $ λ s hs, _).symm⟩,
rw [map_apply (measurable_mul_const _) (measurable_set.univ_pi hs),
(show (* v) ⁻¹' univ.pi s = univ.pi (λ i, (* v i) ⁻¹' s i), by refl), pi_pi],
simp_rw measure_preimage_mul_right,
end
@[to_additive] instance pi.is_inv_invariant [∀ i, group (α i)] [∀ i, has_measurable_inv (α i)]
[∀ i, is_inv_invariant (μ i)] : is_inv_invariant (measure.pi μ) :=
begin
refine ⟨(measure.pi_eq (λ s hs, _)).symm⟩,
have A : has_inv.inv ⁻¹' (pi univ s) = set.pi univ (λ i, has_inv.inv ⁻¹' s i),
{ ext, simp },
simp_rw [measure.inv, measure.map_apply measurable_inv (measurable_set.univ_pi hs), A,
pi_pi, measure_preimage_inv]
end
instance pi.is_open_pos_measure [Π i, topological_space (α i)] [Π i, is_open_pos_measure (μ i)] :
is_open_pos_measure (measure_theory.measure.pi μ) :=
begin
constructor,
rintros U U_open ⟨a, ha⟩,
obtain ⟨s, ⟨hs, hsU⟩⟩ := is_open_pi_iff'.1 U_open a ha,
refine ne_of_gt (lt_of_lt_of_le _ (measure_mono hsU)),
simp only [pi_pi],
rw canonically_ordered_comm_semiring.prod_pos,
intros i _,
apply ((hs i).1.measure_pos (μ i) ⟨a i, (hs i).2⟩),
end
instance pi.is_finite_measure_on_compacts [Π i, topological_space (α i)]
[Π i, is_finite_measure_on_compacts (μ i)] :
is_finite_measure_on_compacts (measure_theory.measure.pi μ) :=
begin
constructor,
intros K hK,
suffices : measure.pi μ (set.univ.pi ( λ j, (function.eval j) '' K)) < ⊤,
{ exact lt_of_le_of_lt (measure_mono (univ.subset_pi_eval_image K)) this, },
rw measure.pi_pi,
refine with_top.prod_lt_top _,
exact λ i _, ne_of_lt (is_compact.measure_lt_top (is_compact.image hK (continuous_apply i))),
end
@[to_additive]
instance pi.is_haar_measure [Π i, group (α i)] [Π i, topological_space (α i)]
[Π i, is_haar_measure (μ i)] [Π i, has_measurable_mul (α i)] :
is_haar_measure (measure.pi μ) := {}
end measure
instance measure_space.pi [Π i, measure_space (α i)] : measure_space (Π i, α i) :=
⟨measure.pi (λ i, volume)⟩
lemma volume_pi [Π i, measure_space (α i)] :
(volume : measure (Π i, α i)) = measure.pi (λ i, volume) :=
rfl
lemma volume_pi_pi [Π i, measure_space (α i)] [∀ i, sigma_finite (volume : measure (α i))]
(s : Π i, set (α i)) :
volume (pi univ s) = ∏ i, volume (s i) :=
measure.pi_pi (λ i, volume) s
lemma volume_pi_ball [Π i, measure_space (α i)] [∀ i, sigma_finite (volume : measure (α i))]
[∀ i, metric_space (α i)] (x : Π i, α i) {r : ℝ} (hr : 0 < r) :
volume (metric.ball x r) = ∏ i, volume (metric.ball (x i) r) :=
measure.pi_ball _ _ hr
lemma volume_pi_closed_ball [Π i, measure_space (α i)] [∀ i, sigma_finite (volume : measure (α i))]
[∀ i, metric_space (α i)] (x : Π i, α i) {r : ℝ} (hr : 0 ≤ r) :
volume (metric.closed_ball x r) = ∏ i, volume (metric.closed_ball (x i) r) :=
measure.pi_closed_ball _ _ hr
open measure
/-- We intentionally restrict this only to the nondependent function space, since type-class
inference cannot find an instance for `ι → ℝ` when this is stated for dependent function spaces. -/
@[to_additive "We intentionally restrict this only to the nondependent function space, since
type-class inference cannot find an instance for `ι → ℝ` when this is stated for dependent function
spaces."]
instance pi.is_mul_left_invariant_volume {α} [group α] [measure_space α]
[sigma_finite (volume : measure α)]
[has_measurable_mul α] [is_mul_left_invariant (volume : measure α)] :
is_mul_left_invariant (volume : measure (ι → α)) :=
pi.is_mul_left_invariant _
/-- We intentionally restrict this only to the nondependent function space, since type-class
inference cannot find an instance for `ι → ℝ` when this is stated for dependent function spaces. -/
@[to_additive "We intentionally restrict this only to the nondependent function space, since
type-class inference cannot find an instance for `ι → ℝ` when this is stated for dependent function
spaces."]
instance pi.is_inv_invariant_volume {α} [group α] [measure_space α]
[sigma_finite (volume : measure α)]
[has_measurable_inv α] [is_inv_invariant (volume : measure α)] :
is_inv_invariant (volume : measure (ι → α)) :=
pi.is_inv_invariant _
/-!
### Measure preserving equivalences
In this section we prove that some measurable equivalences (e.g., between `fin 1 → α` and `α` or
between `fin 2 → α` and `α × α`) preserve measure or volume. These lemmas can be used to prove that
measures of corresponding sets (images or preimages) have equal measures and functions `f ∘ e` and
`f` have equal integrals, see lemmas in the `measure_theory.measure_preserving` prefix.
-/
section measure_preserving
lemma measure_preserving_pi_equiv_pi_subtype_prod {ι : Type u} {α : ι → Type v} [fintype ι]
{m : Π i, measurable_space (α i)} (μ : Π i, measure (α i)) [∀ i, sigma_finite (μ i)]
(p : ι → Prop) [decidable_pred p] :
measure_preserving (measurable_equiv.pi_equiv_pi_subtype_prod α p) (measure.pi μ)
((measure.pi $ λ i : subtype p, μ i).prod (measure.pi $ λ i, μ i)) :=
begin
set e := (measurable_equiv.pi_equiv_pi_subtype_prod α p).symm,
refine measure_preserving.symm e _,
refine ⟨e.measurable, (pi_eq $ λ s hs, _).symm⟩,
have : e ⁻¹' (pi univ s) =
(pi univ (λ i : {i // p i}, s i)) ×ˢ (pi univ (λ i : {i // ¬p i}, s i)),
from equiv.preimage_pi_equiv_pi_subtype_prod_symm_pi p s,
rw [e.map_apply, this, prod_prod, pi_pi, pi_pi],
exact fintype.prod_subtype_mul_prod_subtype p (λ i, μ i (s i))
end
lemma volume_preserving_pi_equiv_pi_subtype_prod {ι : Type*} (α : ι → Type*) [fintype ι]
[Π i, measure_space (α i)] [∀ i, sigma_finite (volume : measure (α i))]
(p : ι → Prop) [decidable_pred p] :
measure_preserving (measurable_equiv.pi_equiv_pi_subtype_prod α p) :=
measure_preserving_pi_equiv_pi_subtype_prod (λ i, volume) p
lemma measure_preserving_pi_fin_succ_above_equiv {n : ℕ} {α : fin (n + 1) → Type u}
{m : Π i, measurable_space (α i)} (μ : Π i, measure (α i)) [∀ i, sigma_finite (μ i)]
(i : fin (n + 1)) :
measure_preserving (measurable_equiv.pi_fin_succ_above_equiv α i) (measure.pi μ)
((μ i).prod $ measure.pi $ λ j, μ (i.succ_above j)) :=
begin
set e := (measurable_equiv.pi_fin_succ_above_equiv α i).symm,
refine measure_preserving.symm e _,
refine ⟨e.measurable, (pi_eq $ λ s hs, _).symm⟩,
rw [e.map_apply, i.prod_univ_succ_above _, ← pi_pi, ← prod_prod],
congr' 1 with ⟨x, f⟩,
simp [i.forall_iff_succ_above]
end
lemma volume_preserving_pi_fin_succ_above_equiv {n : ℕ} (α : fin (n + 1) → Type u)
[Π i, measure_space (α i)] [∀ i, sigma_finite (volume : measure (α i))] (i : fin (n + 1)) :
measure_preserving (measurable_equiv.pi_fin_succ_above_equiv α i) :=
measure_preserving_pi_fin_succ_above_equiv (λ _, volume) i
lemma measure_preserving_fun_unique {β : Type u} {m : measurable_space β} (μ : measure β)
(α : Type v) [unique α] :
measure_preserving (measurable_equiv.fun_unique α β) (measure.pi (λ a : α, μ)) μ :=
begin
set e := measurable_equiv.fun_unique α β,
have : pi_premeasure (λ _ : α, μ.to_outer_measure) = measure.map e.symm μ,
{ ext1 s,
rw [pi_premeasure, fintype.prod_unique, to_outer_measure_apply, e.symm.map_apply],
congr' 1, exact e.to_equiv.image_eq_preimage s },
simp only [measure.pi, outer_measure.pi, this, bounded_by_measure, to_outer_measure_to_measure],
exact (e.symm.measurable.measure_preserving _).symm e.symm
end
lemma volume_preserving_fun_unique (α : Type u) (β : Type v) [unique α] [measure_space β] :
measure_preserving (measurable_equiv.fun_unique α β) volume volume :=
measure_preserving_fun_unique volume α
lemma measure_preserving_pi_fin_two {α : fin 2 → Type u} {m : Π i, measurable_space (α i)}
(μ : Π i, measure (α i)) [∀ i, sigma_finite (μ i)] :
measure_preserving (measurable_equiv.pi_fin_two α) (measure.pi μ) ((μ 0).prod (μ 1)) :=
begin
refine ⟨measurable_equiv.measurable _, (measure.prod_eq $ λ s t hs ht, _).symm⟩,
rw [measurable_equiv.map_apply, measurable_equiv.pi_fin_two_apply, fin.preimage_apply_01_prod,
measure.pi_pi, fin.prod_univ_two],
refl
end
lemma volume_preserving_pi_fin_two (α : fin 2 → Type u) [Π i, measure_space (α i)]
[∀ i, sigma_finite (volume : measure (α i))] :
measure_preserving (measurable_equiv.pi_fin_two α) volume volume :=
measure_preserving_pi_fin_two _
lemma measure_preserving_fin_two_arrow_vec {α : Type u} {m : measurable_space α}
(μ ν : measure α) [sigma_finite μ] [sigma_finite ν] :
measure_preserving measurable_equiv.fin_two_arrow (measure.pi ![μ, ν]) (μ.prod ν) :=
begin
haveI : ∀ i, sigma_finite (![μ, ν] i) := fin.forall_fin_two.2 ⟨‹_›, ‹_›⟩,
exact measure_preserving_pi_fin_two _
end
lemma measure_preserving_fin_two_arrow {α : Type u} {m : measurable_space α}
(μ : measure α) [sigma_finite μ] :
measure_preserving measurable_equiv.fin_two_arrow (measure.pi (λ _, μ)) (μ.prod μ) :=
by simpa only [matrix.vec_single_eq_const, matrix.vec_cons_const]
using measure_preserving_fin_two_arrow_vec μ μ
lemma volume_preserving_fin_two_arrow (α : Type u) [measure_space α]
[sigma_finite (volume : measure α)] :
measure_preserving (@measurable_equiv.fin_two_arrow α _) volume volume :=
measure_preserving_fin_two_arrow volume
lemma measure_preserving_pi_empty {ι : Type u} {α : ι → Type v} [is_empty ι]
{m : Π i, measurable_space (α i)} (μ : Π i, measure (α i)) :
measure_preserving (measurable_equiv.of_unique_of_unique (Π i, α i) unit)
(measure.pi μ) (measure.dirac ()) :=
begin
set e := (measurable_equiv.of_unique_of_unique (Π i, α i) unit),
refine ⟨e.measurable, _⟩,
rw [measure.pi_of_empty, measure.map_dirac e.measurable], refl
end
lemma volume_preserving_pi_empty {ι : Type u} (α : ι → Type v) [is_empty ι]
[Π i, measure_space (α i)] :
measure_preserving (measurable_equiv.of_unique_of_unique (Π i, α i) unit) volume volume :=
measure_preserving_pi_empty (λ _, volume)
end measure_preserving
end measure_theory
|
09d247c7b33e9b3b0d7b7c6c9d972d0ce8bbefcf | 8cb37a089cdb4af3af9d8bf1002b417e407a8e9e | /library/init/data/default.lean | b594f46583b76045146179587beccd4f1eab2bf9 | [
"Apache-2.0"
] | permissive | kbuzzard/lean | ae3c3db4bb462d750dbf7419b28bafb3ec983ef7 | ed1788fd674bb8991acffc8fca585ec746711928 | refs/heads/master | 1,620,983,366,617 | 1,618,937,600,000 | 1,618,937,600,000 | 359,886,396 | 1 | 0 | Apache-2.0 | 1,618,936,987,000 | 1,618,936,987,000 | null | UTF-8 | Lean | false | false | 505 | 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.basic init.data.sigma init.data.nat init.data.char init.data.string
import init.data.list init.data.sum init.data.subtype init.data.int init.data.array
import init.data.bool init.data.fin init.data.unsigned init.data.ordering
import init.data.rbtree init.data.rbmap init.data.option.basic init.data.option.instances
|
492c83354c8c6fc1019e3246aa8b22d632411445 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/topology/algebra/field.lean | e31339c795c4bdc901aef8dc55f3ab0aec6c0fb7 | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 4,640 | lean | /-
Copyright (c) 2021 Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot, Scott Morrison
-/
import topology.algebra.ring
import topology.algebra.group_with_zero
/-!
# Topological fields
A topological division ring is a topological ring whose inversion function is continuous at every
non-zero element.
-/
namespace topological_ring
open topological_space function
variables (R : Type*) [semiring R]
variables [topological_space R]
/-- The induced topology on units of a topological semiring.
This is not a global instance since other topologies could be relevant. Instead there is a class
`induced_units` asserting that something equivalent to this construction holds. -/
def topological_space_units : topological_space Rˣ := induced (coe : Rˣ → R) ‹_›
/-- Asserts the topology on units is the induced topology.
Note: this is not always the correct topology.
Another good candidate is the subspace topology of $R \times R$,
with the units embedded via $u \mapsto (u, u^{-1})$.
These topologies are not (propositionally) equal in general. -/
class induced_units [t : topological_space $ Rˣ] : Prop :=
(top_eq : t = induced (coe : Rˣ → R) ‹_›)
variables [topological_space $ Rˣ]
lemma units_topology_eq [induced_units R] :
‹topological_space Rˣ› = induced (coe : Rˣ → R) ‹_› :=
induced_units.top_eq
lemma induced_units.continuous_coe [induced_units R] : continuous (coe : Rˣ → R) :=
(units_topology_eq R).symm ▸ continuous_induced_dom
lemma units_embedding [induced_units R] :
embedding (coe : Rˣ → R) :=
{ induced := units_topology_eq R,
inj := λ x y h, units.ext h }
instance top_monoid_units [topological_semiring R] [induced_units R] :
has_continuous_mul Rˣ :=
⟨begin
let mulR := (λ (p : R × R), p.1*p.2),
let mulRx := (λ (p : Rˣ × Rˣ), p.1*p.2),
have key : coe ∘ mulRx = mulR ∘ (λ p, (p.1.val, p.2.val)), from rfl,
rw [continuous_iff_le_induced, units_topology_eq R, prod_induced_induced,
induced_compose, key, ← induced_compose],
apply induced_mono,
rw ← continuous_iff_le_induced,
exact continuous_mul,
end⟩
end topological_ring
variables (K : Type*) [division_ring K] [topological_space K]
/-- A topological division ring is a division ring with a topology where all operations are
continuous, including inversion. -/
class topological_division_ring extends topological_ring K, has_continuous_inv₀ K : Prop
namespace topological_division_ring
open filter set
/-!
In this section, we show that units of a topological division ring endowed with the
induced topology form a topological group. These are not global instances because
one could want another topology on units. To turn on this feature, use:
```lean
local attribute [instance]
topological_semiring.topological_space_units topological_division_ring.units_top_group
```
-/
local attribute [instance] topological_ring.topological_space_units
@[priority 100] instance induced_units : topological_ring.induced_units K := ⟨rfl⟩
variables [topological_division_ring K]
lemma units_top_group : topological_group Kˣ :=
{ continuous_inv := begin
have : (coe : Kˣ → K) ∘ (λ x, x⁻¹ : Kˣ → Kˣ) =
(λ x, x⁻¹ : K → K) ∘ (coe : Kˣ → K), from funext units.coe_inv',
rw continuous_iff_continuous_at,
intros x,
rw [continuous_at, nhds_induced, nhds_induced, tendsto_iff_comap, comap_comm this],
apply comap_mono,
rw [← tendsto_iff_comap, units.coe_inv'],
exact continuous_at_inv₀ x.ne_zero
end ,
..topological_ring.top_monoid_units K}
local attribute [instance] units_top_group
lemma continuous_units_inv : continuous (λ x : Kˣ, (↑(x⁻¹) : K)) :=
(topological_ring.induced_units.continuous_coe K).comp continuous_inv
end topological_division_ring
section affine_homeomorph
/-!
This section is about affine homeomorphisms from a topological field `𝕜` to itself.
Technically it does not require `𝕜` to be a topological field, a topological ring that
happens to be a field is enough.
-/
variables {𝕜 : Type*} [field 𝕜] [topological_space 𝕜] [topological_ring 𝕜]
/--
The map `λ x, a * x + b`, as a homeomorphism from `𝕜` (a topological field) to itself, when `a ≠ 0`.
-/
@[simps]
def affine_homeomorph (a b : 𝕜) (h : a ≠ 0) : 𝕜 ≃ₜ 𝕜 :=
{ to_fun := λ x, a * x + b,
inv_fun := λ y, (y - b) / a,
left_inv := λ x, by { simp only [add_sub_cancel], exact mul_div_cancel_left x h, },
right_inv := λ y, by { simp [mul_div_cancel' _ h], }, }
end affine_homeomorph
|
d2b9ebb6c9027f818e3b4f0376d6481d6e1ad9e2 | 9dd3f3912f7321eb58ee9aa8f21778ad6221f87c | /tests/lean/curly_notation.lean | 408f5dba104f3b2da38151eb9fb934529afd42a8 | [
"Apache-2.0"
] | permissive | bre7k30/lean | de893411bcfa7b3c5572e61b9e1c52951b310aa4 | 5a924699d076dab1bd5af23a8f910b433e598d7a | refs/heads/master | 1,610,900,145,817 | 1,488,006,845,000 | 1,488,006,845,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 467 | lean | check ({1, 2, 3} : set nat)
check ({1} : set nat)
check ({} : set nat)
definition s1 : set nat := {1, 2+3, 3, 4}
print s1
definition s2 : set char := {#"a", #"b", #"c"}
print s2
definition s3 : set string := {"hello", "world"}
print s3
check { a ∈ s1 | a > 1 }
check { a in s1 | a > 1 }
set_option pp.unicode false
check { a ∈ s1 | a > 2 }
definition a := 10
check ({a, a} : set nat)
check ({a, 1, a} : set nat)
check ({a} : set nat)
check { a // a > 0 }
|
003c8daa7de3b9cb25c2c50158889a6346ae1b3a | a44280b79dc85615010e3fbda46abf82c6730fa3 | /library/init/data/rbmap/basic.lean | e0584a5238fe1530d4f0bb27c2b124459cf9afd8 | [
"Apache-2.0"
] | permissive | kodyvajjha/lean4 | 8e1c613248b531d47367ca6e8d97ee1046645aa1 | c8a045d69fac152fd5e3a577f718615cecb9c53d | refs/heads/master | 1,589,684,450,102 | 1,555,200,447,000 | 1,556,139,945,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 8,380 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import init.data.repr init.data.option.basic
universes u v w w'
inductive Rbcolor
| red | black
inductive RBNode (α : Type u) (β : α → Type v)
| leaf {} : RBNode
| node (color : Rbcolor) (lchild : RBNode) (key : α) (val : β key) (rchild : RBNode) : RBNode
namespace RBNode
variables {α : Type u} {β : α → Type v} {σ : Type w}
open Rbcolor Nat
def depth (f : Nat → Nat → Nat) : RBNode α β → Nat
| leaf := 0
| (node _ l _ _ r) := succ (f (depth l) (depth r))
protected def min : RBNode α β → Option (Σ k : α, β k)
| leaf := none
| (node _ leaf k v _) := some ⟨k, v⟩
| (node _ l k v _) := min l
protected def max : RBNode α β → Option (Σ k : α, β k)
| leaf := none
| (node _ _ k v leaf) := some ⟨k, v⟩
| (node _ _ k v r) := max r
@[specialize] def fold (f : σ → Π (k : α), β k → σ) : σ → RBNode α β → σ
| b leaf := b
| b (node _ l k v r) := fold (f (fold b l) k v) r
@[specialize] def mfold {m : Type w → Type w'} [Monad m] (f : σ → Π (k : α), β k → m σ) : σ → RBNode α β → m σ
| b leaf := pure b
| b (node _ l k v r) := do
b ← mfold b l,
b ← f b k v,
mfold b r
@[specialize] def revFold (f : σ → Π (k : α), β k → σ) : σ → RBNode α β → σ
| b leaf := b
| b (node _ l k v r) := revFold (f (revFold b r) k v) l
@[specialize] def all (p : Π k : α, β k → Bool) : RBNode α β → Bool
| leaf := true
| (node _ l k v r) := p k v && all l && all r
@[specialize] def any (p : Π k : α, β k → Bool) : RBNode α β → Bool
| leaf := false
| (node _ l k v r) := p k v || any l || any r
def singleton (k : α) (v : β k) : RBNode α β :=
node red leaf k v leaf
def balance1 : RBNode α β → RBNode α β → RBNode α β
| (node _ _ kv vv t) (node _ (node red l kx vx r₁) ky vy r₂) := node red (node black l kx vx r₁) ky vy (node black r₂ kv vv t)
| (node _ _ kv vv t) (node _ l₁ ky vy (node red l₂ kx vx r)) := node red (node black l₁ ky vy l₂) kx vx (node black r kv vv t)
| (node _ _ kv vv t) (node _ l ky vy r) := node black (node red l ky vy r) kv vv t
| _ _ := leaf -- unreachable
def balance2 : RBNode α β → RBNode α β → RBNode α β
| (node _ t kv vv _) (node _ (node red l kx₁ vx₁ r₁) ky vy r₂) := node red (node black t kv vv l) kx₁ vx₁ (node black r₁ ky vy r₂)
| (node _ t kv vv _) (node _ l₁ ky vy (node red l₂ kx₂ vx₂ r₂)) := node red (node black t kv vv l₁) ky vy (node black l₂ kx₂ vx₂ r₂)
| (node _ t kv vv _) (node _ l ky vy r) := node black t kv vv (node red l ky vy r)
| _ _ := leaf -- unreachable
def isRed : RBNode α β → Bool
| (node red _ _ _ _) := true
| _ := false
section insert
variables (lt : α → α → Bool)
@[specialize] def ins : RBNode α β → Π k : α, β k → RBNode α β
| leaf kx vx := node red leaf kx vx leaf
| (node red a ky vy b) kx vx :=
if lt kx ky then node red (ins a kx vx) ky vy b
else if lt ky kx then node red a ky vy (ins b kx vx)
else node red a kx vx b
| (node black a ky vy b) kx vx :=
if lt kx ky then
if isRed a then balance1 (node black leaf ky vy b) (ins a kx vx)
else node black (ins a kx vx) ky vy b
else if lt ky kx then
if isRed b then balance2 (node black a ky vy leaf) (ins b kx vx)
else node black a ky vy (ins b kx vx)
else
node black a kx vx b
def setBlack : RBNode α β → RBNode α β
| (node _ l k v r) := node black l k v r
| e := e
@[inline] def insert (t : RBNode α β) (k : α) (v : β k) : RBNode α β :=
if isRed t then setBlack (ins lt t k v)
else ins lt t k v
end insert
section membership
variable (lt : α → α → Bool)
@[specialize] def findCore : RBNode α β → Π k : α, Option (Σ k : α, β k)
| leaf x := none
| (node _ a ky vy b) x :=
if lt x ky then findCore a x
else if lt ky x then findCore b x
else some ⟨ky, vy⟩
@[specialize] def find {β : Type v} : RBNode α (λ _, β) → α → Option β
| leaf x := none
| (node _ a ky vy b) x :=
if lt x ky then find a x
else if lt ky x then find b x
else some vy
@[specialize] def lowerBound : RBNode α β → α → Option (Sigma β) → Option (Sigma β)
| leaf x lb := lb
| (node _ a ky vy b) x lb :=
if lt x ky then lowerBound a x lb
else if lt ky x then lowerBound b x (some ⟨ky, vy⟩)
else some ⟨ky, vy⟩
end membership
inductive WellFormed (lt : α → α → Bool) : RBNode α β → Prop
| leafWff : WellFormed leaf
| insertWff {n n' : RBNode α β} {k : α} {v : β k} : WellFormed n → n' = insert lt n k v → WellFormed n'
end RBNode
open RBNode
/- TODO(Leo): define dRBMap -/
def RBMap (α : Type u) (β : Type v) (lt : α → α → Bool) : Type (max u v) :=
{t : RBNode α (λ _, β) // t.WellFormed lt }
@[inline] def mkRBMap (α : Type u) (β : Type v) (lt : α → α → Bool) : RBMap α β lt :=
⟨leaf, WellFormed.leafWff lt⟩
@[inline] def RBMap.empty {α : Type u} {β : Type v} {lt : α → α → Bool} : RBMap α β lt :=
mkRBMap _ _ _
instance (α : Type u) (β : Type v) (lt : α → α → Bool) : HasEmptyc (RBMap α β lt) :=
⟨RBMap.empty⟩
namespace RBMap
variables {α : Type u} {β : Type v} {σ : Type w} {lt : α → α → Bool}
def depth (f : Nat → Nat → Nat) (t : RBMap α β lt) : Nat :=
t.val.depth f
@[inline] def fold (f : σ → α → β → σ) : σ → RBMap α β lt → σ
| b ⟨t, _⟩ := t.fold f b
@[inline] def revFold (f : σ → α → β → σ) : σ → RBMap α β lt → σ
| b ⟨t, _⟩ := t.revFold f b
@[inline] def mfold {m : Type w → Type w'} [Monad m] (f : σ → α → β → m σ) : σ → RBMap α β lt → m σ
| b ⟨t, _⟩ := t.mfold f b
@[inline] def mfor {m : Type w → Type w'} [Monad m] (f : α → β → m σ) (t : RBMap α β lt) : m PUnit :=
t.mfold (λ _ k v, f k v *> pure ⟨⟩) ⟨⟩
@[inline] def isEmpty : RBMap α β lt → Bool
| ⟨leaf, _⟩ := true
| _ := false
@[specialize] def toList : RBMap α β lt → List (α × β)
| ⟨t, _⟩ := t.revFold (λ ps k v, (k, v)::ps) []
@[inline] protected def min : RBMap α β lt → Option (α × β)
| ⟨t, _⟩ :=
match t.min with
| some ⟨k, v⟩ := some (k, v)
| none := none
@[inline] protected def max : RBMap α β lt → Option (α × β)
| ⟨t, _⟩ :=
match t.max with
| some ⟨k, v⟩ := some (k, v)
| none := none
instance [HasRepr α] [HasRepr β] : HasRepr (RBMap α β lt) :=
⟨λ t, "rbmapOf " ++ repr t.toList⟩
@[inline] def insert : RBMap α β lt → α → β → RBMap α β lt
| ⟨t, w⟩ k v := ⟨t.insert lt k v, WellFormed.insertWff w rfl⟩
@[specialize] def ofList : List (α × β) → RBMap α β lt
| [] := mkRBMap _ _ _
| (⟨k,v⟩::xs) := (ofList xs).insert k v
@[inline] def findCore : RBMap α β lt → α → Option (Σ k : α, β)
| ⟨t, _⟩ x := t.findCore lt x
@[inline] def find : RBMap α β lt → α → Option β
| ⟨t, _⟩ x := t.find lt x
/-- (lowerBound k) retrieves the kv pair of the largest key smaller than or equal to `k`,
if it exists. -/
@[inline] def lowerBound : RBMap α β lt → α → Option (Σ k : α, β)
| ⟨t, _⟩ x := t.lowerBound lt x none
@[inline] def contains (t : RBMap α β lt) (a : α) : Bool :=
(t.find a).isSome
@[inline] def fromList (l : List (α × β)) (lt : α → α → Bool) : RBMap α β lt :=
l.foldl (λ r p, r.insert p.1 p.2) (mkRBMap α β lt)
@[inline] def all : RBMap α β lt → (α → β → Bool) → Bool
| ⟨t, _⟩ p := t.all p
@[inline] def any : RBMap α β lt → (α → β → Bool) → Bool
| ⟨t, _⟩ p := t.any p
end RBMap
def rbmapOf {α : Type u} {β : Type v} (l : List (α × β)) (lt : α → α → Bool) : RBMap α β lt :=
RBMap.fromList l lt
|
4477aaca1c4b1e1c8b12eefab1c0b15600434857 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/emptyLcnf.lean | 92ceb6c540426f8e29514a330c02a2ddf844f65b | [
"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 | 155 | lean | import Lean
inductive MyEmpty
def f (x : MyEmpty) : Nat :=
MyEmpty.casesOn x
set_option trace.Compiler.result true
#eval Lean.Compiler.compile #[``f]
|
0df9bd273ad47799026cba03e2ff227cba5fd3ea | bbecf0f1968d1fba4124103e4f6b55251d08e9c4 | /src/data/sym/card.lean | 74e90fc017b509ed7a8b921eea53fafb9e33f8f5 | [
"Apache-2.0"
] | permissive | waynemunro/mathlib | e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552 | 065a70810b5480d584033f7bbf8e0409480c2118 | refs/heads/master | 1,693,417,182,397 | 1,634,644,781,000 | 1,634,644,781,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,207 | lean | /-
Copyright (c) 2021 Yaël Dillies, Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies, Bhavik Mehta
-/
import algebra.big_operators.basic
import data.fintype.card
import data.sym.sym2
/-!
# Stars and bars
In this file, we prove the case `n = 2` of stars and bars.
## Informal statement
If we have `n` objects to put in `k` boxes, we can do so in exactly `(n + k - 1).choose n` ways.
## Formal statement
We can identify the `k` boxes with the elements of a fintype `α` of card `k`. Then placing `n`
elements in those boxes corresponds to choosing how many of each element of `α` appear in a multiset
of card `n`. `sym α n` being the subtype of `multiset α` of multisets of card `n`, writing stars
and bars using types gives
```lean
-- TODO: this lemma is not yet proven
lemma stars_and_bars {α : Type*} [fintype α] (n : ℕ) :
card (sym α n) = (card α + n - 1).choose (card α) := sorry
```
## TODO
Prove the general case of stars and bars.
## Tags
stars and bars
-/
open finset fintype
namespace sym2
variables {α : Type*} [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, nat.mul_sub_left_distrib, 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
protected lemma card [fintype α] :
card (sym2 α) = card α * (card α + 1) / 2 :=
by rw [←fintype.card_congr (@equiv.sum_compl _ is_diag (sym2.is_diag.decidable_pred α)),
fintype.card_sum, card_subtype_diag, card_subtype_not_diag, nat.choose_two_right, add_comm,
←nat.triangle_succ, nat.succ_sub_one, mul_comm]
end sym2
|
989c2da7eac2418b8a8dd71e6f39d564e234c1d3 | 6329dd15b8fd567a4737f2dacd02bd0e8c4b3ae4 | /src/game/world1/level2.lean | 30d4bfd91057ce821174027194acfc7086f84909 | [
"Apache-2.0"
] | permissive | agusakov/mathematics_in_lean_game | 76e455a688a8826b05160c16c0490b9e3d39f071 | ad45fd42148f2203b973537adec7e8a48677ba2a | refs/heads/master | 1,666,147,402,274 | 1,592,119,137,000 | 1,592,119,137,000 | 272,111,226 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,123 | lean | import data.real.basic --imports the real numbers
import tactic.maths_in_lean_game -- hide
namespace calculating -- hide
/-
#Calculating
## Level 2: Proving identities
You can type the `ℝ` character as `\R` or `\real`
in the VS Code editor.
The symbol doesn't appear until you hit space or the tab key.
If you hover over a symbol when reading a Lean file,
VS Code will show you the syntax that can be used to enter it.
If your keyboard does not have a backslash,
you can change the leading character by changing the
`lean.input.leader` setting in VS Code.
Try proving these next two identities,
in each case replacing `sorry` by a tactic proof.
With the `rw` tactic, you can use a left arrow (`\l`)
to reverse an identity.
For example, `rw ← mul_assoc a b c`
replaces `a * (b * c)` by `a * b * c` in the current goal.
-/
/- Lemma : no-side-bar
For all natural numbers $a$, we have
$$a + \operatorname{succ}(0) = \operatorname{succ}(a).$$
-/
lemma example2 (a b c : ℝ) : (c * b) * a = b * (a * c) :=
begin [maths_in_lean_game]
sorry
end
/- Tactic : rw
Description of the tactic
-/
end calculating -- hide |
443b37c2cafa29a6d88ef315e23905afc25039aa | 6bbefddc5d215af92ee0f41cafc343d0802aa6c8 | /16-forall.lean | 5f1b5ee44c340c46cb29b37cc26fa3c4d0ec3b9f | [
"Unlicense"
] | permissive | bradheintz/lean-ex | 0dcfab24e31abd9394247353f4e7dfd06655b2e1 | 37419b8d014ba3ba416e2252809a89a1604a1330 | refs/heads/master | 1,645,696,373,325 | 1,503,243,879,000 | 1,503,243,879,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,222 | lean | namespace forall_conjunct_left
variables (α : Type) (p q : α → Prop)
example : (∀ x : α, p x ∧ q x) → ∀ y : α, p y :=
assume h : ∀ x : α , p x ∧ q x,
take k : α,
show p k, from (h k).left
end forall_conjunct_left
namespace forall_rel_trans
variables (α : Type) (r : α → α → Prop)
variable trans_r : ∀ x y z, r x y → r y z → r x z
variables a b c : α
variables (hab : r a b) (hbc : r b c)
#check trans_r
#check trans_r a b c
#check trans_r a b c hab
#check trans_r a b c hab hbc
end forall_rel_trans
namespace forall_rel_trans_impl
variables (α : Type) (r : α → α → Prop)
variable trans_r : ∀ {x y z}, r x y → r y z → r x z
variables a b c : α
variables (hab : r a b) (hbc : r b c)
#check trans_r
#check trans_r hab
#check trans_r hab hbc
end forall_rel_trans_impl
namespace forall_equiv
variables (α : Type) (r : α → α → Prop)
variable reflex_r : ∀ x, r x x
variable symm_r : ∀ {x y}, r x y → r y x
variable trans_r : ∀ {x y z}, r x y → r y z → r x z
example (a b c d : α) (hab : r a b) (hcb : r c b) (hcd : r c d) : r a d :=
trans_r (trans_r hab (symm_r hcb)) hcd
end forall_equiv |
c5a235984b1af1baf8239f22ac06a4fa4373fe54 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/data/int/cast/basic.lean | 32a9faf7c8004111e91795d60b253f3ae67301cb | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 3,784 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Gabriel Ebner
-/
import data.int.cast.defs
import algebra.group.basic
/-!
# Cast of integers (additional theorems)
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file proves additional properties about the *canonical* homomorphism from
the integers into an additive group with a one (`int.cast`).
There is also `data.int.cast.lemmas`,
which includes lemmas stated in terms of algebraic homomorphisms,
and results involving the order structure of `ℤ`.
By contrast, this file's only import beyond `data.int.cast.defs` is `algebra.group.basic`.
-/
universes u
namespace nat
variables {R : Type u} [add_group_with_one R]
@[simp, norm_cast] theorem cast_sub {m n} (h : m ≤ n) : ((n - m : ℕ) : R) = n - m :=
eq_sub_of_add_eq $ by rw [← cast_add, nat.sub_add_cancel h]
@[simp, norm_cast] theorem cast_pred : ∀ {n}, 0 < n → ((n - 1 : ℕ) : R) = n - 1
| 0 h := by cases h
| (n+1) h := by rw [cast_succ, add_sub_cancel]; refl
end nat
open nat
namespace int
variables {R : Type u} [add_group_with_one R]
@[simp] theorem cast_neg_succ_of_nat (n : ℕ) : (-[1+ n] : R) = -(n + 1 : ℕ) :=
add_group_with_one.int_cast_neg_succ_of_nat n
@[simp, norm_cast] theorem cast_zero : ((0 : ℤ) : R) = 0 := (cast_of_nat 0).trans nat.cast_zero
@[simp, norm_cast] theorem cast_coe_nat (n : ℕ) : ((n : ℤ) : R) = n := cast_of_nat _
@[simp, norm_cast] theorem cast_one : ((1 : ℤ) : R) = 1 :=
show (((1 : ℕ) : ℤ) : R) = 1, by simp
@[simp, norm_cast] theorem cast_neg : ∀ n, ((-n : ℤ) : R) = -n
| (0 : ℕ) := by erw [cast_zero, neg_zero]
| (n + 1 : ℕ) := by erw [cast_of_nat, cast_neg_succ_of_nat]; refl
| -[1+ n] := by erw [cast_of_nat, cast_neg_succ_of_nat, neg_neg]
@[simp] theorem cast_sub_nat_nat (m n) :
((int.sub_nat_nat m n : ℤ) : R) = m - n :=
begin
unfold sub_nat_nat, cases e : n - m,
{ simp only [sub_nat_nat, cast_of_nat], simp [e, nat.le_of_sub_eq_zero e] },
{ rw [sub_nat_nat, cast_neg_succ_of_nat, nat.add_one, ← e,
nat.cast_sub $ _root_.le_of_lt $ nat.lt_of_sub_eq_succ e, neg_sub] },
end
lemma neg_of_nat_eq (n : ℕ) : neg_of_nat n = -(n : ℤ) := by cases n; refl
@[simp] theorem cast_neg_of_nat (n : ℕ) : ((neg_of_nat n : ℤ) : R) = -n :=
by simp [neg_of_nat_eq]
@[simp, norm_cast] theorem cast_add : ∀ m n, ((m + n : ℤ) : R) = m + n
| (m : ℕ) (n : ℕ) := by simp [← int.coe_nat_add]
| (m : ℕ) -[1+ n] := by erw [cast_sub_nat_nat, cast_coe_nat, cast_neg_succ_of_nat, sub_eq_add_neg]
| -[1+ m] (n : ℕ) := by erw [cast_sub_nat_nat, cast_coe_nat, cast_neg_succ_of_nat,
sub_eq_iff_eq_add, add_assoc, eq_neg_add_iff_add_eq, ← nat.cast_add, ← nat.cast_add, nat.add_comm]
| -[1+ m] -[1+ n] := show (-[1+ m + n + 1] : R) = _,
by rw [cast_neg_succ_of_nat, cast_neg_succ_of_nat, cast_neg_succ_of_nat, ← neg_add_rev,
← nat.cast_add, nat.add_right_comm m n 1, nat.add_assoc, nat.add_comm]
@[simp, norm_cast] theorem cast_sub (m n) : ((m - n : ℤ) : R) = m - n :=
by simp [int.sub_eq_add_neg, sub_eq_add_neg]
@[simp, norm_cast]
theorem coe_nat_bit0 (n : ℕ) : (↑(bit0 n) : ℤ) = bit0 ↑n := rfl
@[simp, norm_cast]
theorem coe_nat_bit1 (n : ℕ) : (↑(bit1 n) : ℤ) = bit1 ↑n := rfl
@[simp, norm_cast] theorem cast_bit0 (n : ℤ) : ((bit0 n : ℤ) : R) = bit0 n :=
cast_add _ _
@[simp, norm_cast] theorem cast_bit1 (n : ℤ) : ((bit1 n : ℤ) : R) = bit1 n :=
by rw [bit1, cast_add, cast_one, cast_bit0]; refl
lemma cast_two : ((2 : ℤ) : R) = 2 := by simp
lemma cast_three : ((3 : ℤ) : R) = 3 := by simp
lemma cast_four : ((4 : ℤ) : R) = 4 := by simp
end int
|
c476715ab0f01aa84048d27bbc8a7ca87474f2cd | 9ee042bf34eebe0464f0f80c0db14ceb048dab10 | /stage0/src/Lean/Elab/PreDefinition/WF/Main.lean | 1d7a65424fd89f9272f3e3f3a53e9a6022ffee06 | [
"Apache-2.0"
] | permissive | dexmagic/lean4 | 7507e7b07dc9f49db45df5ebd011886367dc2a6c | 48764b60d5bac337eaff4bf8a3d63a216e1d9e03 | refs/heads/master | 1,692,156,265,016 | 1,633,276,980,000 | 1,633,339,480,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,243 | lean | /-
Copyright (c) 2021 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Elab.PreDefinition.Basic
import Lean.Elab.PreDefinition.WF.TerminationBy
import Lean.Elab.PreDefinition.WF.PackDomain
import Lean.Elab.PreDefinition.WF.PackMutual
import Lean.Elab.PreDefinition.WF.Rel
import Lean.Elab.PreDefinition.WF.Fix
namespace Lean.Elab
open WF
open Meta
private partial def addNonRecPreDefs (preDefs : Array PreDefinition) (preDefNonRec : PreDefinition) : TermElabM Unit := do
let Expr.forallE _ domain _ _ ← preDefNonRec.type | unreachable!
let us := preDefNonRec.levelParams.map mkLevelParam
for fidx in [:preDefs.size] do
let preDef := preDefs[fidx]
let value ← lambdaTelescope preDef.value fun xs _ => do
let mkProd (type : Expr) : MetaM Expr := do
mkUnaryArg type xs
let rec mkSum (i : Nat) (type : Expr) : MetaM Expr := do
if i == preDefs.size - 1 then
mkProd type
else
(← whnfD type).withApp fun f args => do
assert! args.size == 2
if i == fidx then
return mkApp3 (mkConst ``Sum.inl f.constLevels!) args[0] args[1] (← mkProd args[0])
else
let r ← mkSum (i+1) args[1]
return mkApp3 (mkConst ``Sum.inr f.constLevels!) args[0] args[1] r
let arg ← mkSum 0 domain
mkLambdaFVars xs (mkApp (mkConst preDefNonRec.declName us) arg)
trace[Elab.definition.wf] "{preDef.declName} := {value}"
addNonRec { preDef with value }
def wfRecursion (preDefs : Array PreDefinition) (wfStx? : Option Syntax) : TermElabM Unit := do
let unaryPreDef ← withoutModifyingEnv do
for preDef in preDefs do
addAsAxiom preDef
let unaryPreDefs ← packDomain preDefs
packMutual unaryPreDefs
let wfRel ← elabWFRel unaryPreDef wfStx?
let preDefNonRec ← withoutModifyingEnv do
addAsAxiom unaryPreDef
mkFix unaryPreDef wfRel
trace[Elab.definition.wf] ">> {preDefNonRec.declName}"
addNonRec preDefNonRec
addNonRecPreDefs preDefs preDefNonRec
addAndCompilePartialRec preDefs
builtin_initialize registerTraceClass `Elab.definition.wf
end Lean.Elab
|
4dd8489964c99dd7f4a81b6230470177d166cba6 | 2a70b774d16dbdf5a533432ee0ebab6838df0948 | /_target/deps/mathlib/src/category_theory/limits/shapes/constructions/pullbacks.lean | 5604d4218304134b93356c7b750e596f16a502bf | [
"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 | 3,925 | lean | /-
Copyright (c) 2020 Markus Himmel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Markus Himmel
-/
import category_theory.limits.shapes.binary_products
import category_theory.limits.shapes.equalizers
import category_theory.limits.shapes.pullbacks
universes v u
/-!
# Constructing pullbacks from binary products and equalizers
If a category as binary products and equalizers, then it has pullbacks.
Also, if a category has binary coproducts and coequalizers, then it has pushouts
-/
open category_theory
namespace category_theory.limits
/-- If the product `X ⨯ Y` and the equalizer of `π₁ ≫ f` and `π₂ ≫ g` exist, then the
pullback of `f` and `g` exists: It is given by composing the equalizer with the projections. -/
lemma has_limit_cospan_of_has_limit_pair_of_has_limit_parallel_pair
{C : Type u} [𝒞 : category.{v} C] {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) [has_limit (pair X Y)]
[has_limit (parallel_pair (prod.fst ≫ f) (prod.snd ≫ g))] : has_limit (cospan f g) :=
let π₁ : X ⨯ Y ⟶ X := prod.fst, π₂ : X ⨯ Y ⟶ Y := prod.snd, e := equalizer.ι (π₁ ≫ f) (π₂ ≫ g) in
has_limit.mk
{ cone := pullback_cone.mk (e ≫ π₁) (e ≫ π₂) $ by simp only [category.assoc, equalizer.condition],
is_limit := pullback_cone.is_limit.mk _
(λ s, equalizer.lift (prod.lift (s.π.app walking_cospan.left)
(s.π.app walking_cospan.right)) $ by
rw [←category.assoc, limit.lift_π, ←category.assoc, limit.lift_π];
exact pullback_cone.condition _)
(by simp) (by simp) $ λ s m h₁ h₂, by { ext,
{ simpa using h₁ },
{ simpa using h₂ } } }
section
local attribute [instance] has_limit_cospan_of_has_limit_pair_of_has_limit_parallel_pair
/-- If a category has all binary products and all equalizers, then it also has all pullbacks.
As usual, this is not an instance, since there may be a more direct way to construct
pullbacks. -/
lemma has_pullbacks_of_has_binary_products_of_has_equalizers
(C : Type u) [𝒞 : category.{v} C] [has_binary_products C] [has_equalizers C] :
has_pullbacks C :=
{ has_limit := λ F, has_limit_of_iso (diagram_iso_cospan F).symm }
end
/-- If the coproduct `Y ⨿ Z` and the coequalizer of `f ≫ ι₁` and `g ≫ ι₂` exist, then the
pushout of `f` and `g` exists: It is given by composing the inclusions with the coequalizer. -/
lemma has_colimit_span_of_has_colimit_pair_of_has_colimit_parallel_pair
{C : Type u} [𝒞 : category.{v} C] {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) [has_colimit (pair Y Z)]
[has_colimit (parallel_pair (f ≫ coprod.inl) (g ≫ coprod.inr))] : has_colimit (span f g) :=
let ι₁ : Y ⟶ Y ⨿ Z := coprod.inl, ι₂ : Z ⟶ Y ⨿ Z := coprod.inr,
c := coequalizer.π (f ≫ ι₁) (g ≫ ι₂) in
has_colimit.mk
{ cocone := pushout_cocone.mk (ι₁ ≫ c) (ι₂ ≫ c) $
by rw [←category.assoc, ←category.assoc, coequalizer.condition],
is_colimit := pushout_cocone.is_colimit.mk _
(λ s, coequalizer.desc (coprod.desc (s.ι.app walking_span.left)
(s.ι.app walking_span.right)) $ by
rw [category.assoc, colimit.ι_desc, category.assoc, colimit.ι_desc];
exact pushout_cocone.condition _)
(by simp) (by simp) $ λ s m h₁ h₂, by { ext,
{ simpa using h₁ },
{ simpa using h₂ } } }
section
local attribute [instance] has_colimit_span_of_has_colimit_pair_of_has_colimit_parallel_pair
/-- If a category has all binary coproducts and all coequalizers, then it also has all pushouts.
As usual, this is not an instance, since there may be a more direct way to construct
pushouts. -/
lemma has_pushouts_of_has_binary_coproducts_of_has_coequalizers
(C : Type u) [𝒞 : category.{v} C] [has_binary_coproducts C] [has_coequalizers C] :
has_pushouts C :=
has_pushouts_of_has_colimit_span C
end
end category_theory.limits
|
581078ea17ff1ef9b9f88cd99eb525738590fcd3 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/analysis/inner_product_space/linear_pmap.lean | 0613e2dfe34cdffdc337a265320bbdaa9147adb2 | [
"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,481 | lean | /-
Copyright (c) 2022 Moritz Doll. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Moritz Doll
-/
import analysis.inner_product_space.adjoint
import topology.algebra.module.linear_pmap
import topology.algebra.module.basic
/-!
# Partially defined linear operators on Hilbert spaces
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
We will develop the basics of the theory of unbounded operators on Hilbert spaces.
## Main definitions
* `linear_pmap.is_formal_adjoint`: An operator `T` is a formal adjoint of `S` if for all `x` in the
domain of `T` and `y` in the domain of `S`, we have that `⟪T x, y⟫ = ⟪x, S y⟫`.
* `linear_pmap.adjoint`: The adjoint of a map `E →ₗ.[𝕜] F` as a map `F →ₗ.[𝕜] E`.
## Main statements
* `linear_pmap.adjoint_is_formal_adjoint`: The adjoint is a formal adjoint
* `linear_pmap.is_formal_adjoint.le_adjoint`: Every formal adjoint is contained in the adjoint
* `continuous_linear_map.to_pmap_adjoint_eq_adjoint_to_pmap_of_dense`: The adjoint on
`continuous_linear_map` and `linear_pmap` coincide.
## Notation
* For `T : E →ₗ.[𝕜] F` the adjoint can be written as `T†`.
This notation is localized in `linear_pmap`.
## Implementation notes
We use the junk value pattern to define the adjoint for all `linear_pmap`s. In the case that
`T : E →ₗ.[𝕜] F` is not densely defined the adjoint `T†` is the zero map from `T.adjoint_domain` to
`E`.
## References
* [J. Weidmann, *Linear Operators in Hilbert Spaces*][weidmann_linear]
## Tags
Unbounded operators, closed operators
-/
noncomputable theory
open is_R_or_C
open_locale complex_conjugate classical
variables {𝕜 E F G : Type*} [is_R_or_C 𝕜]
variables [normed_add_comm_group E] [inner_product_space 𝕜 E]
variables [normed_add_comm_group F] [inner_product_space 𝕜 F]
local notation `⟪`x`, `y`⟫` := @inner 𝕜 _ _ x y
namespace linear_pmap
/-- An operator `T` is a formal adjoint of `S` if for all `x` in the domain of `T` and `y` in the
domain of `S`, we have that `⟪T x, y⟫ = ⟪x, S y⟫`. -/
def is_formal_adjoint (T : E →ₗ.[𝕜] F) (S : F →ₗ.[𝕜] E) : Prop :=
∀ (x : T.domain) (y : S.domain), ⟪T x, y⟫ = ⟪(x : E), S y⟫
variables {T : E →ₗ.[𝕜] F} {S : F →ₗ.[𝕜] E}
@[protected] lemma is_formal_adjoint.symm (h : T.is_formal_adjoint S) : S.is_formal_adjoint T :=
λ y _, by rw [←inner_conj_symm, ←inner_conj_symm (y : F), h]
variables (T)
/-- The domain of the adjoint operator.
This definition is needed to construct the adjoint operator and the preferred version to use is
`T.adjoint.domain` instead of `T.adjoint_domain`. -/
def adjoint_domain : submodule 𝕜 F :=
{ carrier := {y | continuous ((innerₛₗ 𝕜 y).comp T.to_fun)},
zero_mem' := by { rw [set.mem_set_of_eq, linear_map.map_zero, linear_map.zero_comp],
exact continuous_zero },
add_mem' := λ x y hx hy, by { rw [set.mem_set_of_eq, linear_map.map_add] at *, exact hx.add hy },
smul_mem' := λ a x hx, by { rw [set.mem_set_of_eq, linear_map.map_smulₛₗ] at *,
exact hx.const_smul (conj a) } }
/-- The operator `λ x, ⟪y, T x⟫` considered as a continuous linear operator from `T.adjoint_domain`
to `𝕜`. -/
def adjoint_domain_mk_clm (y : T.adjoint_domain) : T.domain →L[𝕜] 𝕜 :=
⟨(innerₛₗ 𝕜 (y : F)).comp T.to_fun, y.prop⟩
lemma adjoint_domain_mk_clm_apply (y : T.adjoint_domain) (x : T.domain) :
adjoint_domain_mk_clm T y x = ⟪(y : F), T x⟫ := rfl
variable {T}
variable (hT : dense (T.domain : set E))
include hT
/-- The unique continuous extension of the operator `adjoint_domain_mk_clm` to `E`. -/
def adjoint_domain_mk_clm_extend (y : T.adjoint_domain) :
E →L[𝕜] 𝕜 :=
(T.adjoint_domain_mk_clm y).extend (submodule.subtypeL T.domain)
hT.dense_range_coe uniform_embedding_subtype_coe.to_uniform_inducing
@[simp] lemma adjoint_domain_mk_clm_extend_apply (y : T.adjoint_domain) (x : T.domain) :
adjoint_domain_mk_clm_extend hT y (x : E) = ⟪(y : F), T x⟫ :=
continuous_linear_map.extend_eq _ _ _ _ _
variables [complete_space E]
/-- The adjoint as a linear map from its domain to `E`.
This is an auxiliary definition needed to define the adjoint operator as a `linear_pmap` without
the assumption that `T.domain` is dense. -/
def adjoint_aux : T.adjoint_domain →ₗ[𝕜] E :=
{ to_fun := λ y, (inner_product_space.to_dual 𝕜 E).symm (adjoint_domain_mk_clm_extend hT y),
map_add' := λ x y, hT.eq_of_inner_left $ λ _,
by simp only [inner_add_left, submodule.coe_add, inner_product_space.to_dual_symm_apply,
adjoint_domain_mk_clm_extend_apply],
map_smul' := λ _ _, hT.eq_of_inner_left $ λ _,
by simp only [inner_smul_left, submodule.coe_smul_of_tower, ring_hom.id_apply,
inner_product_space.to_dual_symm_apply, adjoint_domain_mk_clm_extend_apply] }
lemma adjoint_aux_inner (y : T.adjoint_domain) (x : T.domain) :
⟪adjoint_aux hT y, x⟫ = ⟪(y : F), T x⟫ :=
by simp only [adjoint_aux, linear_map.coe_mk, inner_product_space.to_dual_symm_apply,
adjoint_domain_mk_clm_extend_apply]
lemma adjoint_aux_unique (y : T.adjoint_domain) {x₀ : E}
(hx₀ : ∀ x : T.domain, ⟪x₀, x⟫ = ⟪(y : F), T x⟫) : adjoint_aux hT y = x₀ :=
hT.eq_of_inner_left (λ v, (adjoint_aux_inner hT _ _).trans (hx₀ v).symm)
omit hT
variable (T)
/-- The adjoint operator as a partially defined linear operator. -/
def adjoint : F →ₗ.[𝕜] E :=
{ domain := T.adjoint_domain,
to_fun := if hT : dense (T.domain : set E) then adjoint_aux hT else 0 }
localized "postfix (name := adjoint) `†`:1100 := linear_pmap.adjoint" in linear_pmap
lemma mem_adjoint_domain_iff (y : F) :
y ∈ T†.domain ↔ continuous ((innerₛₗ 𝕜 y).comp T.to_fun) := iff.rfl
variable {T}
lemma mem_adjoint_domain_of_exists (y : F) (h : ∃ w : E, ∀ (x : T.domain), ⟪w, x⟫ = ⟪y, T x⟫) :
y ∈ T†.domain :=
begin
cases h with w hw,
rw T.mem_adjoint_domain_iff,
have : continuous ((innerSL 𝕜 w).comp T.domain.subtypeL) := by continuity,
convert this using 1,
exact funext (λ x, (hw x).symm),
end
lemma adjoint_apply_of_not_dense (hT : ¬ dense (T.domain : set E)) (y : T†.domain) : T† y = 0 :=
begin
change (if hT : dense (T.domain : set E) then adjoint_aux hT else 0) y = _,
simp only [hT, not_false_iff, dif_neg, linear_map.zero_apply],
end
include hT
lemma adjoint_apply_of_dense (y : T†.domain) : T† y = adjoint_aux hT y :=
begin
change (if hT : dense (T.domain : set E) then adjoint_aux hT else 0) y = _,
simp only [hT, dif_pos, linear_map.coe_mk],
end
lemma adjoint_apply_eq (y : T†.domain) {x₀ : E}
(hx₀ : ∀ x : T.domain, ⟪x₀, x⟫ = ⟪(y : F), T x⟫) : T† y = x₀ :=
(adjoint_apply_of_dense hT y).symm ▸ adjoint_aux_unique hT _ hx₀
/-- The fundamental property of the adjoint. -/
lemma adjoint_is_formal_adjoint : T†.is_formal_adjoint T :=
λ x, (adjoint_apply_of_dense hT x).symm ▸ adjoint_aux_inner hT x
/-- The adjoint is maximal in the sense that it contains every formal adjoint. -/
lemma is_formal_adjoint.le_adjoint (h : T.is_formal_adjoint S) : S ≤ T† :=
-- Trivially, every `x : S.domain` is in `T.adjoint.domain`
⟨λ x hx, mem_adjoint_domain_of_exists _ ⟨S ⟨x, hx⟩, h.symm ⟨x, hx⟩⟩,
-- Equality on `S.domain` follows from equality
-- `⟪v, S x⟫ = ⟪v, T.adjoint y⟫` for all `v : T.domain`:
λ _ _ hxy, (adjoint_apply_eq hT _ (λ _, by rw [h.symm, hxy])).symm⟩
end linear_pmap
namespace continuous_linear_map
variables [complete_space E] [complete_space F]
variables (A : E →L[𝕜] F) {p : submodule 𝕜 E}
/-- Restricting `A` to a dense submodule and taking the `linear_pmap.adjoint` is the same
as taking the `continuous_linear_map.adjoint` interpreted as a `linear_pmap`. -/
lemma to_pmap_adjoint_eq_adjoint_to_pmap_of_dense (hp : dense (p : set E)) :
(A.to_pmap p).adjoint = A.adjoint.to_pmap ⊤ :=
begin
ext,
{ simp only [to_linear_map_eq_coe, linear_map.to_pmap_domain, submodule.mem_top, iff_true,
linear_pmap.mem_adjoint_domain_iff, linear_map.coe_comp, innerₛₗ_apply_coe],
exact ((innerSL 𝕜 x).comp $ A.comp $ submodule.subtypeL _).cont },
intros x y hxy,
refine linear_pmap.adjoint_apply_eq hp _ (λ v, _),
simp only [adjoint_inner_left, hxy, linear_map.to_pmap_apply, to_linear_map_eq_coe, coe_coe],
end
end continuous_linear_map
|
407f4395da1638fd6916aeb50e220b7dda66ac39 | 13d50f9487a2afddb5e1ae1bbe68f7870f70e79a | /Main.lean | ef04b177fec1dc976cc92c4f318ab4462049c363 | [] | no_license | gebner/lean4-mathlib-import | 09a09d9cc30738bcc253e919ab3485e13b8f992d | 719c0558dfa9c4ec201aa40f4786d5f1c1e4bd1e | refs/heads/master | 1,649,553,984,859 | 1,584,121,837,000 | 1,584,121,837,000 | 238,557,672 | 4 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 1,266 | lean | -- new_frontend
import Init.Lean
import Import.ExportParser
import Import.Import
open Lean
def parseExport (fn : String) : IO ExportParserState := do
conts ← IO.FS.readFile fn;
let lines := conts.splitOn "\n";
pure $ lines.foldl ExportParserState.processLine ExportParserState.initial
def parseName (n : String) : Name :=
(n.splitOn ".").foldl mkNameStr Name.anonymous
def parseAttrs (fn : String) : IO (List (Name × Name)) := do
conts ← IO.FS.readFile fn;
let lines := conts.splitOn "\n";
let lines := lines.filter (fun line => line != "");
pure $ lines.map $ fun line =>
match (line.splitOn " ") with
| [attr, decl] => (parseName decl, attr)
| _ => (`has_add, `class) -- dummy
def main (args : List String) : IO UInt32 := do
exportFile ← parseExport (args.get! 0);
attrsFile ← parseAttrs (args.get! 1);
IO.println attrsFile;
let outputOLean := args.get! 2;
-- env0 ← mkEmptyEnvironment;
path ← IO.getEnv "LEAN_PATH";
IO.println path;
initSearchPath path;
env0 ← importModules [{ module := `Init.Default }];
(_, env) ← IO.runMeta (StateT.run (do
exportFile.decls.mapM ImportState.processDecl;
attrsFile.mapM (fun ⟨d,a⟩ => ImportState.addAttr d a)) ImportState.default) env0;
env.displayStats;
writeModule env outputOLean;
pure 0
|
71db2fa0297ee0ef46c71799bb7c61e01692e787 | 32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7 | /src/Lean/Meta/WHNF.lean | 874aec31d9e78364a385b873d71ad15aa4d195e1 | [
"Apache-2.0"
] | permissive | walterhu1015/lean4 | b2c71b688975177402758924eaa513475ed6ce72 | 2214d81e84646a905d0b20b032c89caf89c737ad | refs/heads/master | 1,671,342,096,906 | 1,599,695,985,000 | 1,599,695,985,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 17,659 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.ToExpr
import Lean.AuxRecursor
import Lean.Meta.Basic
import Lean.Meta.LevelDefEq
namespace Lean
namespace Meta
/- ===========================
Smart unfolding support
=========================== -/
def smartUnfoldingSuffix := "_sunfold"
@[inline] def mkSmartUnfoldingNameFor (n : Name) : Name :=
mkNameStr n smartUnfoldingSuffix
/- ===========================
Helper methods
=========================== -/
variables {m : Type → Type} [MonadLiftT MetaM m]
private def isAuxDefImp? (constName : Name) : MetaM Bool := do
env ← getEnv; pure (isAuxRecursor env constName || isNoConfusion env constName)
@[inline] def isAuxDef? (constName : Name) : m Bool :=
liftMetaM $ isAuxDefImp? constName
@[inline] private def matchConstAux {α} (e : Expr) (failK : Unit → MetaM α) (k : ConstantInfo → List Level → MetaM α) : MetaM α :=
match e with
| Expr.const name lvls _ => do
(some cinfo) ← getConst? name | failK ();
k cinfo lvls
| _ => failK ()
/- ===========================
Helper functions for reducing recursors
=========================== -/
private def getFirstCtor (d : Name) : MetaM (Option Name) := do
some (ConstantInfo.inductInfo { ctors := ctor::_, ..}) ← getConstNoEx? d | pure none;
pure (some ctor)
private def mkNullaryCtor (type : Expr) (nparams : Nat) : MetaM (Option Expr) :=
match type.getAppFn with
| Expr.const d lvls _ => do
(some ctor) ← getFirstCtor d | pure none;
pure $ mkAppN (mkConst ctor lvls) (type.getAppArgs.shrink nparams)
| _ => pure none
def toCtorIfLit : Expr → Expr
| Expr.lit (Literal.natVal v) _ =>
if v == 0 then mkConst `Nat.zero
else mkApp (mkConst `Nat.succ) (mkNatLit (v-1))
| Expr.lit (Literal.strVal v) _ =>
mkApp (mkConst `String.mk) (toExpr v.toList)
| e => e
private def getRecRuleFor (rec : RecursorVal) (major : Expr) : Option RecursorRule :=
match major.getAppFn with
| Expr.const fn _ _ => rec.rules.find? $ fun r => r.ctor == fn
| _ => none
private def toCtorWhenK (rec : RecursorVal) (major : Expr) : MetaM (Option Expr) := do
majorType ← inferType major;
majorType ← whnf majorType;
let majorTypeI := majorType.getAppFn;
if !majorTypeI.isConstOf rec.getInduct then
pure none
else if majorType.hasExprMVar && majorType.getAppArgs.anyFrom rec.nparams Expr.hasExprMVar then
pure none
else do
(some newCtorApp) ← mkNullaryCtor majorType rec.nparams | pure none;
newType ← inferType newCtorApp;
defeq ← Meta.isExprDefEqAux majorType newType;
pure $ if defeq then newCtorApp else none
/-- Auxiliary function for reducing recursor applications. -/
private def reduceRec {α} (rec : RecursorVal) (recLvls : List Level) (recArgs : Array Expr) (failK : Unit → MetaM α) (successK : Expr → MetaM α) : MetaM α :=
let majorIdx := rec.getMajorIdx;
if h : majorIdx < recArgs.size then do
let major := recArgs.get ⟨majorIdx, h⟩;
major ← whnf major;
major ←
if !rec.k then
pure major
else do {
newMajor ← toCtorWhenK rec major;
pure (newMajor.getD major)
};
let major := toCtorIfLit major;
match getRecRuleFor rec major with
| some rule =>
let majorArgs := major.getAppArgs;
if recLvls.length != rec.lparams.length then
failK ()
else
let rhs := rule.rhs.instantiateLevelParams rec.lparams recLvls;
-- Apply parameters, motives and minor premises from recursor application.
let rhs := mkAppRange rhs 0 (rec.nparams+rec.nmotives+rec.nminors) recArgs;
/- The number of parameters in the constructor is not necessarily
equal to the number of parameters in the recursor when we have
nested inductive types. -/
let nparams := majorArgs.size - rule.nfields;
let rhs := mkAppRange rhs nparams majorArgs.size majorArgs;
let rhs := mkAppRange rhs (majorIdx + 1) recArgs.size recArgs;
successK rhs
| none => failK ()
else
failK ()
@[specialize] private def isRecStuck? (isStuck? : Expr → MetaM (Option MVarId)) (rec : RecursorVal) (recLvls : List Level) (recArgs : Array Expr)
: MetaM (Option MVarId) :=
if rec.k then
-- TODO: improve this case
pure none
else do
let majorIdx := rec.getMajorIdx;
if h : majorIdx < recArgs.size then do
let major := recArgs.get ⟨majorIdx, h⟩;
major ← whnf major;
isStuck? major
else
pure none
/- ===========================
Helper functions for reducing Quot.lift and Quot.ind
=========================== -/
/-- Auxiliary function for reducing `Quot.lift` and `Quot.ind` applications. -/
private def reduceQuotRec {α} (rec : QuotVal) (recLvls : List Level) (recArgs : Array Expr) (failK : Unit → MetaM α) (successK : Expr → MetaM α) : MetaM α :=
let process (majorPos argPos : Nat) : MetaM α :=
if h : majorPos < recArgs.size then do
let major := recArgs.get ⟨majorPos, h⟩;
major ← whnf major;
match major with
| Expr.app (Expr.app (Expr.app (Expr.const majorFn _ _) _ _) _ _) majorArg _ => do
some (ConstantInfo.quotInfo { kind := QuotKind.ctor, .. }) ← getConstNoEx? majorFn | failK ();
let f := recArgs.get! argPos;
let r := mkApp f majorArg;
let recArity := majorPos + 1;
successK $ mkAppRange r recArity recArgs.size recArgs
| _ => failK ()
else
failK ();
match rec.kind with
| QuotKind.lift => process 5 3
| QuotKind.ind => process 4 3
| _ => failK ()
@[specialize] private def isQuotRecStuck? (isStuck? : Expr → MetaM (Option MVarId)) (rec : QuotVal) (recLvls : List Level) (recArgs : Array Expr)
: MetaM (Option MVarId) :=
let process? (majorPos : Nat) : MetaM (Option MVarId) :=
if h : majorPos < recArgs.size then do
let major := recArgs.get ⟨majorPos, h⟩;
major ← whnf major;
isStuck? major
else
pure none;
match rec.kind with
| QuotKind.lift => process? 5
| QuotKind.ind => process? 4
| _ => pure none
/- ===========================
Helper function for extracting "stuck term"
=========================== -/
/-- Return `some (Expr.mvar mvarId)` if metavariable `mvarId` is blocking reduction. -/
private partial def getStuckMVarImp? : Expr → MetaM (Option MVarId)
| Expr.mdata _ e _ => getStuckMVarImp? e
| Expr.proj _ _ e _ => do e ← whnf e; getStuckMVarImp? e
| e@(Expr.mvar mvarId _) => pure (some mvarId)
| e@(Expr.app f _ _) =>
let f := f.getAppFn;
match f with
| Expr.mvar mvarId _ => pure (some mvarId)
| Expr.const fName fLvls _ => do
cinfo? ← getConstNoEx? fName;
match cinfo? with
| some $ ConstantInfo.recInfo rec => isRecStuck? getStuckMVarImp? rec fLvls e.getAppArgs
| some $ ConstantInfo.quotInfo rec => isQuotRecStuck? getStuckMVarImp? rec fLvls e.getAppArgs
| _ => pure none
| _ => pure none
| _ => pure none
@[inline] def getStuckMVar? (e : Expr) : m (Option MVarId) :=
liftM $ getStuckMVarImp? e
/- ===========================
Weak Head Normal Form auxiliary combinators
=========================== -/
/-- Auxiliary combinator for handling easy WHNF cases. It takes a function for handling the "hard" cases as an argument -/
@[specialize] private partial def whnfEasyCases : Expr → (Expr → MetaM Expr) → MetaM Expr
| e@(Expr.forallE _ _ _ _), _ => pure e
| e@(Expr.lam _ _ _ _), _ => pure e
| e@(Expr.sort _ _), _ => pure e
| e@(Expr.lit _ _), _ => pure e
| e@(Expr.bvar _ _), _ => unreachable!
| Expr.mdata _ e _, k => whnfEasyCases e k
| e@(Expr.letE _ _ _ _ _), k => k e
| e@(Expr.fvar fvarId _), k => do
decl ← getLocalDecl fvarId;
match decl with
| LocalDecl.cdecl _ _ _ _ _ => pure e
| LocalDecl.ldecl _ _ _ _ v nonDep => do
cfg ← getConfig;
if nonDep && !cfg.zetaNonDep then
pure e
else do
when cfg.trackZeta $
modify fun s => { s with zetaFVarIds := s.zetaFVarIds.insert fvarId };
whnfEasyCases v k
| e@(Expr.mvar mvarId _), k => do
v? ← getExprMVarAssignment? mvarId;
match v? with
| some v => whnfEasyCases v k
| none => pure e
| e@(Expr.const _ _ _), k => k e
| e@(Expr.app _ _ _), k => k e
| e@(Expr.proj _ _ _ _), k => k e
| Expr.localE _ _ _ _, _ => unreachable!
/-- Return true iff term is of the form `idRhs ...` -/
private def isIdRhsApp (e : Expr) : Bool :=
e.isAppOf `idRhs
/-- (@idRhs T f a_1 ... a_n) ==> (f a_1 ... a_n) -/
private def extractIdRhs (e : Expr) : Expr :=
if !isIdRhsApp e then e
else
let args := e.getAppArgs;
if args.size < 2 then e
else mkAppRange (args.get! 1) 2 args.size args
@[specialize] private def deltaDefinition {α} (c : ConstantInfo) (lvls : List Level)
(failK : Unit → α) (successK : Expr → α) : α :=
if c.lparams.length != lvls.length then failK ()
else
let val := c.instantiateValueLevelParams lvls;
successK (extractIdRhs val)
@[specialize] private def deltaBetaDefinition {α} (c : ConstantInfo) (lvls : List Level) (revArgs : Array Expr)
(failK : Unit → α) (successK : Expr → α) : α :=
if c.lparams.length != lvls.length then failK ()
else
let val := c.instantiateValueLevelParams lvls;
let val := val.betaRev revArgs;
successK (extractIdRhs val)
/--
Apply beta-reduction, zeta-reduction (i.e., unfold let local-decls), iota-reduction,
expand let-expressions, expand assigned meta-variables. -/
private partial def whnfCoreImp : Expr → MetaM Expr
| e => whnfEasyCases e $ fun e =>
match e with
| e@(Expr.const _ _ _) => pure e
| e@(Expr.letE _ _ v b _) => whnfCoreImp $ b.instantiate1 v
| e@(Expr.app f _ _) => do
let f := f.getAppFn;
f' ← whnfCoreImp f;
if f'.isLambda then
let revArgs := e.getAppRevArgs;
whnfCoreImp $ f'.betaRev revArgs
else do
let done : Unit → MetaM Expr := fun _ =>
if f == f' then pure e else pure $ e.updateFn f';
matchConstAux f' done $ fun cinfo lvls =>
match cinfo with
| ConstantInfo.recInfo rec => reduceRec rec lvls e.getAppArgs done whnfCoreImp
| ConstantInfo.quotInfo rec => reduceQuotRec rec lvls e.getAppArgs done whnfCoreImp
| c@(ConstantInfo.defnInfo _) => do
unfold? ← isAuxDef? c.name;
if unfold? then
deltaBetaDefinition c lvls e.getAppRevArgs done whnfCoreImp
else
done ()
| _ => done ()
| e@(Expr.proj _ i c _) => do
c ← whnf c;
matchConstAux c.getAppFn (fun _ => pure e) $ fun cinfo lvls =>
match cinfo with
| ConstantInfo.ctorInfo ctorVal => pure $ c.getArgD (ctorVal.nparams + i) e
| _ => pure e
| _ => unreachable!
@[inline] def whnfCore (e : Expr) : m Expr :=
liftMetaM $ whnfCoreImp e
/--
Similar to `whnfCore`, but uses `synthesizePending` to (try to) synthesize metavariables
that are blocking reduction. -/
private partial def whnfCoreUnstuck : Expr → MetaM Expr
| e => do
e ← whnfCore e;
(some mvarId) ← getStuckMVar? e | pure e;
succeeded ← Meta.synthPending mvarId;
if succeeded then whnfCoreUnstuck e else pure e
/-- Unfold definition using "smart unfolding" if possible. -/
private def unfoldDefinitionImp? (e : Expr) : MetaM (Option Expr) :=
match e with
| Expr.app f _ _ =>
matchConstAux f.getAppFn (fun _ => pure none) $ fun fInfo fLvls =>
if fInfo.lparams.length != fLvls.length then pure none
else do
fAuxInfo? ← getConstNoEx? (mkSmartUnfoldingNameFor fInfo.name);
match fAuxInfo? with
| some $ fAuxInfo@(ConstantInfo.defnInfo _) =>
deltaBetaDefinition fAuxInfo fLvls e.getAppRevArgs (fun _ => pure none) $ fun e₁ => do
e₂ ← whnfCoreUnstuck e₁;
if isIdRhsApp e₂ then
pure (some (extractIdRhs e₂))
else
pure none
| _ =>
if fInfo.hasValue then
deltaBetaDefinition fInfo fLvls e.getAppRevArgs (fun _ => pure none) (fun e => pure (some e))
else
pure none
| Expr.const name lvls _ => do
(some (cinfo@(ConstantInfo.defnInfo _))) ← getConstNoEx? name | pure none;
deltaDefinition cinfo lvls (fun _ => pure none) (fun e => pure (some e))
| _ => pure none
@[inline] def unfoldDefinition? (e : Expr) : m (Option Expr) :=
liftMetaM $ unfoldDefinitionImp? e
unsafe def reduceNativeConst (α : Type) (typeName : Name) (constName : Name) : MetaM α := do
env ← getEnv;
match env.evalConstCheck α typeName constName with
| Except.error ex => throwError ex
| Except.ok v => pure v
unsafe def reduceBoolNativeUnsafe (constName : Name) : MetaM Bool := reduceNativeConst Bool `Bool constName
unsafe def reduceNatNativeUnsafe (constName : Name) : MetaM Nat := reduceNativeConst Nat `Nat constName
@[implementedBy reduceBoolNativeUnsafe] constant reduceBoolNative (constName : Name) : MetaM Bool := arbitrary _
@[implementedBy reduceNatNativeUnsafe] constant reduceNatNative (constName : Name) : MetaM Nat := arbitrary _
def reduceNative? (e : Expr) : MetaM (Option Expr) :=
match e with
| Expr.app (Expr.const fName _ _) (Expr.const argName _ _) _ =>
if fName == `Lean.reduceBool then do
b ← reduceBoolNative argName;
pure $ toExpr b
else if fName == `Lean.reduceNat then do
n ← reduceNatNative argName;
pure $ toExpr n
else
pure none
| _ => pure none
@[inline] def withNatValue {α} (a : Expr) (k : Nat → MetaM (Option α)) : MetaM (Option α) := do
a ← whnf a;
match a with
| Expr.const `Nat.zero _ _ => k 0
| Expr.lit (Literal.natVal v) _ => k v
| _ => pure none
def reduceUnaryNatOp (f : Nat → Nat) (a : Expr) : MetaM (Option Expr) :=
withNatValue a $ fun a =>
pure $ mkNatLit $ f a
def reduceBinNatOp (f : Nat → Nat → Nat) (a b : Expr) : MetaM (Option Expr) :=
withNatValue a $ fun a =>
withNatValue b $ fun b => do
trace `Meta.isDefEq.whnf.reduceBinOp $ fun _ => toString a ++ " op " ++ toString b;
pure $ mkNatLit $ f a b
def reduceBinNatPred (f : Nat → Nat → Bool) (a b : Expr) : MetaM (Option Expr) := do
withNatValue a $ fun a =>
withNatValue b $ fun b =>
pure $ toExpr $ f a b
def reduceNat? (e : Expr) : MetaM (Option Expr) :=
if e.hasFVar || e.hasMVar then
pure none
else match e with
| Expr.app (Expr.const fn _ _) a _ =>
if fn == `Nat.succ then reduceUnaryNatOp Nat.succ a
else pure none
| Expr.app (Expr.app (Expr.const fn _ _) a1 _) a2 _ =>
if fn == `Nat.add then reduceBinNatOp Nat.add a1 a2
else if fn == `Nat.sub then reduceBinNatOp Nat.sub a1 a2
else if fn == `Nat.mul then reduceBinNatOp Nat.mul a1 a2
else if fn == `Nat.div then reduceBinNatOp Nat.div a1 a2
else if fn == `Nat.mod then reduceBinNatOp Nat.mod a1 a2
else if fn == `Nat.beq then reduceBinNatPred Nat.beq a1 a2
else if fn == `Nat.ble then reduceBinNatPred Nat.ble a1 a2
else pure none
| _ => pure none
@[inline] private def useWHNFCache (e : Expr) : MetaM Bool := do
-- We cache only closed terms
if e.hasFVar then pure false
else do
ctx ← read;
pure $ ctx.config.transparency != TransparencyMode.reducible
@[inline] private def cached? (useCache : Bool) (e : Expr) : MetaM (Option Expr) := do
if useCache then do
ctx ← read;
s ← get;
match ctx.config.transparency with
| TransparencyMode.default => pure $ s.cache.whnfDefault.find? e
| TransparencyMode.all => pure $ s.cache.whnfAll.find? e
| _ => unreachable!
else
pure none
private def cache (useCache : Bool) (e r : Expr) : MetaM Expr := do
ctx ← read;
when useCache $
match ctx.config.transparency with
| TransparencyMode.default => modify $ fun s => { s with cache := { s.cache with whnfDefault := s.cache.whnfDefault.insert e r } }
| TransparencyMode.all => modify $ fun s => { s with cache := { s.cache with whnfAll := s.cache.whnfAll.insert e r } }
| _ => unreachable!;
pure r
partial def whnfImp : Expr → MetaM Expr
| e => whnfEasyCases e $ fun e => do
useCache ← useWHNFCache e;
e? ← cached? useCache e;
match e? with
| some e' => pure e'
| none => do
e' ← whnfCore e;
v? ← reduceNat? e';
match v? with
| some v => cache useCache e v
| none => do
v? ← reduceNative? e';
match v? with
| some v => cache useCache e v
| none => do
e? ← unfoldDefinition? e';
match e? with
| some e => whnfImp e
| none => cache useCache e e'
@[init] def setWHNFRef : IO Unit :=
whnfRef.set whnfImp
/- Given an expression `e`, compute its WHNF and if the result is a constructor, return field #i. -/
def reduceProj? (e : Expr) (i : Nat) : MetaM (Option Expr) := do
e ← whnf e;
matchConstCtor e.getAppFn (fun _ => pure none) fun ctorVal _ =>
let numArgs := e.getAppNumArgs;
let idx := ctorVal.nparams + i;
if idx < numArgs then
pure (some (e.getArg! idx))
else
pure none
@[specialize] partial def whnfHeadPredAux (pred : Expr → MetaM Bool) : Expr → MetaM Expr
| e => whnfEasyCases e $ fun e => do
e ← whnfCore e;
condM (pred e)
(do
e? ← unfoldDefinition? e;
match e? with
| some e => whnfHeadPredAux e
| none => pure e)
(pure e)
@[inline] def whnfHeadPred (e : Expr) (pred : Expr → MetaM Bool) : m Expr :=
liftMetaM $ whnfHeadPredAux pred e
def whnfUntil (e : Expr) (declName : Name) : m (Option Expr) := liftMetaM do
e ← whnfHeadPredAux (fun e => pure $ !e.isAppOf declName) e;
if e.isAppOf declName then pure e
else pure none
end Meta
end Lean
|
aba0e8f7a5b1e53b9dcaed521bf466e29c259c9a | e953c38599905267210b87fb5d82dcc3e52a4214 | /library/algebra/ordered_field.lean | 24b7ad654726d9a1ec2a868c69e0e4de7b3191db | [
"Apache-2.0"
] | permissive | c-cube/lean | 563c1020bff98441c4f8ba60111fef6f6b46e31b | 0fb52a9a139f720be418dafac35104468e293b66 | refs/heads/master | 1,610,753,294,113 | 1,440,451,356,000 | 1,440,499,588,000 | 41,748,334 | 0 | 0 | null | 1,441,122,656,000 | 1,441,122,656,000 | null | UTF-8 | Lean | false | false | 20,608 | lean | /-
Copyright (c) 2014 Robert Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Robert Lewis
-/
import algebra.ordered_ring algebra.field
open eq eq.ops
namespace algebra
structure linear_ordered_field [class] (A : Type) extends linear_ordered_ring A, field A
section linear_ordered_field
variable {A : Type}
variables [s : linear_ordered_field A] {a b c d : A}
include s
-- helpers for following
theorem mul_zero_lt_mul_inv_of_pos (H : 0 < a) : a * 0 < a * (1 / a) :=
calc
a * 0 = 0 : mul_zero
... < 1 : zero_lt_one
... = a * a⁻¹ : mul_inv_cancel (ne.symm (ne_of_lt H))
... = a * (1 / a) : inv_eq_one_div
theorem mul_zero_lt_mul_inv_of_neg (H : a < 0) : a * 0 < a * (1 / a) :=
calc
a * 0 = 0 : mul_zero
... < 1 : zero_lt_one
... = a * a⁻¹ : mul_inv_cancel (ne_of_lt H)
... = a * (1 / a) : inv_eq_one_div
theorem div_pos_of_pos (H : 0 < a) : 0 < 1 / a :=
lt_of_mul_lt_mul_left (mul_zero_lt_mul_inv_of_pos H) (le_of_lt H)
theorem div_neg_of_neg (H : a < 0) : 1 / a < 0 :=
gt_of_mul_lt_mul_neg_left (mul_zero_lt_mul_inv_of_neg H) (le_of_lt H)
theorem le_mul_of_ge_one_right (Hb : b ≥ 0) (H : a ≥ 1) : b ≤ b * a :=
mul_one _ ▸ (mul_le_mul_of_nonneg_left H Hb)
theorem lt_mul_of_gt_one_right (Hb : b > 0) (H : a > 1) : b < b * a :=
mul_one _ ▸ (mul_lt_mul_of_pos_left H Hb)
theorem one_le_div_iff_le (Hb : b > 0) : 1 ≤ a / b ↔ b ≤ a :=
have Hb' : b ≠ 0, from ne.symm (ne_of_lt Hb),
iff.intro
(assume H : 1 ≤ a / b,
calc
b = b : refl
... ≤ b * (a / b) : le_mul_of_ge_one_right (le_of_lt Hb) H
... = a : mul_div_cancel' Hb')
(assume H : b ≤ a,
have Hbinv : 1 / b > 0, from div_pos_of_pos Hb, calc
1 = b * (1 / b) : mul_one_div_cancel Hb'
... ≤ a * (1 / b) : mul_le_mul_of_nonneg_right H (le_of_lt Hbinv)
... = a / b : div_eq_mul_one_div)
theorem le_of_one_le_div (Hb : b > 0) (H : 1 ≤ a / b) : b ≤ a :=
(iff.mp (one_le_div_iff_le Hb)) H
theorem one_le_div_of_le (Hb : b > 0) (H : b ≤ a) : 1 ≤ a / b :=
(iff.mpr (one_le_div_iff_le Hb)) H
theorem one_lt_div_iff_lt (Hb : b > 0) : 1 < a / b ↔ b < a :=
have Hb' : b ≠ 0, from ne.symm (ne_of_lt Hb),
iff.intro
(assume H : 1 < a / b,
calc
b < b * (a / b) : lt_mul_of_gt_one_right Hb H
... = a : mul_div_cancel' Hb')
(assume H : b < a,
have Hbinv : 1 / b > 0, from div_pos_of_pos Hb, calc
1 = b * (1 / b) : mul_one_div_cancel Hb'
... < a * (1 / b) : mul_lt_mul_of_pos_right H Hbinv
... = a / b : div_eq_mul_one_div)
theorem lt_of_one_lt_div (Hb : b > 0) (H : 1 < a / b) : b < a :=
(iff.mp (one_lt_div_iff_lt Hb)) H
theorem one_lt_div_of_lt (Hb : b > 0) (H : b < a) : 1 < a / b :=
(iff.mpr (one_lt_div_iff_lt Hb)) H
theorem exists_lt : ∃ x, x < a :=
have H : a - 1 < a, from add_lt_of_le_of_neg (le.refl _) zero_gt_neg_one,
exists.intro _ H
theorem exists_gt : ∃ x, x > a :=
have H : a + 1 > a, from lt_add_of_le_of_pos (le.refl _) zero_lt_one,
exists.intro _ H
-- the following theorems amount to four iffs, for <, ≤, ≥, >.
theorem mul_le_of_le_div (Hc : 0 < c) (H : a ≤ b / c) : a * c ≤ b :=
div_mul_cancel (ne.symm (ne_of_lt Hc)) ▸ mul_le_mul_of_nonneg_right H (le_of_lt Hc)
theorem le_div_of_mul_le (Hc : 0 < c) (H : a * c ≤ b) : a ≤ b / c :=
calc
a = a * c * (1 / c) : mul_mul_div (ne.symm (ne_of_lt Hc))
... ≤ b * (1 / c) : mul_le_mul_of_nonneg_right H (le_of_lt (div_pos_of_pos Hc))
... = b / c : div_eq_mul_one_div
theorem mul_lt_of_lt_div (Hc : 0 < c) (H : a < b / c) : a * c < b :=
div_mul_cancel (ne.symm (ne_of_lt Hc)) ▸ mul_lt_mul_of_pos_right H Hc
theorem lt_div_of_mul_lt (Hc : 0 < c) (H : a * c < b) : a < b / c :=
calc
a = a * c * (1 / c) : mul_mul_div (ne.symm (ne_of_lt Hc))
... < b * (1 / c) : mul_lt_mul_of_pos_right H (div_pos_of_pos Hc)
... = b / c : div_eq_mul_one_div
theorem mul_le_of_ge_div_neg (Hc : c < 0) (H : a ≥ b / c) : a * c ≤ b :=
div_mul_cancel (ne_of_lt Hc) ▸ mul_le_mul_of_nonpos_right H (le_of_lt Hc)
theorem ge_div_of_mul_le_neg (Hc : c < 0) (H : a * c ≤ b) : a ≥ b / c :=
calc
a = a * c * (1 / c) : mul_mul_div (ne_of_lt Hc)
... ≥ b * (1 / c) : mul_le_mul_of_nonpos_right H (le_of_lt (div_neg_of_neg Hc))
... = b / c : div_eq_mul_one_div
theorem mul_lt_of_gt_div_neg (Hc : c < 0) (H : a > b / c) : a * c < b :=
div_mul_cancel (ne_of_lt Hc) ▸ mul_lt_mul_of_neg_right H Hc
theorem gt_div_of_mul_gt_neg (Hc : c < 0) (H : a * c < b) : a > b / c :=
calc
a = a * c * (1 / c) : mul_mul_div (ne_of_lt Hc)
... > b * (1 / c) : mul_lt_mul_of_neg_right H (div_neg_of_neg Hc)
... = b / c : div_eq_mul_one_div
-----
theorem div_le_of_le_mul (Hb : b > 0) (H : a ≤ b * c) : a / b ≤ c :=
calc
a / b = a * (1 / b) : div_eq_mul_one_div
... ≤ (b * c) * (1 / b) : mul_le_mul_of_nonneg_right H (le_of_lt (div_pos_of_pos Hb))
... = (b * c) / b : div_eq_mul_one_div
... = c : mul_div_cancel_left (ne.symm (ne_of_lt Hb))
theorem le_mul_of_div_le (Hc : c > 0) (H : a / c ≤ b) : a ≤ b * c :=
calc
a = a / c * c : div_mul_cancel (ne.symm (ne_of_lt Hc))
... ≤ b * c : mul_le_mul_of_nonneg_right H (le_of_lt Hc)
-- following these in the isabelle file, there are 8 biconditionals for the above with - signs
-- skipping for now
theorem mul_sub_mul_div_mul_neg (Hc : c ≠ 0) (Hd : d ≠ 0) (H : a / c < b / d) :
(a * d - b * c) / (c * d) < 0 :=
have H1 : a / c - b / d < 0, from calc
a / c - b / d < b / d - b / d : sub_lt_sub_right H
... = 0 : sub_self,
calc
0 > a / c - b / d : H1
... = (a * d - c * b) / (c * d) : div_sub_div Hc Hd
... = (a * d - b * c) / (c * d) : mul.comm
theorem mul_sub_mul_div_mul_nonpos (Hc : c ≠ 0) (Hd : d ≠ 0) (H : a / c ≤ b / d) :
(a * d - b * c) / (c * d) ≤ 0 :=
have H1 : a / c - b / d ≤ 0, from calc
a / c - b / d ≤ b / d - b / d : sub_le_sub_right H
... = 0 : sub_self,
calc
0 ≥ a / c - b / d : H1
... = (a * d - c * b) / (c * d) : div_sub_div Hc Hd
... = (a * d - b * c) / (c * d) : mul.comm
theorem div_lt_div_of_mul_sub_mul_div_neg (Hc : c ≠ 0) (Hd : d ≠ 0)
(H : (a * d - b * c) / (c * d) < 0) : a / c < b / d :=
assert H1 : (a * d - c * b) / (c * d) < 0, by rewrite [mul.comm c b]; exact H,
assert H2 : a / c - b / d < 0, by rewrite [div_sub_div Hc Hd]; exact H1,
assert H3 : a / c - b / d + b / d < 0 + b / d, from add_lt_add_right H2 _,
begin rewrite [zero_add at H3, neg_add_cancel_right at H3], exact H3 end
theorem div_le_div_of_mul_sub_mul_div_nonpos (Hc : c ≠ 0) (Hd : d ≠ 0)
(H : (a * d - b * c) / (c * d) ≤ 0) : a / c ≤ b / d :=
assert H1 : (a * d - c * b) / (c * d) ≤ 0, by rewrite [mul.comm c b]; exact H,
assert H2 : a / c - b / d ≤ 0, by rewrite [div_sub_div Hc Hd]; exact H1,
assert H3 : a / c - b / d + b / d ≤ 0 + b / d, from add_le_add_right H2 _,
begin rewrite [zero_add at H3, neg_add_cancel_right at H3], exact H3 end
theorem pos_div_of_pos_of_pos (Ha : 0 < a) (Hb : 0 < b) : 0 < a / b :=
begin
rewrite div_eq_mul_one_div,
apply mul_pos,
exact Ha,
apply div_pos_of_pos,
exact Hb
end
theorem nonneg_div_of_nonneg_of_pos (Ha : 0 ≤ a) (Hb : 0 < b) : 0 ≤ a / b :=
begin
rewrite div_eq_mul_one_div,
apply mul_nonneg,
exact Ha,
apply le_of_lt,
apply div_pos_of_pos,
exact Hb
end
theorem neg_div_of_neg_of_pos (Ha : a < 0) (Hb : 0 < b) : a / b < 0:=
begin
rewrite div_eq_mul_one_div,
apply mul_neg_of_neg_of_pos,
exact Ha,
apply div_pos_of_pos,
exact Hb
end
theorem nonpos_div_of_nonpos_of_pos (Ha : a ≤ 0) (Hb : 0 < b) : a / b ≤ 0 :=
begin
rewrite div_eq_mul_one_div,
apply mul_nonpos_of_nonpos_of_nonneg,
exact Ha,
apply le_of_lt,
apply div_pos_of_pos,
exact Hb
end
theorem neg_div_of_pos_of_neg (Ha : 0 < a) (Hb : b < 0) : a / b < 0 :=
begin
rewrite div_eq_mul_one_div,
apply mul_neg_of_pos_of_neg,
exact Ha,
apply div_neg_of_neg,
exact Hb
end
theorem nonpos_div_of_nonneg_of_neg (Ha : 0 ≤ a) (Hb : b < 0) : a / b ≤ 0 :=
begin
rewrite div_eq_mul_one_div,
apply mul_nonpos_of_nonneg_of_nonpos,
exact Ha,
apply le_of_lt,
apply div_neg_of_neg,
exact Hb
end
theorem pos_div_of_neg_of_neg (Ha : a < 0) (Hb : b < 0) : 0 < a / b :=
begin
rewrite div_eq_mul_one_div,
apply mul_pos_of_neg_of_neg,
exact Ha,
apply div_neg_of_neg,
exact Hb
end
theorem nonneg_div_of_nonpos_of_neg (Ha : a ≤ 0) (Hb : b < 0) : 0 ≤ a / b :=
begin
rewrite div_eq_mul_one_div,
apply mul_nonneg_of_nonpos_of_nonpos,
exact Ha,
apply le_of_lt,
apply div_neg_of_neg,
exact Hb
end
theorem div_lt_div_of_lt_of_pos (H : a < b) (Hc : 0 < c) : a / c < b / c :=
begin
rewrite [{a/c}div_eq_mul_one_div, {b/c}div_eq_mul_one_div],
exact mul_lt_mul_of_pos_right H (div_pos_of_pos Hc)
end
theorem div_le_div_of_le_of_pos (H : a ≤ b) (Hc : 0 < c) : a / c ≤ b / c :=
begin
rewrite [{a/c}div_eq_mul_one_div, {b/c}div_eq_mul_one_div],
exact mul_le_mul_of_nonneg_right H (le_of_lt (div_pos_of_pos Hc))
end
theorem div_lt_div_of_lt_of_neg (H : b < a) (Hc : c < 0) : a / c < b / c :=
begin
rewrite [{a/c}div_eq_mul_one_div, {b/c}div_eq_mul_one_div],
exact mul_lt_mul_of_neg_right H (div_neg_of_neg Hc)
end
theorem div_le_div_of_le_of_neg (H : b ≤ a) (Hc : c < 0) : a / c ≤ b / c :=
begin
rewrite [{a/c}div_eq_mul_one_div, {b/c}div_eq_mul_one_div],
exact mul_le_mul_of_nonpos_right H (le_of_lt (div_neg_of_neg Hc))
end
theorem two_pos : (1 : A) + 1 > 0 :=
add_pos zero_lt_one zero_lt_one
theorem two_ne_zero : (1 : A) + 1 ≠ 0 :=
ne.symm (ne_of_lt two_pos)
notation 2 := 1 + 1
theorem add_halves : a / 2 + a / 2 = a :=
calc
a / 2 + a / 2 = (a + a) / 2 : by rewrite div_add_div_same
... = (a * 1 + a * 1) / 2 : by rewrite mul_one
... = (a * 2) / 2 : by rewrite left_distrib
... = a : by rewrite [@mul_div_cancel A _ _ _ two_ne_zero]
theorem sub_self_div_two : a - a / 2 = a / 2 :=
by rewrite [-{a}add_halves at {1}, add_sub_cancel]
theorem div_two_sub_self : a / 2 - a = - (a / 2) :=
by rewrite [-{a}add_halves at {2}, sub_add_eq_sub_sub, sub_self, zero_sub]
theorem nonneg_le_nonneg_of_squares_le (Ha : a ≥ 0) (Hb : b ≥ 0) (H : a * a ≤ b * b) : a ≤ b :=
begin
apply le_of_not_gt,
intro Hab,
let Hposa := lt_of_le_of_lt Hb Hab,
let H' := calc
b * b ≤ a * b : mul_le_mul_of_nonneg_right (le_of_lt Hab) Hb
... < a * a : mul_lt_mul_of_pos_left Hab Hposa,
apply (not_le_of_gt H') H
end
theorem div_two : (a + a) / 2 = a :=
symm (iff.mpr (eq_div_iff_mul_eq (ne_of_gt (add_pos zero_lt_one zero_lt_one)))
(by rewrite [left_distrib, *mul_one]))
theorem two_ge_one : (2 : A) ≥ 1 :=
by rewrite -(add_zero 1) at {3}; apply add_le_add_left; apply zero_le_one
theorem mul_le_mul_of_mul_div_le (H : a * (b / c) ≤ d) (Hc : c > 0) : b * a ≤ d * c :=
begin
rewrite [-mul_div_assoc at H, mul.comm b],
apply le_mul_of_div_le Hc H
end
theorem div_two_lt_of_pos (H : a > 0) : a / (1 + 1) < a :=
have Ha : a / (1 + 1) > 0, from pos_div_of_pos_of_pos H (add_pos zero_lt_one zero_lt_one),
calc
a / (1 + 1) < a / (1 + 1) + a / (1 + 1) : lt_add_of_pos_left Ha
... = a : add_halves
theorem div_mul_le_div_mul_of_div_le_div_pos {e : A} (Hb : b ≠ 0) (Hd : d ≠ 0) (H : a / b ≤ c / d)
(He : e > 0) : a / (b * e) ≤ c / (d * e) :=
begin
rewrite [div_mul_eq_div_mul_one_div Hb (ne_of_gt He), div_mul_eq_div_mul_one_div Hd (ne_of_gt He)],
apply mul_le_mul_of_nonneg_right H,
apply le_of_lt,
apply div_pos_of_pos He
end
theorem find_midpoint (H : a > b) : ∃ c : A, a > b + c ∧ c > 0 :=
exists.intro ((a - b) / (1 + 1))
(and.intro (assert H2 : a + a > (b + b) + (a - b), from calc
a + a > b + a : add_lt_add_right H
... = b + a + b - b : add_sub_cancel
... = b + b + a - b : add.right_comm
... = (b + b) + (a - b) : add_sub,
assert H3 : (a + a) / (1 + 1) > ((b + b) + (a - b)) / (1 + 1),
from div_lt_div_of_lt_of_pos H2 two_pos,
by rewrite [div_two at H3, -div_add_div_same at H3, div_two at H3]; exact H3)
(pos_div_of_pos_of_pos (iff.mpr !sub_pos_iff_lt H) two_pos))
end linear_ordered_field
structure discrete_linear_ordered_field [class] (A : Type) extends linear_ordered_field A,
decidable_linear_ordered_comm_ring A :=
(inv_zero : inv zero = zero)
section discrete_linear_ordered_field
variable {A : Type}
variables [s : discrete_linear_ordered_field A] {a b c : A}
include s
definition dec_eq_of_dec_lt : ∀ x y : A, decidable (x = y) :=
take x y,
decidable.by_cases
(assume H : x < y, decidable.inr (ne_of_lt H))
(assume H : ¬ x < y,
decidable.by_cases
(assume H' : y < x, decidable.inr (ne.symm (ne_of_lt H')))
(assume H' : ¬ y < x,
decidable.inl (le.antisymm (le_of_not_gt H') (le_of_not_gt H))))
definition discrete_linear_ordered_field.to_discrete_field [trans-instance] [reducible] [coercion]
: discrete_field A :=
⦃ discrete_field, s, has_decidable_eq := dec_eq_of_dec_lt⦄
theorem pos_of_div_pos (H : 0 < 1 / a) : 0 < a :=
have H1 : 0 < 1 / (1 / a), from div_pos_of_pos H,
have H2 : 1 / a ≠ 0, from
(assume H3 : 1 / a = 0,
have H4 : 1 / (1 / a) = 0, from H3⁻¹ ▸ div_zero,
absurd H4 (ne.symm (ne_of_lt H1))),
(div_div (ne_zero_of_one_div_ne_zero H2)) ▸ H1
theorem neg_of_div_neg (H : 1 / a < 0) : a < 0 :=
have H1 : 0 < - (1 / a), from neg_pos_of_neg H,
have Ha : a ≠ 0, from ne_zero_of_one_div_ne_zero (ne_of_lt H),
have H2 : 0 < 1 / (-a), from (one_div_neg_eq_neg_one_div Ha)⁻¹ ▸ H1,
have H3 : 0 < -a, from pos_of_div_pos H2,
neg_of_neg_pos H3
theorem le_of_div_le (H : 0 < a) (Hl : 1 / a ≤ 1 / b) : b ≤ a :=
have Hb : 0 < b, from pos_of_div_pos (calc
0 < 1 / a : div_pos_of_pos H
... ≤ 1 / b : Hl),
have H' : 1 ≤ a / b, from (calc
1 = a / a : div_self (ne.symm (ne_of_lt H))
... = a * (1 / a) : div_eq_mul_one_div
... ≤ a * (1 / b) : mul_le_mul_of_nonneg_left Hl (le_of_lt H)
... = a / b : div_eq_mul_one_div
), le_of_one_le_div Hb H'
theorem le_of_div_le_neg (H : b < 0) (Hl : 1 / a ≤ 1 / b) : b ≤ a :=
assert Ha : a ≠ 0, from ne_of_lt (neg_of_div_neg (calc
1 / a ≤ 1 / b : Hl
... < 0 : div_neg_of_neg H)),
have H' : -b > 0, from neg_pos_of_neg H,
have Hl' : - (1 / b) ≤ - (1 / a), from neg_le_neg Hl,
have Hl'' : 1 / - b ≤ 1 / - a, from calc
1 / -b = - (1 / b) : by rewrite [one_div_neg_eq_neg_one_div (ne_of_lt H)]
... ≤ - (1 / a) : Hl'
... = 1 / -a : by rewrite [one_div_neg_eq_neg_one_div Ha],
le_of_neg_le_neg (le_of_div_le H' Hl'')
theorem lt_of_div_lt (H : 0 < a) (Hl : 1 / a < 1 / b) : b < a :=
have Hb : 0 < b, from pos_of_div_pos (calc
0 < 1 / a : div_pos_of_pos H
... < 1 / b : Hl),
have H : 1 < a / b, from (calc
1 = a / a : div_self (ne.symm (ne_of_lt H))
... = a * (1 / a) : div_eq_mul_one_div
... < a * (1 / b) : mul_lt_mul_of_pos_left Hl H
... = a / b : div_eq_mul_one_div),
lt_of_one_lt_div Hb H
theorem lt_of_div_lt_neg (H : b < 0) (Hl : 1 / a < 1 / b) : b < a :=
have H1 : b ≤ a, from le_of_div_le_neg H (le_of_lt Hl),
have Hn : b ≠ a, from
(assume Hn' : b = a,
have Hl' : 1 / a = 1 / b, from Hn' ▸ refl _,
absurd Hl' (ne_of_lt Hl)),
lt_of_le_of_ne H1 Hn
theorem div_lt_div_of_lt (Ha : 0 < a) (H : a < b) : 1 / b < 1 / a :=
lt_of_not_ge
(assume H',
absurd H (not_lt_of_ge (le_of_div_le Ha H')))
theorem div_le_div_of_le (Ha : 0 < a) (H : a ≤ b) : 1 / b ≤ 1 / a :=
le_of_not_gt
(assume H',
absurd H (not_le_of_gt (lt_of_div_lt Ha H')))
theorem div_lt_div_of_lt_neg (Hb : b < 0) (H : a < b) : 1 / b < 1 / a :=
lt_of_not_ge
(assume H',
absurd H (not_lt_of_ge (le_of_div_le_neg Hb H')))
theorem div_le_div_of_le_neg (Hb : b < 0) (H : a ≤ b) : 1 / b ≤ 1 / a :=
le_of_not_gt
(assume H',
absurd H (not_le_of_gt (lt_of_div_lt_neg Hb H')))
theorem one_lt_div (H1 : 0 < a) (H2 : a < 1) : 1 < 1 / a :=
one_div_one ▸ div_lt_div_of_lt H1 H2
theorem one_le_div (H1 : 0 < a) (H2 : a ≤ 1) : 1 ≤ 1 / a :=
one_div_one ▸ div_le_div_of_le H1 H2
theorem neg_one_lt_div_neg (H1 : a < 0) (H2 : -1 < a) : 1 / a < -1 :=
one_div_neg_one_eq_neg_one ▸ div_lt_div_of_lt_neg H1 H2
theorem neg_one_le_div_neg (H1 : a < 0) (H2 : -1 ≤ a) : 1 / a ≤ -1 :=
one_div_neg_one_eq_neg_one ▸ div_le_div_of_le_neg H1 H2
theorem div_lt_div_of_pos_of_lt_of_pos (Hb : 0 < b) (H : b < a) (Hc : 0 < c) : c / a < c / b :=
begin
apply iff.mp !sub_neg_iff_lt,
rewrite [div_eq_mul_one_div, {c / b}div_eq_mul_one_div, -mul_sub_left_distrib],
apply mul_neg_of_pos_of_neg,
exact Hc,
apply iff.mpr !sub_neg_iff_lt,
apply div_lt_div_of_lt,
repeat assumption
end
theorem div_mul_le_div_mul_of_div_le_div_pos' {d e : A} (H : a / b ≤ c / d)
(He : e > 0) : a / (b * e) ≤ c / (d * e) :=
begin
rewrite [2 div_mul_eq_div_mul_one_div'],
apply mul_le_mul_of_nonneg_right H,
apply le_of_lt,
apply div_pos_of_pos He
end
theorem abs_one_div : abs (1 / a) = 1 / abs a :=
if H : a > 0 then
by rewrite [abs_of_pos H, abs_of_pos (div_pos_of_pos H)]
else
(if H' : a < 0 then
by rewrite [abs_of_neg H', abs_of_neg (div_neg_of_neg H'),
-(one_div_neg_eq_neg_one_div (ne_of_lt H'))]
else
assert Heq : a = 0, from eq_of_le_of_ge (le_of_not_gt H) (le_of_not_gt H'),
by rewrite [Heq, div_zero, *abs_zero, div_zero])
theorem ge_sub_of_abs_sub_le_left (H : abs (a - b) ≤ c) : a ≥ b - c :=
if Hz : 0 ≤ a - b then
(calc
a ≥ b : (iff.mp !sub_nonneg_iff_le) Hz
... ≥ b - c : sub_le_of_nonneg _ _ (le.trans !abs_nonneg H))
else
(have Habs : b - a ≤ c, by rewrite [abs_of_neg (lt_of_not_ge Hz) at H, neg_sub at H]; apply H,
have Habs' : b ≤ c + a, from (iff.mpr !le_add_iff_sub_right_le) Habs,
(iff.mp !le_add_iff_sub_left_le) Habs')
theorem ge_sub_of_abs_sub_le_right (H : abs (a - b) ≤ c) : b ≥ a - c :=
ge_sub_of_abs_sub_le_left (!abs_sub ▸ H)
theorem abs_sub_square : abs (a - b) * abs (a - b) = a * a + b * b - 2 * a * b :=
by rewrite [abs_mul_abs_self, *mul_sub_left_distrib, *mul_sub_right_distrib,
sub_add_eq_sub_sub, sub_neg_eq_add, *right_distrib, sub_add_eq_sub_sub, *one_mul,
*add.assoc, {_ + b * b}add.comm, {_ + (b * b + _)}add.comm, mul.comm b a, *add.assoc]
theorem abs_abs_sub_abs_le_abs_sub (a b : A) : abs (abs a - abs b) ≤ abs (a - b) :=
begin
apply nonneg_le_nonneg_of_squares_le,
repeat apply abs_nonneg,
rewrite [*abs_sub_square, *abs_abs, *abs_mul_abs_self],
apply sub_le_sub_left,
rewrite *mul.assoc,
apply mul_le_mul_of_nonneg_left,
rewrite -abs_mul,
apply le_abs_self,
apply le_of_lt,
apply two_pos
end
theorem sign_eq_div_abs (a : A) : sign a = a / (abs a) :=
decidable.by_cases
(suppose a = 0, by subst a; rewrite [zero_div, sign_zero])
(suppose a ≠ 0,
have abs a ≠ 0, from assume H, this (eq_zero_of_abs_eq_zero H),
eq_div_of_mul_eq this !eq_sign_mul_abs⁻¹)
end discrete_linear_ordered_field
end algebra
|
b4a399aaee2c9430c180a5a5e754d14a581cdac9 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/ring_theory/valuation/integers.lean | 2035a8bdd4314362d70f7bc0a51b6ee957957898 | [
"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 | 4,223 | lean | /-
Copyright (c) 2020 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
-/
import ring_theory.valuation.basic
/-!
# Ring of integers under a given valuation
The elements with valuation less than or equal to 1.
TODO: Define characteristic predicate.
-/
universes u v w
namespace valuation
section ring
variables {R : Type u} {Γ₀ : Type v} [ring R] [linear_ordered_comm_group_with_zero Γ₀]
variables (v : valuation R Γ₀)
/-- The ring of integers under a given valuation is the subring of elements with valuation ≤ 1. -/
def integer : subring R :=
{ carrier := { x | v x ≤ 1 },
one_mem' := le_of_eq v.map_one,
mul_mem' := λ x y hx hy, trans_rel_right (≤) (v.map_mul x y) (mul_le_one' hx hy),
zero_mem' := trans_rel_right (≤) v.map_zero zero_le_one',
add_mem' := λ x y hx hy, le_trans (v.map_add x y) (max_le hx hy),
neg_mem' := λ x hx, trans_rel_right (≤) (v.map_neg x) hx }
end ring
section comm_ring
variables {R : Type u} {Γ₀ : Type v} [comm_ring R] [linear_ordered_comm_group_with_zero Γ₀]
variables (v : valuation R Γ₀)
variables (O : Type w) [comm_ring O] [algebra O R]
/-- Given a valuation v : R → Γ₀ and a ring homomorphism O →+* R, we say that O is the integers of v
if f is injective, and its range is exactly `v.integer`. -/
structure integers : Prop :=
(hom_inj : function.injective (algebra_map O R))
(map_le_one : ∀ x, v (algebra_map O R x) ≤ 1)
(exists_of_le_one : ∀ ⦃r⦄, v r ≤ 1 → ∃ x, algebra_map O R x = r)
-- typeclass shortcut
instance : algebra v.integer R :=
algebra.of_subring v.integer
theorem integer.integers : v.integers v.integer :=
{ hom_inj := subtype.coe_injective,
map_le_one := λ r, r.2,
exists_of_le_one := λ r hr, ⟨⟨r, hr⟩, rfl⟩ }
namespace integers
variables {v O} (hv : integers v O)
include hv
lemma one_of_is_unit {x : O} (hx : is_unit x) : v (algebra_map O R x) = 1 :=
let ⟨u, hu⟩ := hx in le_antisymm (hv.2 _) $
by { rw [← v.map_one, ← (algebra_map O R).map_one, ← u.mul_inv, ← mul_one (v (algebra_map O R x)),
hu, (algebra_map O R).map_mul, v.map_mul], exact mul_le_mul_left' (hv.2 (u⁻¹ : units O)) _ }
lemma is_unit_of_one {x : O} (hx : is_unit (algebra_map O R x)) (hvx : v (algebra_map O R x) = 1) :
is_unit x :=
let ⟨u, hu⟩ := hx in
have h1 : v u ≤ 1, from hu.symm ▸ hv.2 x,
have h2 : v (u⁻¹ : units R) ≤ 1,
by rw [← one_mul (v _), ← hvx, ← v.map_mul, ← hu, u.mul_inv, hu, hvx, v.map_one],
let ⟨r1, hr1⟩ := hv.3 h1, ⟨r2, hr2⟩ := hv.3 h2 in
⟨⟨r1, r2, hv.1 $ by rw [ring_hom.map_mul, ring_hom.map_one, hr1, hr2, units.mul_inv],
hv.1 $ by rw [ring_hom.map_mul, ring_hom.map_one, hr1, hr2, units.inv_mul]⟩,
hv.1 $ hr1.trans hu⟩
lemma le_of_dvd {x y : O} (h : x ∣ y) : v (algebra_map O R y) ≤ v (algebra_map O R x) :=
let ⟨z, hz⟩ := h in by { rw [← mul_one (v (algebra_map O R x)), hz, ring_hom.map_mul, v.map_mul],
exact mul_le_mul_left' (hv.2 z) _ }
end integers
end comm_ring
section field
variables {F : Type u} {Γ₀ : Type v} [field F] [linear_ordered_comm_group_with_zero Γ₀]
variables {v : valuation F Γ₀} {O : Type w} [comm_ring O] [algebra O F] (hv : integers v O)
include hv
namespace integers
lemma dvd_of_le {x y : O} (h : v (algebra_map O F x) ≤ v (algebra_map O F y)) : y ∣ x :=
classical.by_cases (λ hy : algebra_map O F y = 0, have hx : x = 0,
from hv.1 $ (algebra_map O F).map_zero.symm ▸
(v.zero_iff.1 $ le_zero_iff.1 (v.map_zero ▸ hy ▸ h)),
hx.symm ▸ dvd_zero y) $
λ hy : algebra_map O F y ≠ 0,
have v ((algebra_map O F y)⁻¹ * algebra_map O F x) ≤ 1,
by { rw [← v.map_one, ← inv_mul_cancel hy, v.map_mul, v.map_mul], exact mul_le_mul_left' h _ },
let ⟨z, hz⟩ := hv.3 this in
⟨z, hv.1 $ ((algebra_map O F).map_mul y z).symm ▸ hz.symm ▸ (mul_inv_cancel_left' hy _).symm⟩
lemma dvd_iff_le {x y : O} : x ∣ y ↔ v (algebra_map O F y) ≤ v (algebra_map O F x) :=
⟨hv.le_of_dvd, hv.dvd_of_le⟩
lemma le_iff_dvd {x y : O} : v (algebra_map O F x) ≤ v (algebra_map O F y) ↔ y ∣ x :=
⟨hv.dvd_of_le, hv.le_of_dvd⟩
end integers
end field
end valuation
|
9c625608e41cc358f5add99ede3535cd588567db | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/data/nat/pow.lean | c41eaf25c9ec6865cf8070e7515c35d316c9f1c3 | [
"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 | 11,621 | lean | /-
Copyright (c) 2014 Floris van Doorn (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn, Leonardo de Moura, Jeremy Avigad, Mario Carneiro
-/
import data.nat.basic
import algebra.group_power.order
/-! # `nat.pow`
Results on the power operation on natural numbers.
-/
namespace nat
/-! ### `pow` -/
-- This is redundant with `canonically_ordered_semiring.pow_le_pow_of_le_left`,
-- but `canonically_ordered_semiring` is not such an obvious abstraction, and also quite long.
-- So, we leave a version in the `nat` namespace as well.
-- (The global `pow_le_pow_of_le_left` needs an extra hypothesis `0 ≤ x`.)
protected theorem pow_le_pow_of_le_left {x y : ℕ} (H : x ≤ y) : ∀ i : ℕ, x^i ≤ y^i :=
canonically_ordered_semiring.pow_le_pow_of_le_left H
theorem pow_le_pow_of_le_right {x : ℕ} (H : x > 0) {i : ℕ} : ∀ {j}, i ≤ j → x^i ≤ x^j
| 0 h := by rw eq_zero_of_le_zero h; apply le_refl
| (succ j) h := h.lt_or_eq_dec.elim
(λhl, by rw [pow_succ', ← nat.mul_one (x^i)]; exact
nat.mul_le_mul (pow_le_pow_of_le_right $ le_of_lt_succ hl) H)
(λe, by rw e; refl)
theorem pow_lt_pow_of_lt_left {x y : ℕ} (H : x < y) {i} (h : 0 < i) : x^i < y^i :=
begin
cases i with i, { exact absurd h (not_lt_zero _) },
rw [pow_succ', pow_succ'],
exact nat.mul_lt_mul' (nat.pow_le_pow_of_le_left (le_of_lt H) _) H
(pow_pos (lt_of_le_of_lt (zero_le _) H) _)
end
theorem pow_lt_pow_of_lt_right {x : ℕ} (H : x > 1) {i j : ℕ} (h : i < j) : x^i < x^j :=
begin
have xpos := lt_of_succ_lt H,
refine lt_of_lt_of_le _ (pow_le_pow_of_le_right xpos h),
rw [← nat.mul_one (x^i), pow_succ'],
exact nat.mul_lt_mul_of_pos_left H (pow_pos xpos _)
end
-- TODO: Generalize?
lemma pow_lt_pow_succ {p : ℕ} (h : 1 < p) (n : ℕ) : p^n < p^(n+1) :=
suffices 1*p^n < p*p^n, by simpa [pow_succ],
nat.mul_lt_mul_of_pos_right h (pow_pos (lt_of_succ_lt h) n)
lemma lt_pow_self {p : ℕ} (h : 1 < p) : ∀ n : ℕ, n < p ^ n
| 0 := by simp [zero_lt_one]
| (n+1) := calc
n + 1 < p^n + 1 : nat.add_lt_add_right (lt_pow_self _) _
... ≤ p ^ (n+1) : pow_lt_pow_succ h _
lemma lt_two_pow (n : ℕ) : n < 2^n :=
lt_pow_self dec_trivial n
lemma one_le_pow (n m : ℕ) (h : 0 < m) : 1 ≤ m^n :=
by { rw ←one_pow n, exact nat.pow_le_pow_of_le_left h n }
lemma one_le_pow' (n m : ℕ) : 1 ≤ (m+1)^n := one_le_pow n (m+1) (succ_pos m)
lemma one_le_two_pow (n : ℕ) : 1 ≤ 2^n := one_le_pow n 2 dec_trivial
lemma one_lt_pow (n m : ℕ) (h₀ : 0 < n) (h₁ : 1 < m) : 1 < m^n :=
by { rw ←one_pow n, exact pow_lt_pow_of_lt_left h₁ h₀ }
lemma one_lt_pow' (n m : ℕ) : 1 < (m+2)^(n+1) :=
one_lt_pow (n+1) (m+2) (succ_pos n) (nat.lt_of_sub_eq_succ rfl)
lemma one_lt_two_pow (n : ℕ) (h₀ : 0 < n) : 1 < 2^n := one_lt_pow n 2 h₀ dec_trivial
lemma one_lt_two_pow' (n : ℕ) : 1 < 2^(n+1) := one_lt_pow (n+1) 2 (succ_pos n) dec_trivial
lemma pow_right_strict_mono {x : ℕ} (k : 2 ≤ x) : strict_mono (λ (n : ℕ), x^n) :=
λ _ _, pow_lt_pow_of_lt_right k
lemma pow_le_iff_le_right {x m n : ℕ} (k : 2 ≤ x) : x^m ≤ x^n ↔ m ≤ n :=
strict_mono.le_iff_le (pow_right_strict_mono k)
lemma pow_lt_iff_lt_right {x m n : ℕ} (k : 2 ≤ x) : x^m < x^n ↔ m < n :=
strict_mono.lt_iff_lt (pow_right_strict_mono k)
lemma pow_right_injective {x : ℕ} (k : 2 ≤ x) : function.injective (λ (n : ℕ), x^n) :=
strict_mono.injective (pow_right_strict_mono k)
lemma pow_left_strict_mono {m : ℕ} (k : 1 ≤ m) : strict_mono (λ (x : ℕ), x^m) :=
λ _ _ h, pow_lt_pow_of_lt_left h k
lemma mul_lt_mul_pow_succ {n a q : ℕ} (a0 : 0 < a) (q1 : 1 < q) :
n * q < a * q ^ (n + 1) :=
begin
rw [pow_succ', ← mul_assoc, mul_lt_mul_right (zero_lt_one.trans q1)],
exact lt_mul_of_one_le_of_lt (nat.succ_le_iff.mpr a0) (nat.lt_pow_self q1 n),
end
end nat
lemma strict_mono.nat_pow {n : ℕ} (hn : 1 ≤ n) {f : ℕ → ℕ} (hf : strict_mono f) :
strict_mono (λ m, (f m) ^ n) :=
(nat.pow_left_strict_mono hn).comp hf
namespace nat
lemma pow_le_iff_le_left {m x y : ℕ} (k : 1 ≤ m) : x^m ≤ y^m ↔ x ≤ y :=
strict_mono.le_iff_le (pow_left_strict_mono k)
lemma pow_lt_iff_lt_left {m x y : ℕ} (k : 1 ≤ m) : x^m < y^m ↔ x < y :=
strict_mono.lt_iff_lt (pow_left_strict_mono k)
lemma pow_left_injective {m : ℕ} (k : 1 ≤ m) : function.injective (λ (x : ℕ), x^m) :=
strict_mono.injective (pow_left_strict_mono k)
theorem sq_sub_sq (a b : ℕ) : a ^ 2 - b ^ 2 = (a + b) * (a - b) :=
by { rw [sq, sq], exact nat.mul_self_sub_mul_self_eq a b }
alias nat.sq_sub_sq ← nat.pow_two_sub_pow_two
/-! ### `pow` and `mod` / `dvd` -/
theorem mod_pow_succ {b : ℕ} (b_pos : 0 < b) (w m : ℕ)
: m % (b^succ w) = b * (m/b % b^w) + m % b :=
begin
apply nat.strong_induction_on m,
clear m,
intros p IH,
cases lt_or_ge p (b^succ w) with h₁ h₁,
-- base case: p < b^succ w
{ have h₂ : p / b < b^w,
{ rw [div_lt_iff_lt_mul p _ b_pos],
simpa [pow_succ'] using h₁ },
rw [mod_eq_of_lt h₁, mod_eq_of_lt h₂],
simp [div_add_mod] },
-- step: p ≥ b^succ w
{ -- Generate condition for induction hypothesis
have h₂ : p - b^succ w < p,
{ apply sub_lt_of_pos_le _ _ (pow_pos b_pos _) h₁ },
-- Apply induction
rw [mod_eq_sub_mod h₁, IH _ h₂],
-- Normalize goal and h1
simp only [pow_succ],
simp only [ge, pow_succ] at h₁,
-- Pull subtraction outside mod and div
rw [sub_mul_mod _ _ _ h₁, sub_mul_div _ _ _ h₁],
-- Cancel subtraction inside mod b^w
have p_b_ge : b^w ≤ p / b,
{ rw [le_div_iff_mul_le _ _ b_pos, mul_comm],
exact h₁ },
rw [eq.symm (mod_eq_sub_mod p_b_ge)] }
end
lemma pow_dvd_pow_iff_pow_le_pow {k l : ℕ} : Π {x : ℕ} (w : 0 < x), x^k ∣ x^l ↔ x^k ≤ x^l
| (x+1) w :=
begin
split,
{ intro a, exact le_of_dvd (pow_pos (succ_pos x) l) a, },
{ intro a, cases x with x,
{ simp only [one_pow], },
{ have le := (pow_le_iff_le_right (le_add_left _ _)).mp a,
use (x+2)^(l-k),
rw [←pow_add, add_comm k, nat.sub_add_cancel le], } }
end
/-- If `1 < x`, then `x^k` divides `x^l` if and only if `k` is at most `l`. -/
lemma pow_dvd_pow_iff_le_right {x k l : ℕ} (w : 1 < x) : x^k ∣ x^l ↔ k ≤ l :=
by rw [pow_dvd_pow_iff_pow_le_pow (lt_of_succ_lt w), pow_le_iff_le_right w]
lemma pow_dvd_pow_iff_le_right' {b k l : ℕ} : (b+2)^k ∣ (b+2)^l ↔ k ≤ l :=
pow_dvd_pow_iff_le_right (nat.lt_of_sub_eq_succ rfl)
lemma not_pos_pow_dvd : ∀ {p k : ℕ} (hp : 1 < p) (hk : 1 < k), ¬ p^k ∣ p
| (succ p) (succ k) hp hk h :=
have succ p * (succ p)^k ∣ succ p * 1, by simpa [pow_succ] using h,
have (succ p) ^ k ∣ 1, from dvd_of_mul_dvd_mul_left (succ_pos _) this,
have he : (succ p) ^ k = 1, from eq_one_of_dvd_one this,
have k < (succ p) ^ k, from lt_pow_self hp k,
have k < 1, by rwa [he] at this,
have k = 0, from eq_zero_of_le_zero $ le_of_lt_succ this,
have 1 < 1, by rwa [this] at hk,
absurd this dec_trivial
lemma pow_dvd_of_le_of_pow_dvd {p m n k : ℕ} (hmn : m ≤ n) (hdiv : p ^ n ∣ k) : p ^ m ∣ k :=
have p ^ m ∣ p ^ n, from pow_dvd_pow _ hmn,
dvd_trans this hdiv
lemma dvd_of_pow_dvd {p k m : ℕ} (hk : 1 ≤ k) (hpk : p^k ∣ m) : p ∣ m :=
by rw ←pow_one p; exact pow_dvd_of_le_of_pow_dvd hk hpk
lemma pow_div {x m n : ℕ} (h : n ≤ m) (hx : 0 < x) : x ^ m / x ^ n = x ^ (m - n) :=
by rw [nat.div_eq_iff_eq_mul_left (pow_pos hx n) (pow_dvd_pow _ h), pow_sub_mul_pow _ h]
/-! ### `shiftl` and `shiftr` -/
lemma shiftl_eq_mul_pow (m) : ∀ n, shiftl m n = m * 2 ^ n
| 0 := (nat.mul_one _).symm
| (k+1) := show bit0 (shiftl m k) = m * (2 * 2 ^ k),
by rw [bit0_val, shiftl_eq_mul_pow, mul_left_comm, mul_comm 2]
lemma shiftl'_tt_eq_mul_pow (m) : ∀ n, shiftl' tt m n + 1 = (m + 1) * 2 ^ n
| 0 := by simp [shiftl, shiftl', pow_zero, nat.one_mul]
| (k+1) :=
begin
change bit1 (shiftl' tt m k) + 1 = (m + 1) * (2 * 2 ^ k),
rw bit1_val,
change 2 * (shiftl' tt m k + 1) = _,
rw [shiftl'_tt_eq_mul_pow, mul_left_comm, mul_comm 2],
end
lemma one_shiftl (n) : shiftl 1 n = 2 ^ n :=
(shiftl_eq_mul_pow _ _).trans (nat.one_mul _)
@[simp] lemma zero_shiftl (n) : shiftl 0 n = 0 :=
(shiftl_eq_mul_pow _ _).trans (nat.zero_mul _)
lemma shiftr_eq_div_pow (m) : ∀ n, shiftr m n = m / 2 ^ n
| 0 := (nat.div_one _).symm
| (k+1) := (congr_arg div2 (shiftr_eq_div_pow k)).trans $
by rw [div2_val, nat.div_div_eq_div_mul, mul_comm]; refl
@[simp] lemma zero_shiftr (n) : shiftr 0 n = 0 :=
(shiftr_eq_div_pow _ _).trans (nat.zero_div _)
theorem shiftl'_ne_zero_left (b) {m} (h : m ≠ 0) (n) : shiftl' b m n ≠ 0 :=
by induction n; simp [shiftl', bit_ne_zero, *]
theorem shiftl'_tt_ne_zero (m) : ∀ {n} (h : n ≠ 0), shiftl' tt m n ≠ 0
| 0 h := absurd rfl h
| (succ n) _ := nat.bit1_ne_zero _
/-! ### `size` -/
@[simp] theorem size_zero : size 0 = 0 := by simp [size]
@[simp] theorem size_bit {b n} (h : bit b n ≠ 0) : size (bit b n) = succ (size n) :=
begin
rw size,
conv { to_lhs, rw [binary_rec], simp [h] },
rw div2_bit,
end
@[simp] theorem size_bit0 {n} (h : n ≠ 0) : size (bit0 n) = succ (size n) :=
@size_bit ff n (nat.bit0_ne_zero h)
@[simp] theorem size_bit1 (n) : size (bit1 n) = succ (size n) :=
@size_bit tt n (nat.bit1_ne_zero n)
@[simp] theorem size_one : size 1 = 1 :=
show size (bit1 0) = 1, by rw [size_bit1, size_zero]
@[simp] theorem size_shiftl' {b m n} (h : shiftl' b m n ≠ 0) :
size (shiftl' b m n) = size m + n :=
begin
induction n with n IH; simp [shiftl'] at h ⊢,
rw [size_bit h, nat.add_succ],
by_cases s0 : shiftl' b m n = 0; [skip, rw [IH s0]],
rw s0 at h ⊢,
cases b, {exact absurd rfl h},
have : shiftl' tt m n + 1 = 1 := congr_arg (+1) s0,
rw [shiftl'_tt_eq_mul_pow] at this,
have m0 := succ.inj (eq_one_of_dvd_one ⟨_, this.symm⟩),
subst m0,
simp at this,
have : n = 0 := eq_zero_of_le_zero (le_of_not_gt $ λ hn,
ne_of_gt (pow_lt_pow_of_lt_right dec_trivial hn) this),
subst n, refl
end
@[simp] theorem size_shiftl {m} (h : m ≠ 0) (n) :
size (shiftl m n) = size m + n :=
size_shiftl' (shiftl'_ne_zero_left _ h _)
theorem lt_size_self (n : ℕ) : n < 2^size n :=
begin
rw [← one_shiftl],
have : ∀ {n}, n = 0 → n < shiftl 1 (size n), { simp },
apply binary_rec _ _ n, {apply this rfl},
intros b n IH,
by_cases bit b n = 0, {apply this h},
rw [size_bit h, shiftl_succ],
exact bit_lt_bit0 _ IH
end
theorem size_le {m n : ℕ} : size m ≤ n ↔ m < 2^n :=
⟨λ h, lt_of_lt_of_le (lt_size_self _) (pow_le_pow_of_le_right dec_trivial h),
begin
rw [← one_shiftl], revert n,
apply binary_rec _ _ m,
{ intros n h, simp },
{ intros b m IH n h,
by_cases e : bit b m = 0, { simp [e] },
rw [size_bit e],
cases n with n,
{ exact e.elim (eq_zero_of_le_zero (le_of_lt_succ h)) },
{ apply succ_le_succ (IH _),
apply lt_imp_lt_of_le_imp_le (λ h', bit0_le_bit _ h') h } }
end⟩
theorem lt_size {m n : ℕ} : m < size n ↔ 2^m ≤ n :=
by rw [← not_lt, decidable.iff_not_comm, not_lt, size_le]
theorem size_pos {n : ℕ} : 0 < size n ↔ 0 < n :=
by rw lt_size; refl
theorem size_eq_zero {n : ℕ} : size n = 0 ↔ n = 0 :=
by have := @size_pos n; simp [pos_iff_ne_zero] at this;
exact decidable.not_iff_not.1 this
theorem size_pow {n : ℕ} : size (2^n) = n+1 :=
le_antisymm
(size_le.2 $ pow_lt_pow_of_lt_right dec_trivial (lt_succ_self _))
(lt_size.2 $ le_refl _)
theorem size_le_size {m n : ℕ} (h : m ≤ n) : size m ≤ size n :=
size_le.2 $ lt_of_le_of_lt h (lt_size_self _)
end nat
|
3436f3346968ce3f1a83e5c5f3e6d39696777cc7 | bb31430994044506fa42fd667e2d556327e18dfe | /src/data/set/function.lean | ad181e2038170849a332fef3b20290c0837e79dc | [
"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 | 60,791 | lean | /-
Copyright (c) 2014 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Andrew Zipperer, Haitao Zhang, Minchao Wu, Yury Kudryashov
-/
import data.set.prod
import logic.function.conjugate
/-!
# Functions over sets
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
## Main definitions
### Predicate
* `set.eq_on f₁ f₂ s` : functions `f₁` and `f₂` are equal at every point of `s`;
* `set.maps_to f s t` : `f` sends every point of `s` to a point of `t`;
* `set.inj_on f s` : restriction of `f` to `s` is injective;
* `set.surj_on f s t` : every point in `s` has a preimage in `s`;
* `set.bij_on f s t` : `f` is a bijection between `s` and `t`;
* `set.left_inv_on f' f s` : for every `x ∈ s` we have `f' (f x) = x`;
* `set.right_inv_on f' f t` : for every `y ∈ t` we have `f (f' y) = y`;
* `set.inv_on f' f s t` : `f'` is a two-side inverse of `f` on `s` and `t`, i.e.
we have `set.left_inv_on f' f s` and `set.right_inv_on f' f t`.
### Functions
* `set.restrict f s` : restrict the domain of `f` to the set `s`;
* `set.cod_restrict f s h` : given `h : ∀ x, f x ∈ s`, restrict the codomain of `f` to the set `s`;
* `set.maps_to.restrict f s t h`: given `h : maps_to f s t`, restrict the domain of `f` to `s`
and the codomain to `t`.
-/
universes u v w x y
variables {α : Type u} {β : Type v} {π : α → Type v} {γ : Type w} {ι : Sort x}
open equiv equiv.perm function
namespace set
/-! ### Restrict -/
/-- Restrict domain of a function `f` to a set `s`. Same as `subtype.restrict` but this version
takes an argument `↥s` instead of `subtype s`. -/
def restrict (s : set α) (f : Π a : α, π a) : Π a : s, π a := λ x, f x
lemma restrict_eq (f : α → β) (s : set α) : s.restrict f = f ∘ coe := rfl
@[simp] lemma restrict_apply (f : α → β) (s : set α) (x : s) : s.restrict f x = f x := rfl
lemma restrict_eq_iff {f : Π a, π a} {s : set α} {g : Π a : s, π a} :
restrict s f = g ↔ ∀ a (ha : a ∈ s), f a = g ⟨a, ha⟩ :=
funext_iff.trans subtype.forall
lemma eq_restrict_iff {s : set α} {f : Π a : s, π a} {g : Π a, π a} :
f = restrict s g ↔ ∀ a (ha : a ∈ s), f ⟨a, ha⟩ = g a :=
funext_iff.trans subtype.forall
@[simp] lemma range_restrict (f : α → β) (s : set α) : set.range (s.restrict f) = f '' s :=
(range_comp _ _).trans $ congr_arg (('') f) subtype.range_coe
lemma image_restrict (f : α → β) (s t : set α) : s.restrict f '' (coe ⁻¹' t) = f '' (t ∩ s) :=
by rw [restrict, image_comp, image_preimage_eq_inter_range, subtype.range_coe]
@[simp] lemma restrict_dite {s : set α} [∀ x, decidable (x ∈ s)] (f : Π a ∈ s, β) (g : Π a ∉ s, β) :
s.restrict (λ a, if h : a ∈ s then f a h else g a h) = λ a, f a a.2 :=
funext $ λ a, dif_pos a.2
@[simp] lemma restrict_dite_compl {s : set α} [∀ x, decidable (x ∈ s)] (f : Π a ∈ s, β)
(g : Π a ∉ s, β) :
sᶜ.restrict (λ a, if h : a ∈ s then f a h else g a h) = λ a, g a a.2 :=
funext $ λ a, dif_neg a.2
@[simp] lemma restrict_ite (f g : α → β) (s : set α) [∀ x, decidable (x ∈ s)] :
s.restrict (λ a, if a ∈ s then f a else g a) = s.restrict f :=
restrict_dite _ _
@[simp] lemma restrict_ite_compl (f g : α → β) (s : set α) [∀ x, decidable (x ∈ s)] :
sᶜ.restrict (λ a, if a ∈ s then f a else g a) = sᶜ.restrict g :=
restrict_dite_compl _ _
@[simp] lemma restrict_piecewise (f g : α → β) (s : set α) [∀ x, decidable (x ∈ s)] :
s.restrict (piecewise s f g) = s.restrict f :=
restrict_ite _ _ _
@[simp] lemma restrict_piecewise_compl (f g : α → β) (s : set α) [∀ x, decidable (x ∈ s)] :
sᶜ.restrict (piecewise s f g) = sᶜ.restrict g :=
restrict_ite_compl _ _ _
lemma restrict_extend_range (f : α → β) (g : α → γ) (g' : β → γ) :
(range f).restrict (extend f g g') = λ x, g x.coe_prop.some :=
by convert restrict_dite _ _
@[simp] lemma restrict_extend_compl_range (f : α → β) (g : α → γ) (g' : β → γ) :
(range f)ᶜ.restrict (extend f g g') = g' ∘ coe :=
by convert restrict_dite_compl _ _
lemma range_extend_subset (f : α → β) (g : α → γ) (g' : β → γ) :
range (extend f g g') ⊆ range g ∪ g' '' (range f)ᶜ :=
begin
classical,
rintro _ ⟨y, rfl⟩,
rw extend_def, split_ifs,
exacts [or.inl (mem_range_self _), or.inr (mem_image_of_mem _ h)]
end
lemma range_extend {f : α → β} (hf : injective f) (g : α → γ) (g' : β → γ) :
range (extend f g g') = range g ∪ g' '' (range f)ᶜ :=
begin
refine (range_extend_subset _ _ _).antisymm _,
rintro z (⟨x, rfl⟩|⟨y, hy, rfl⟩),
exacts [⟨f x, hf.extend_apply _ _ _⟩, ⟨y, extend_apply' _ _ _ hy⟩]
end
/-- Restrict codomain of a function `f` to a set `s`. Same as `subtype.coind` but this version
has codomain `↥s` instead of `subtype s`. -/
def cod_restrict (f : ι → α) (s : set α) (h : ∀ x, f x ∈ s) : ι → s :=
λ x, ⟨f x, h x⟩
@[simp] lemma coe_cod_restrict_apply (f : ι → α) (s : set α) (h : ∀ x, f x ∈ s) (x : ι) :
(cod_restrict f s h x : α) = f x :=
rfl
@[simp] lemma restrict_comp_cod_restrict {f : ι → α} {g : α → β} {b : set α}
(h : ∀ x, f x ∈ b) : (b.restrict g) ∘ (b.cod_restrict f h) = g ∘ f := rfl
@[simp] lemma injective_cod_restrict {f : ι → α} {s : set α} (h : ∀ x, f x ∈ s) :
injective (cod_restrict f s h) ↔ injective f :=
by simp only [injective, subtype.ext_iff, coe_cod_restrict_apply]
alias injective_cod_restrict ↔ _ _root_.function.injective.cod_restrict
variables {s s₁ s₂ : set α} {t t₁ t₂ : set β} {p : set γ} {f f₁ f₂ f₃ : α → β} {g g₁ g₂ : β → γ}
{f' f₁' f₂' : β → α} {g' : γ → β} {a : α} {b : β}
/-! ### Equality on a set -/
/-- Two functions `f₁ f₂ : α → β` are equal on `s`
if `f₁ x = f₂ x` for all `x ∈ a`. -/
def eq_on (f₁ f₂ : α → β) (s : set α) : Prop :=
∀ ⦃x⦄, x ∈ s → f₁ x = f₂ x
@[simp] lemma eq_on_empty (f₁ f₂ : α → β) : eq_on f₁ f₂ ∅ := λ x, false.elim
@[simp] lemma eq_on_singleton : eq_on f₁ f₂ {a} ↔ f₁ a = f₂ a := by simp [set.eq_on]
@[simp] lemma restrict_eq_restrict_iff : restrict s f₁ = restrict s f₂ ↔ eq_on f₁ f₂ s :=
restrict_eq_iff
@[symm] lemma eq_on.symm (h : eq_on f₁ f₂ s) : eq_on f₂ f₁ s :=
λ x hx, (h hx).symm
lemma eq_on_comm : eq_on f₁ f₂ s ↔ eq_on f₂ f₁ s :=
⟨eq_on.symm, eq_on.symm⟩
@[refl] lemma eq_on_refl (f : α → β) (s : set α) : eq_on f f s :=
λ _ _, rfl
@[trans] lemma eq_on.trans (h₁ : eq_on f₁ f₂ s) (h₂ : eq_on f₂ f₃ s) : eq_on f₁ f₃ s :=
λ x hx, (h₁ hx).trans (h₂ hx)
theorem eq_on.image_eq (heq : eq_on f₁ f₂ s) : f₁ '' s = f₂ '' s :=
image_congr heq
theorem eq_on.inter_preimage_eq (heq : eq_on f₁ f₂ s) (t : set β) : s ∩ f₁ ⁻¹' t = s ∩ f₂ ⁻¹' t :=
ext $ λ x, and.congr_right_iff.2 $ λ hx, by rw [mem_preimage, mem_preimage, heq hx]
lemma eq_on.mono (hs : s₁ ⊆ s₂) (hf : eq_on f₁ f₂ s₂) : eq_on f₁ f₂ s₁ :=
λ x hx, hf (hs hx)
@[simp] lemma eq_on_union : eq_on f₁ f₂ (s₁ ∪ s₂) ↔ eq_on f₁ f₂ s₁ ∧ eq_on f₁ f₂ s₂ :=
ball_or_left_distrib
lemma eq_on.union (h₁ : eq_on f₁ f₂ s₁) (h₂ : eq_on f₁ f₂ s₂) : eq_on f₁ f₂ (s₁ ∪ s₂) :=
eq_on_union.2 ⟨h₁, h₂⟩
lemma eq_on.comp_left (h : s.eq_on f₁ f₂) : s.eq_on (g ∘ f₁) (g ∘ f₂) := λ a ha, congr_arg _ $ h ha
@[simp] lemma eq_on_range {ι : Sort*} {f : ι → α} {g₁ g₂ : α → β} :
eq_on g₁ g₂ (range f) ↔ g₁ ∘ f = g₂ ∘ f :=
forall_range_iff.trans $ funext_iff.symm
alias eq_on_range ↔ eq_on.comp_eq _
/-! ### Congruence lemmas -/
section order
variables [preorder α] [preorder β]
lemma _root_.monotone_on.congr (h₁ : monotone_on f₁ s) (h : s.eq_on f₁ f₂) : monotone_on f₂ s :=
begin
intros a ha b hb hab,
rw [←h ha, ←h hb],
exact h₁ ha hb hab,
end
lemma _root_.antitone_on.congr (h₁ : antitone_on f₁ s) (h : s.eq_on f₁ f₂) : antitone_on f₂ s :=
h₁.dual_right.congr h
lemma _root_.strict_mono_on.congr (h₁ : strict_mono_on f₁ s) (h : s.eq_on f₁ f₂) :
strict_mono_on f₂ s :=
begin
intros a ha b hb hab,
rw [←h ha, ←h hb],
exact h₁ ha hb hab,
end
lemma _root_.strict_anti_on.congr (h₁ : strict_anti_on f₁ s) (h : s.eq_on f₁ f₂) :
strict_anti_on f₂ s :=
h₁.dual_right.congr h
lemma eq_on.congr_monotone_on (h : s.eq_on f₁ f₂) : monotone_on f₁ s ↔ monotone_on f₂ s :=
⟨λ h₁, h₁.congr h, λ h₂, h₂.congr h.symm⟩
lemma eq_on.congr_antitone_on (h : s.eq_on f₁ f₂) : antitone_on f₁ s ↔ antitone_on f₂ s :=
⟨λ h₁, h₁.congr h, λ h₂, h₂.congr h.symm⟩
lemma eq_on.congr_strict_mono_on (h : s.eq_on f₁ f₂) : strict_mono_on f₁ s ↔ strict_mono_on f₂ s :=
⟨λ h₁, h₁.congr h, λ h₂, h₂.congr h.symm⟩
lemma eq_on.congr_strict_anti_on (h : s.eq_on f₁ f₂) : strict_anti_on f₁ s ↔ strict_anti_on f₂ s :=
⟨λ h₁, h₁.congr h, λ h₂, h₂.congr h.symm⟩
end order
/-! ### Mono lemmas-/
section mono
variables [preorder α] [preorder β]
lemma _root_.monotone_on.mono (h : monotone_on f s) (h' : s₂ ⊆ s) : monotone_on f s₂ :=
λ x hx y hy, h (h' hx) (h' hy)
lemma _root_.antitone_on.mono (h : antitone_on f s) (h' : s₂ ⊆ s) : antitone_on f s₂ :=
λ x hx y hy, h (h' hx) (h' hy)
lemma _root_.strict_mono_on.mono (h : strict_mono_on f s) (h' : s₂ ⊆ s) : strict_mono_on f s₂ :=
λ x hx y hy, h (h' hx) (h' hy)
lemma _root_.strict_anti_on.mono (h : strict_anti_on f s) (h' : s₂ ⊆ s) : strict_anti_on f s₂ :=
λ x hx y hy, h (h' hx) (h' hy)
protected lemma _root_.monotone_on.monotone (h : monotone_on f s) : monotone (f ∘ coe : s → β) :=
λ x y hle, h x.coe_prop y.coe_prop hle
protected lemma _root_.antitone_on.monotone (h : antitone_on f s) : antitone (f ∘ coe : s → β) :=
λ x y hle, h x.coe_prop y.coe_prop hle
protected lemma _root_.strict_mono_on.strict_mono (h : strict_mono_on f s) :
strict_mono (f ∘ coe : s → β) :=
λ x y hlt, h x.coe_prop y.coe_prop hlt
protected lemma _root_.strict_anti_on.strict_anti (h : strict_anti_on f s) :
strict_anti (f ∘ coe : s → β) :=
λ x y hlt, h x.coe_prop y.coe_prop hlt
end mono
/-! ### maps to -/
/-- `maps_to f a b` means that the image of `a` is contained in `b`. -/
def maps_to (f : α → β) (s : set α) (t : set β) : Prop := ∀ ⦃x⦄, x ∈ s → f x ∈ t
/-- Given a map `f` sending `s : set α` into `t : set β`, restrict domain of `f` to `s`
and the codomain to `t`. Same as `subtype.map`. -/
def maps_to.restrict (f : α → β) (s : set α) (t : set β) (h : maps_to f s t) :
s → t :=
subtype.map f h
@[simp] lemma maps_to.coe_restrict_apply (h : maps_to f s t) (x : s) :
(h.restrict f s t x : β) = f x := rfl
/-- Restricting the domain and then the codomain is the same as `maps_to.restrict`. -/
@[simp] lemma cod_restrict_restrict (h : ∀ x : s, f x ∈ t) :
cod_restrict (s.restrict f) t h = maps_to.restrict f s t (λ x hx, h ⟨x, hx⟩) := rfl
/-- Reverse of `set.cod_restrict_restrict`. -/
lemma maps_to.restrict_eq_cod_restrict (h : maps_to f s t) :
h.restrict f s t = cod_restrict (s.restrict f) t (λ x, h x.2) := rfl
lemma maps_to.coe_restrict (h : set.maps_to f s t) :
coe ∘ h.restrict f s t = s.restrict f := rfl
lemma maps_to.range_restrict (f : α → β) (s : set α) (t : set β) (h : maps_to f s t) :
range (h.restrict f s t) = coe ⁻¹' (f '' s) :=
set.range_subtype_map f h
lemma maps_to_iff_exists_map_subtype : maps_to f s t ↔ ∃ g : s → t, ∀ x : s, f x = g x :=
⟨λ h, ⟨h.restrict f s t, λ _, rfl⟩,
λ ⟨g, hg⟩ x hx, by { erw [hg ⟨x, hx⟩], apply subtype.coe_prop }⟩
theorem maps_to' : maps_to f s t ↔ f '' s ⊆ t :=
image_subset_iff.symm
lemma maps_to.subset_preimage {f : α → β} {s : set α} {t : set β} (hf : maps_to f s t) :
s ⊆ f ⁻¹' t := hf
theorem maps_to_empty (f : α → β) (t : set β) : maps_to f ∅ t := empty_subset _
@[simp] lemma maps_to_singleton : maps_to f {a} t ↔ f a ∈ t := singleton_subset_iff
theorem maps_to.image_subset (h : maps_to f s t) : f '' s ⊆ t :=
maps_to'.1 h
theorem maps_to.congr (h₁ : maps_to f₁ s t) (h : eq_on f₁ f₂ s) :
maps_to f₂ s t :=
λ x hx, h hx ▸ h₁ hx
lemma eq_on.comp_right (hg : t.eq_on g₁ g₂) (hf : s.maps_to f t) : s.eq_on (g₁ ∘ f) (g₂ ∘ f) :=
λ a ha, hg $ hf ha
theorem eq_on.maps_to_iff (H : eq_on f₁ f₂ s) : maps_to f₁ s t ↔ maps_to f₂ s t :=
⟨λ h, h.congr H, λ h, h.congr H.symm⟩
theorem maps_to.comp (h₁ : maps_to g t p) (h₂ : maps_to f s t) : maps_to (g ∘ f) s p :=
λ x h, h₁ (h₂ h)
theorem maps_to_id (s : set α) : maps_to id s s := λ x, id
theorem maps_to.iterate {f : α → α} {s : set α} (h : maps_to f s s) :
∀ n, maps_to (f^[n]) s s
| 0 := λ _, id
| (n+1) := (maps_to.iterate n).comp h
theorem maps_to.iterate_restrict {f : α → α} {s : set α} (h : maps_to f s s) (n : ℕ) :
(h.restrict f s s^[n]) = (h.iterate n).restrict _ _ _ :=
begin
funext x,
rw [subtype.ext_iff, maps_to.coe_restrict_apply],
induction n with n ihn generalizing x,
{ refl },
{ simp [nat.iterate, ihn] }
end
lemma maps_to_of_subsingleton' [subsingleton β] (f : α → β) (h : s.nonempty → t.nonempty) :
maps_to f s t :=
λ a ha, subsingleton.mem_iff_nonempty.2 $ h ⟨a, ha⟩
lemma maps_to_of_subsingleton [subsingleton α] (f : α → α) (s : set α) : maps_to f s s :=
maps_to_of_subsingleton' _ id
theorem maps_to.mono (hf : maps_to f s₁ t₁) (hs : s₂ ⊆ s₁) (ht : t₁ ⊆ t₂) :
maps_to f s₂ t₂ :=
λ x hx, ht (hf $ hs hx)
theorem maps_to.mono_left (hf : maps_to f s₁ t) (hs : s₂ ⊆ s₁) : maps_to f s₂ t :=
λ x hx, hf (hs hx)
theorem maps_to.mono_right (hf : maps_to f s t₁) (ht : t₁ ⊆ t₂) : maps_to f s t₂ :=
λ x hx, ht (hf hx)
theorem maps_to.union_union (h₁ : maps_to f s₁ t₁) (h₂ : maps_to f s₂ t₂) :
maps_to f (s₁ ∪ s₂) (t₁ ∪ t₂) :=
λ x hx, hx.elim (λ hx, or.inl $ h₁ hx) (λ hx, or.inr $ h₂ hx)
theorem maps_to.union (h₁ : maps_to f s₁ t) (h₂ : maps_to f s₂ t) :
maps_to f (s₁ ∪ s₂) t :=
union_self t ▸ h₁.union_union h₂
@[simp] theorem maps_to_union : maps_to f (s₁ ∪ s₂) t ↔ maps_to f s₁ t ∧ maps_to f s₂ t :=
⟨λ h, ⟨h.mono (subset_union_left s₁ s₂) (subset.refl t),
h.mono (subset_union_right s₁ s₂) (subset.refl t)⟩, λ h, h.1.union h.2⟩
theorem maps_to.inter (h₁ : maps_to f s t₁) (h₂ : maps_to f s t₂) :
maps_to f s (t₁ ∩ t₂) :=
λ x hx, ⟨h₁ hx, h₂ hx⟩
theorem maps_to.inter_inter (h₁ : maps_to f s₁ t₁) (h₂ : maps_to f s₂ t₂) :
maps_to f (s₁ ∩ s₂) (t₁ ∩ t₂) :=
λ x hx, ⟨h₁ hx.1, h₂ hx.2⟩
@[simp] theorem maps_to_inter : maps_to f s (t₁ ∩ t₂) ↔ maps_to f s t₁ ∧ maps_to f s t₂ :=
⟨λ h, ⟨h.mono (subset.refl s) (inter_subset_left t₁ t₂),
h.mono (subset.refl s) (inter_subset_right t₁ t₂)⟩, λ h, h.1.inter h.2⟩
theorem maps_to_univ (f : α → β) (s : set α) : maps_to f s univ := λ x h, trivial
theorem maps_to_image (f : α → β) (s : set α) : maps_to f s (f '' s) := by rw maps_to'
theorem maps_to_preimage (f : α → β) (t : set β) : maps_to f (f ⁻¹' t) t := subset.refl _
theorem maps_to_range (f : α → β) (s : set α) : maps_to f s (range f) :=
(maps_to_image f s).mono (subset.refl s) (image_subset_range _ _)
@[simp] lemma maps_image_to (f : α → β) (g : γ → α) (s : set γ) (t : set β) :
maps_to f (g '' s) t ↔ maps_to (f ∘ g) s t :=
⟨λ h c hc, h ⟨c, hc, rfl⟩, λ h d ⟨c, hc⟩, hc.2 ▸ h hc.1⟩
lemma maps_to.comp_left (g : β → γ) (hf : maps_to f s t) : maps_to (g ∘ f) s (g '' t) :=
λ x hx, ⟨f x, hf hx, rfl⟩
lemma maps_to.comp_right {s : set β} {t : set γ} (hg : maps_to g s t) (f : α → β) :
maps_to (g ∘ f) (f ⁻¹' s) t := λ x hx, hg hx
@[simp] lemma maps_univ_to (f : α → β) (s : set β) :
maps_to f univ s ↔ ∀ a, f a ∈ s :=
⟨λ h a, h (mem_univ _), λ h x _, h x⟩
@[simp] lemma maps_range_to (f : α → β) (g : γ → α) (s : set β) :
maps_to f (range g) s ↔ maps_to (f ∘ g) univ s :=
by rw [←image_univ, maps_image_to]
theorem surjective_maps_to_image_restrict (f : α → β) (s : set α) :
surjective ((maps_to_image f s).restrict f s (f '' s)) :=
λ ⟨y, x, hs, hxy⟩, ⟨⟨x, hs⟩, subtype.ext hxy⟩
theorem maps_to.mem_iff (h : maps_to f s t) (hc : maps_to f sᶜ tᶜ) {x} : f x ∈ t ↔ x ∈ s :=
⟨λ ht, by_contra $ λ hs, hc hs ht, λ hx, h hx⟩
/-! ### Restriction onto preimage -/
section
variables (t f)
/-- The restriction of a function onto the preimage of a set. -/
@[simps] def restrict_preimage : f ⁻¹' t → t :=
(set.maps_to_preimage f t).restrict _ _ _
lemma range_restrict_preimage :
range (t.restrict_preimage f) = coe ⁻¹' (range f) :=
begin
delta set.restrict_preimage,
rw [maps_to.range_restrict, set.image_preimage_eq_inter_range,
set.preimage_inter, subtype.coe_preimage_self, set.univ_inter],
end
variables {f} {U : ι → set β}
lemma restrict_preimage_injective (hf : injective f) : injective (t.restrict_preimage f) :=
λ x y e, subtype.mk.inj_arrow e (λ e, subtype.coe_injective (hf e))
lemma restrict_preimage_surjective (hf : surjective f) : surjective (t.restrict_preimage f) :=
λ x, ⟨⟨_, (show f (hf x).some ∈ t, from (hf x).some_spec.symm ▸ x.2)⟩, subtype.ext (hf x).some_spec⟩
lemma restrict_preimage_bijective (hf : bijective f) : bijective (t.restrict_preimage f) :=
⟨t.restrict_preimage_injective hf.1, t.restrict_preimage_surjective hf.2⟩
alias set.restrict_preimage_injective ← _root_.function.injective.restrict_preimage
alias set.restrict_preimage_surjective ← _root_.function.surjective.restrict_preimage
alias set.restrict_preimage_bijective ← _root_.function.bijective.restrict_preimage
end
/-! ### Injectivity on a set -/
/-- `f` is injective on `a` if the restriction of `f` to `a` is injective. -/
def inj_on (f : α → β) (s : set α) : Prop :=
∀ ⦃x₁ : α⦄, x₁ ∈ s → ∀ ⦃x₂ : α⦄, x₂ ∈ s → f x₁ = f x₂ → x₁ = x₂
theorem subsingleton.inj_on (hs : s.subsingleton) (f : α → β) : inj_on f s :=
λ x hx y hy h, hs hx hy
@[simp] theorem inj_on_empty (f : α → β) : inj_on f ∅ :=
subsingleton_empty.inj_on f
@[simp] theorem inj_on_singleton (f : α → β) (a : α) : inj_on f {a} :=
subsingleton_singleton.inj_on f
theorem inj_on.eq_iff {x y} (h : inj_on f s) (hx : x ∈ s) (hy : y ∈ s) :
f x = f y ↔ x = y :=
⟨h hx hy, λ h, h ▸ rfl⟩
lemma inj_on.ne_iff {x y} (h : inj_on f s) (hx : x ∈ s) (hy : y ∈ s) : f x ≠ f y ↔ x ≠ y :=
(h.eq_iff hx hy).not
alias inj_on.ne_iff ↔ _ inj_on.ne
theorem inj_on.congr (h₁ : inj_on f₁ s) (h : eq_on f₁ f₂ s) :
inj_on f₂ s :=
λ x hx y hy, h hx ▸ h hy ▸ h₁ hx hy
theorem eq_on.inj_on_iff (H : eq_on f₁ f₂ s) : inj_on f₁ s ↔ inj_on f₂ s :=
⟨λ h, h.congr H, λ h, h.congr H.symm⟩
theorem inj_on.mono (h : s₁ ⊆ s₂) (ht : inj_on f s₂) : inj_on f s₁ :=
λ x hx y hy H, ht (h hx) (h hy) H
theorem inj_on_union (h : disjoint s₁ s₂) :
inj_on f (s₁ ∪ s₂) ↔ inj_on f s₁ ∧ inj_on f s₂ ∧ ∀ (x ∈ s₁) (y ∈ s₂), f x ≠ f y :=
begin
refine ⟨λ H, ⟨H.mono $ subset_union_left _ _, H.mono $ subset_union_right _ _, _⟩, _⟩,
{ intros x hx y hy hxy,
obtain rfl : x = y, from H (or.inl hx) (or.inr hy) hxy,
exact h.le_bot ⟨hx, hy⟩ },
{ rintro ⟨h₁, h₂, h₁₂⟩,
rintro x (hx|hx) y (hy|hy) hxy,
exacts [h₁ hx hy hxy, (h₁₂ _ hx _ hy hxy).elim, (h₁₂ _ hy _ hx hxy.symm).elim, h₂ hx hy hxy] }
end
theorem inj_on_insert {f : α → β} {s : set α} {a : α} (has : a ∉ s) :
set.inj_on f (insert a s) ↔ set.inj_on f s ∧ f a ∉ f '' s :=
have disjoint s {a}, from disjoint_iff_inf_le.mpr $ λ x ⟨hxs, (hxa : x = a)⟩, has (hxa ▸ hxs),
by { rw [← union_singleton, inj_on_union this], simp }
lemma injective_iff_inj_on_univ : injective f ↔ inj_on f univ :=
⟨λ h x hx y hy hxy, h hxy, λ h _ _ heq, h trivial trivial heq⟩
lemma inj_on_of_injective (h : injective f) (s : set α) : inj_on f s :=
λ x hx y hy hxy, h hxy
alias inj_on_of_injective ← _root_.function.injective.inj_on
lemma inj_on_id (s : set α) : inj_on id s := injective_id.inj_on _
theorem inj_on.comp (hg : inj_on g t) (hf: inj_on f s) (h : maps_to f s t) :
inj_on (g ∘ f) s :=
λ x hx y hy heq, hf hx hy $ hg (h hx) (h hy) heq
lemma inj_on.iterate {f : α → α} {s : set α} (h : inj_on f s) (hf : maps_to f s s) :
∀ n, inj_on (f^[n]) s
| 0 := inj_on_id _
| (n + 1) := (inj_on.iterate n).comp h hf
lemma inj_on_of_subsingleton [subsingleton α] (f : α → β) (s : set α) : inj_on f s :=
(injective_of_subsingleton _).inj_on _
lemma _root_.function.injective.inj_on_range (h : injective (g ∘ f)) : inj_on g (range f) :=
by { rintros _ ⟨x, rfl⟩ _ ⟨y, rfl⟩ H, exact congr_arg f (h H) }
lemma inj_on_iff_injective : inj_on f s ↔ injective (s.restrict f) :=
⟨λ H a b h, subtype.eq $ H a.2 b.2 h,
λ H a as b bs h, congr_arg subtype.val $ @H ⟨a, as⟩ ⟨b, bs⟩ h⟩
alias inj_on_iff_injective ↔ inj_on.injective _
lemma maps_to.restrict_inj (h : maps_to f s t) : injective (h.restrict f s t) ↔ inj_on f s :=
by rw [h.restrict_eq_cod_restrict, injective_cod_restrict, inj_on_iff_injective]
lemma exists_inj_on_iff_injective [nonempty β] :
(∃ f : α → β, inj_on f s) ↔ ∃ f : s → β, injective f :=
⟨λ ⟨f, hf⟩, ⟨_, hf.injective⟩,
λ ⟨f, hf⟩, by { lift f to α → β using trivial, exact ⟨f, inj_on_iff_injective.2 hf⟩ }⟩
lemma inj_on_preimage {B : set (set β)} (hB : B ⊆ 𝒫 (range f)) :
inj_on (preimage f) B :=
λ s hs t ht hst, (preimage_eq_preimage' (hB hs) (hB ht)).1 hst
lemma inj_on.mem_of_mem_image {x} (hf : inj_on f s) (hs : s₁ ⊆ s) (h : x ∈ s) (h₁ : f x ∈ f '' s₁) :
x ∈ s₁ :=
let ⟨x', h', eq⟩ := h₁ in hf (hs h') h eq ▸ h'
lemma inj_on.mem_image_iff {x} (hf : inj_on f s) (hs : s₁ ⊆ s) (hx : x ∈ s) :
f x ∈ f '' s₁ ↔ x ∈ s₁ :=
⟨hf.mem_of_mem_image hs hx, mem_image_of_mem f⟩
lemma inj_on.preimage_image_inter (hf : inj_on f s) (hs : s₁ ⊆ s) :
f ⁻¹' (f '' s₁) ∩ s = s₁ :=
ext $ λ x, ⟨λ ⟨h₁, h₂⟩, hf.mem_of_mem_image hs h₂ h₁, λ h, ⟨mem_image_of_mem _ h, hs h⟩⟩
lemma eq_on.cancel_left (h : s.eq_on (g ∘ f₁) (g ∘ f₂)) (hg : t.inj_on g) (hf₁ : s.maps_to f₁ t)
(hf₂ : s.maps_to f₂ t) :
s.eq_on f₁ f₂ :=
λ a ha, hg (hf₁ ha) (hf₂ ha) (h ha)
lemma inj_on.cancel_left (hg : t.inj_on g) (hf₁ : s.maps_to f₁ t) (hf₂ : s.maps_to f₂ t) :
s.eq_on (g ∘ f₁) (g ∘ f₂) ↔ s.eq_on f₁ f₂ :=
⟨λ h, h.cancel_left hg hf₁ hf₂, eq_on.comp_left⟩
lemma inj_on.image_inter {s t u : set α} (hf : u.inj_on f) (hs : s ⊆ u) (ht : t ⊆ u) :
f '' (s ∩ t) = f '' s ∩ f '' t :=
begin
apply subset.antisymm (image_inter_subset _ _ _),
rintros x ⟨⟨y, ys, hy⟩, ⟨z, zt, hz⟩⟩,
have : y = z,
{ apply hf (hs ys) (ht zt),
rwa ← hz at hy },
rw ← this at zt,
exact ⟨y, ⟨ys, zt⟩, hy⟩,
end
lemma _root_.disjoint.image {s t u : set α} {f : α → β} (h : disjoint s t) (hf : inj_on f u)
(hs : s ⊆ u) (ht : t ⊆ u) : disjoint (f '' s) (f '' t) :=
begin
rw disjoint_iff_inter_eq_empty at h ⊢,
rw [← hf.image_inter hs ht, h, image_empty],
end
/-! ### Surjectivity on a set -/
/-- `f` is surjective from `a` to `b` if `b` is contained in the image of `a`. -/
def surj_on (f : α → β) (s : set α) (t : set β) : Prop := t ⊆ f '' s
theorem surj_on.subset_range (h : surj_on f s t) : t ⊆ range f :=
subset.trans h $ image_subset_range f s
lemma surj_on_iff_exists_map_subtype :
surj_on f s t ↔ ∃ (t' : set β) (g : s → t'), t ⊆ t' ∧ surjective g ∧ ∀ x : s, f x = g x :=
⟨λ h, ⟨_, (maps_to_image f s).restrict f s _, h, surjective_maps_to_image_restrict _ _, λ _, rfl⟩,
λ ⟨t', g, htt', hg, hfg⟩ y hy, let ⟨x, hx⟩ := hg ⟨y, htt' hy⟩ in
⟨x, x.2, by rw [hfg, hx, subtype.coe_mk]⟩⟩
theorem surj_on_empty (f : α → β) (s : set α) : surj_on f s ∅ := empty_subset _
@[simp] lemma surj_on_singleton : surj_on f s {b} ↔ b ∈ f '' s := singleton_subset_iff
theorem surj_on_image (f : α → β) (s : set α) : surj_on f s (f '' s) := subset.rfl
theorem surj_on.comap_nonempty (h : surj_on f s t) (ht : t.nonempty) : s.nonempty :=
(ht.mono h).of_image
theorem surj_on.congr (h : surj_on f₁ s t) (H : eq_on f₁ f₂ s) : surj_on f₂ s t :=
by rwa [surj_on, ← H.image_eq]
theorem eq_on.surj_on_iff (h : eq_on f₁ f₂ s) : surj_on f₁ s t ↔ surj_on f₂ s t :=
⟨λ H, H.congr h, λ H, H.congr h.symm⟩
theorem surj_on.mono (hs : s₁ ⊆ s₂) (ht : t₁ ⊆ t₂) (hf : surj_on f s₁ t₂) : surj_on f s₂ t₁ :=
subset.trans ht $ subset.trans hf $ image_subset _ hs
theorem surj_on.union (h₁ : surj_on f s t₁) (h₂ : surj_on f s t₂) : surj_on f s (t₁ ∪ t₂) :=
λ x hx, hx.elim (λ hx, h₁ hx) (λ hx, h₂ hx)
theorem surj_on.union_union (h₁ : surj_on f s₁ t₁) (h₂ : surj_on f s₂ t₂) :
surj_on f (s₁ ∪ s₂) (t₁ ∪ t₂) :=
(h₁.mono (subset_union_left _ _) (subset.refl _)).union
(h₂.mono (subset_union_right _ _) (subset.refl _))
theorem surj_on.inter_inter (h₁ : surj_on f s₁ t₁) (h₂ : surj_on f s₂ t₂) (h : inj_on f (s₁ ∪ s₂)) :
surj_on f (s₁ ∩ s₂) (t₁ ∩ t₂) :=
begin
intros y hy,
rcases h₁ hy.1 with ⟨x₁, hx₁, rfl⟩,
rcases h₂ hy.2 with ⟨x₂, hx₂, heq⟩,
obtain rfl : x₁ = x₂ := h (or.inl hx₁) (or.inr hx₂) heq.symm,
exact mem_image_of_mem f ⟨hx₁, hx₂⟩
end
theorem surj_on.inter (h₁ : surj_on f s₁ t) (h₂ : surj_on f s₂ t) (h : inj_on f (s₁ ∪ s₂)) :
surj_on f (s₁ ∩ s₂) t :=
inter_self t ▸ h₁.inter_inter h₂ h
lemma surj_on_id (s : set α) : surj_on id s s := by simp [surj_on]
theorem surj_on.comp (hg : surj_on g t p) (hf : surj_on f s t) : surj_on (g ∘ f) s p :=
subset.trans hg $ subset.trans (image_subset g hf) $ (image_comp g f s) ▸ subset.refl _
lemma surj_on.iterate {f : α → α} {s : set α} (h : surj_on f s s) : ∀ n, surj_on (f^[n]) s s
| 0 := surj_on_id _
| (n + 1) := (surj_on.iterate n).comp h
lemma surj_on.comp_left (hf : surj_on f s t) (g : β → γ) : surj_on (g ∘ f) s (g '' t) :=
by { rw [surj_on, image_comp g f], exact image_subset _ hf }
lemma surj_on.comp_right {s : set β} {t : set γ} (hf : surjective f) (hg : surj_on g s t) :
surj_on (g ∘ f) (f ⁻¹' s) t :=
by rwa [surj_on, image_comp g f, image_preimage_eq _ hf]
lemma surj_on_of_subsingleton' [subsingleton β] (f : α → β) (h : t.nonempty → s.nonempty) :
surj_on f s t :=
λ a ha, subsingleton.mem_iff_nonempty.2 $ (h ⟨a, ha⟩).image _
lemma surj_on_of_subsingleton [subsingleton α] (f : α → α) (s : set α) : surj_on f s s :=
surj_on_of_subsingleton' _ id
lemma surjective_iff_surj_on_univ : surjective f ↔ surj_on f univ univ :=
by simp [surjective, surj_on, subset_def]
lemma surj_on_iff_surjective : surj_on f s univ ↔ surjective (s.restrict f) :=
⟨λ H b, let ⟨a, as, e⟩ := @H b trivial in ⟨⟨a, as⟩, e⟩,
λ H b _, let ⟨⟨a, as⟩, e⟩ := H b in ⟨a, as, e⟩⟩
lemma surj_on.image_eq_of_maps_to (h₁ : surj_on f s t) (h₂ : maps_to f s t) :
f '' s = t :=
eq_of_subset_of_subset h₂.image_subset h₁
lemma image_eq_iff_surj_on_maps_to : f '' s = t ↔ s.surj_on f t ∧ s.maps_to f t :=
begin
refine ⟨_, λ h, h.1.image_eq_of_maps_to h.2⟩,
rintro rfl,
exact ⟨s.surj_on_image f, s.maps_to_image f⟩,
end
lemma surj_on.maps_to_compl (h : surj_on f s t) (h' : injective f) : maps_to f sᶜ tᶜ :=
λ x hs ht, let ⟨x', hx', heq⟩ := h ht in hs $ h' heq ▸ hx'
lemma maps_to.surj_on_compl (h : maps_to f s t) (h' : surjective f) : surj_on f sᶜ tᶜ :=
h'.forall.2 $ λ x ht, mem_image_of_mem _ $ λ hs, ht (h hs)
lemma eq_on.cancel_right (hf : s.eq_on (g₁ ∘ f) (g₂ ∘ f)) (hf' : s.surj_on f t) : t.eq_on g₁ g₂ :=
begin
intros b hb,
obtain ⟨a, ha, rfl⟩ := hf' hb,
exact hf ha,
end
lemma surj_on.cancel_right (hf : s.surj_on f t) (hf' : s.maps_to f t) :
s.eq_on (g₁ ∘ f) (g₂ ∘ f) ↔ t.eq_on g₁ g₂ :=
⟨λ h, h.cancel_right hf, λ h, h.comp_right hf'⟩
lemma eq_on_comp_right_iff : s.eq_on (g₁ ∘ f) (g₂ ∘ f) ↔ (f '' s).eq_on g₁ g₂ :=
(s.surj_on_image f).cancel_right $ s.maps_to_image f
/-! ### Bijectivity -/
/-- `f` is bijective from `s` to `t` if `f` is injective on `s` and `f '' s = t`. -/
def bij_on (f : α → β) (s : set α) (t : set β) : Prop :=
maps_to f s t ∧ inj_on f s ∧ surj_on f s t
lemma bij_on.maps_to (h : bij_on f s t) : maps_to f s t := h.left
lemma bij_on.inj_on (h : bij_on f s t) : inj_on f s := h.right.left
lemma bij_on.surj_on (h : bij_on f s t) : surj_on f s t := h.right.right
lemma bij_on.mk (h₁ : maps_to f s t) (h₂ : inj_on f s) (h₃ : surj_on f s t) :
bij_on f s t :=
⟨h₁, h₂, h₃⟩
@[simp] lemma bij_on_empty (f : α → β) : bij_on f ∅ ∅ :=
⟨maps_to_empty f ∅, inj_on_empty f, surj_on_empty f ∅⟩
@[simp] lemma bij_on_singleton : bij_on f {a} {b} ↔ f a = b := by simp [bij_on, eq_comm]
lemma bij_on.inter_maps_to (h₁ : bij_on f s₁ t₁) (h₂ : maps_to f s₂ t₂) (h₃ : s₁ ∩ f ⁻¹' t₂ ⊆ s₂) :
bij_on f (s₁ ∩ s₂) (t₁ ∩ t₂) :=
⟨h₁.maps_to.inter_inter h₂, h₁.inj_on.mono $ inter_subset_left _ _,
λ y hy, let ⟨x, hx, hxy⟩ := h₁.surj_on hy.1 in ⟨x, ⟨hx, h₃ ⟨hx, hxy.symm.rec_on hy.2⟩⟩, hxy⟩⟩
lemma maps_to.inter_bij_on (h₁ : maps_to f s₁ t₁) (h₂ : bij_on f s₂ t₂)
(h₃ : s₂ ∩ f ⁻¹' t₁ ⊆ s₁) :
bij_on f (s₁ ∩ s₂) (t₁ ∩ t₂) :=
inter_comm s₂ s₁ ▸ inter_comm t₂ t₁ ▸ h₂.inter_maps_to h₁ h₃
lemma bij_on.inter (h₁ : bij_on f s₁ t₁) (h₂ : bij_on f s₂ t₂) (h : inj_on f (s₁ ∪ s₂)) :
bij_on f (s₁ ∩ s₂) (t₁ ∩ t₂) :=
⟨h₁.maps_to.inter_inter h₂.maps_to, h₁.inj_on.mono $ inter_subset_left _ _,
h₁.surj_on.inter_inter h₂.surj_on h⟩
lemma bij_on.union (h₁ : bij_on f s₁ t₁) (h₂ : bij_on f s₂ t₂) (h : inj_on f (s₁ ∪ s₂)) :
bij_on f (s₁ ∪ s₂) (t₁ ∪ t₂) :=
⟨h₁.maps_to.union_union h₂.maps_to, h, h₁.surj_on.union_union h₂.surj_on⟩
theorem bij_on.subset_range (h : bij_on f s t) : t ⊆ range f :=
h.surj_on.subset_range
lemma inj_on.bij_on_image (h : inj_on f s) : bij_on f s (f '' s) :=
bij_on.mk (maps_to_image f s) h (subset.refl _)
theorem bij_on.congr (h₁ : bij_on f₁ s t) (h : eq_on f₁ f₂ s) :
bij_on f₂ s t :=
bij_on.mk (h₁.maps_to.congr h) (h₁.inj_on.congr h) (h₁.surj_on.congr h)
theorem eq_on.bij_on_iff (H : eq_on f₁ f₂ s) : bij_on f₁ s t ↔ bij_on f₂ s t :=
⟨λ h, h.congr H, λ h, h.congr H.symm⟩
lemma bij_on.image_eq (h : bij_on f s t) :
f '' s = t :=
h.surj_on.image_eq_of_maps_to h.maps_to
lemma bij_on_id (s : set α) : bij_on id s s := ⟨s.maps_to_id, s.inj_on_id, s.surj_on_id⟩
theorem bij_on.comp (hg : bij_on g t p) (hf : bij_on f s t) : bij_on (g ∘ f) s p :=
bij_on.mk (hg.maps_to.comp hf.maps_to) (hg.inj_on.comp hf.inj_on hf.maps_to)
(hg.surj_on.comp hf.surj_on)
lemma bij_on.iterate {f : α → α} {s : set α} (h : bij_on f s s) : ∀ n, bij_on (f^[n]) s s
| 0 := s.bij_on_id
| (n + 1) := (bij_on.iterate n).comp h
lemma bij_on_of_subsingleton' [subsingleton α] [subsingleton β] (f : α → β)
(h : s.nonempty ↔ t.nonempty) : bij_on f s t :=
⟨maps_to_of_subsingleton' _ h.1, inj_on_of_subsingleton _ _, surj_on_of_subsingleton' _ h.2⟩
lemma bij_on_of_subsingleton [subsingleton α] (f : α → α) (s : set α) : bij_on f s s :=
bij_on_of_subsingleton' _ iff.rfl
theorem bij_on.bijective (h : bij_on f s t) : bijective (h.maps_to.restrict f s t) :=
⟨λ x y h', subtype.ext $ h.inj_on x.2 y.2 $ subtype.ext_iff.1 h',
λ ⟨y, hy⟩, let ⟨x, hx, hxy⟩ := h.surj_on hy in ⟨⟨x, hx⟩, subtype.eq hxy⟩⟩
lemma bijective_iff_bij_on_univ : bijective f ↔ bij_on f univ univ :=
iff.intro
(λ h, let ⟨inj, surj⟩ := h in
⟨maps_to_univ f _, inj.inj_on _, iff.mp surjective_iff_surj_on_univ surj⟩)
(λ h, let ⟨map, inj, surj⟩ := h in
⟨iff.mpr injective_iff_inj_on_univ inj, iff.mpr surjective_iff_surj_on_univ surj⟩)
alias bijective_iff_bij_on_univ ↔ _root_.function.bijective.bij_on_univ _
lemma bij_on.compl (hst : bij_on f s t) (hf : bijective f) : bij_on f sᶜ tᶜ :=
⟨hst.surj_on.maps_to_compl hf.1, hf.1.inj_on _, hst.maps_to.surj_on_compl hf.2⟩
/-! ### left inverse -/
/-- `g` is a left inverse to `f` on `a` means that `g (f x) = x` for all `x ∈ a`. -/
def left_inv_on (f' : β → α) (f : α → β) (s : set α) : Prop :=
∀ ⦃x⦄, x ∈ s → f' (f x) = x
@[simp] lemma left_inv_on_empty (f' : β → α) (f : α → β) : left_inv_on f' f ∅ := empty_subset _
@[simp] lemma left_inv_on_singleton : left_inv_on f' f {a} ↔ f' (f a) = a := singleton_subset_iff
lemma left_inv_on.eq_on (h : left_inv_on f' f s) : eq_on (f' ∘ f) id s := h
lemma left_inv_on.eq (h : left_inv_on f' f s) {x} (hx : x ∈ s) : f' (f x) = x := h hx
lemma left_inv_on.congr_left (h₁ : left_inv_on f₁' f s)
{t : set β} (h₁' : maps_to f s t) (heq : eq_on f₁' f₂' t) : left_inv_on f₂' f s :=
λ x hx, heq (h₁' hx) ▸ h₁ hx
theorem left_inv_on.congr_right (h₁ : left_inv_on f₁' f₁ s) (heq : eq_on f₁ f₂ s) :
left_inv_on f₁' f₂ s :=
λ x hx, heq hx ▸ h₁ hx
theorem left_inv_on.inj_on (h : left_inv_on f₁' f s) : inj_on f s :=
λ x₁ h₁ x₂ h₂ heq,
calc
x₁ = f₁' (f x₁) : eq.symm $ h h₁
... = f₁' (f x₂) : congr_arg f₁' heq
... = x₂ : h h₂
theorem left_inv_on.surj_on (h : left_inv_on f' f s) (hf : maps_to f s t) : surj_on f' t s :=
λ x hx, ⟨f x, hf hx, h hx⟩
theorem left_inv_on.maps_to (h : left_inv_on f' f s) (hf : surj_on f s t) : maps_to f' t s :=
λ y hy, let ⟨x, hs, hx⟩ := hf hy in by rwa [← hx, h hs]
lemma left_inv_on_id (s : set α) : left_inv_on id id s := λ a _, rfl
theorem left_inv_on.comp
(hf' : left_inv_on f' f s) (hg' : left_inv_on g' g t) (hf : maps_to f s t) :
left_inv_on (f' ∘ g') (g ∘ f) s :=
λ x h,
calc
(f' ∘ g') ((g ∘ f) x) = f' (f x) : congr_arg f' (hg' (hf h))
... = x : hf' h
theorem left_inv_on.mono (hf : left_inv_on f' f s) (ht : s₁ ⊆ s) : left_inv_on f' f s₁ :=
λ x hx, hf (ht hx)
theorem left_inv_on.image_inter' (hf : left_inv_on f' f s) :
f '' (s₁ ∩ s) = f' ⁻¹' s₁ ∩ f '' s :=
begin
apply subset.antisymm,
{ rintro _ ⟨x, ⟨h₁, h⟩, rfl⟩, exact ⟨by rwa [mem_preimage, hf h], mem_image_of_mem _ h⟩ },
{ rintro _ ⟨h₁, ⟨x, h, rfl⟩⟩, exact mem_image_of_mem _ ⟨by rwa ← hf h, h⟩ }
end
theorem left_inv_on.image_inter (hf : left_inv_on f' f s) :
f '' (s₁ ∩ s) = f' ⁻¹' (s₁ ∩ s) ∩ f '' s :=
begin
rw hf.image_inter',
refine subset.antisymm _ (inter_subset_inter_left _ (preimage_mono $ inter_subset_left _ _)),
rintro _ ⟨h₁, x, hx, rfl⟩, exact ⟨⟨h₁, by rwa hf hx⟩, mem_image_of_mem _ hx⟩
end
theorem left_inv_on.image_image (hf : left_inv_on f' f s) :
f' '' (f '' s) = s :=
by rw [image_image, image_congr hf, image_id']
theorem left_inv_on.image_image' (hf : left_inv_on f' f s) (hs : s₁ ⊆ s) :
f' '' (f '' s₁) = s₁ :=
(hf.mono hs).image_image
/-! ### Right inverse -/
/-- `g` is a right inverse to `f` on `b` if `f (g x) = x` for all `x ∈ b`. -/
@[reducible] def right_inv_on (f' : β → α) (f : α → β) (t : set β) : Prop :=
left_inv_on f f' t
@[simp] lemma right_inv_on_empty (f' : β → α) (f : α → β) : right_inv_on f' f ∅ := empty_subset _
@[simp] lemma right_inv_on_singleton : right_inv_on f' f {b} ↔ f (f' b) = b := singleton_subset_iff
lemma right_inv_on.eq_on (h : right_inv_on f' f t) : eq_on (f ∘ f') id t := h
lemma right_inv_on.eq (h : right_inv_on f' f t) {y} (hy : y ∈ t) : f (f' y) = y := h hy
lemma left_inv_on.right_inv_on_image (h : left_inv_on f' f s) : right_inv_on f' f (f '' s) :=
λ y ⟨x, hx, eq⟩, eq ▸ congr_arg f $ h.eq hx
theorem right_inv_on.congr_left (h₁ : right_inv_on f₁' f t) (heq : eq_on f₁' f₂' t) :
right_inv_on f₂' f t :=
h₁.congr_right heq
theorem right_inv_on.congr_right (h₁ : right_inv_on f' f₁ t) (hg : maps_to f' t s)
(heq : eq_on f₁ f₂ s) : right_inv_on f' f₂ t :=
left_inv_on.congr_left h₁ hg heq
theorem right_inv_on.surj_on (hf : right_inv_on f' f t) (hf' : maps_to f' t s) :
surj_on f s t :=
hf.surj_on hf'
theorem right_inv_on.maps_to (h : right_inv_on f' f t) (hf : surj_on f' t s) : maps_to f s t :=
h.maps_to hf
lemma right_inv_on_id (s : set α) : right_inv_on id id s := λ a _, rfl
theorem right_inv_on.comp (hf : right_inv_on f' f t) (hg : right_inv_on g' g p)
(g'pt : maps_to g' p t) : right_inv_on (f' ∘ g') (g ∘ f) p :=
hg.comp hf g'pt
theorem right_inv_on.mono (hf : right_inv_on f' f t) (ht : t₁ ⊆ t) : right_inv_on f' f t₁ :=
hf.mono ht
theorem inj_on.right_inv_on_of_left_inv_on (hf : inj_on f s) (hf' : left_inv_on f f' t)
(h₁ : maps_to f s t) (h₂ : maps_to f' t s) :
right_inv_on f f' s :=
λ x h, hf (h₂ $ h₁ h) h (hf' (h₁ h))
theorem eq_on_of_left_inv_on_of_right_inv_on (h₁ : left_inv_on f₁' f s) (h₂ : right_inv_on f₂' f t)
(h : maps_to f₂' t s) : eq_on f₁' f₂' t :=
λ y hy,
calc f₁' y = (f₁' ∘ f ∘ f₂') y : congr_arg f₁' (h₂ hy).symm
... = f₂' y : h₁ (h hy)
theorem surj_on.left_inv_on_of_right_inv_on (hf : surj_on f s t) (hf' : right_inv_on f f' s) :
left_inv_on f f' t :=
λ y hy, let ⟨x, hx, heq⟩ := hf hy in by rw [← heq, hf' hx]
/-! ### Two-side inverses -/
/-- `g` is an inverse to `f` viewed as a map from `a` to `b` -/
def inv_on (g : β → α) (f : α → β) (s : set α) (t : set β) : Prop :=
left_inv_on g f s ∧ right_inv_on g f t
@[simp] lemma inv_on_empty (f' : β → α) (f : α → β) : inv_on f' f ∅ ∅ := by simp [inv_on]
@[simp] lemma inv_on_singleton : inv_on f' f {a} {b} ↔ f' (f a) = a ∧ f (f' b) = b :=
by simp [inv_on]
lemma inv_on.symm (h : inv_on f' f s t) : inv_on f f' t s := ⟨h.right, h.left⟩
lemma inv_on_id (s : set α) : inv_on id id s s := ⟨s.left_inv_on_id, s.right_inv_on_id⟩
lemma inv_on.comp (hf : inv_on f' f s t) (hg : inv_on g' g t p) (fst : maps_to f s t)
(g'pt : maps_to g' p t) :
inv_on (f' ∘ g') (g ∘ f) s p :=
⟨hf.1.comp hg.1 fst, hf.2.comp hg.2 g'pt⟩
lemma inv_on.mono (h : inv_on f' f s t) (hs : s₁ ⊆ s) (ht : t₁ ⊆ t) : inv_on f' f s₁ t₁ :=
⟨h.1.mono hs, h.2.mono ht⟩
/-- If functions `f'` and `f` are inverse on `s` and `t`, `f` maps `s` into `t`, and `f'` maps `t`
into `s`, then `f` is a bijection between `s` and `t`. The `maps_to` arguments can be deduced from
`surj_on` statements using `left_inv_on.maps_to` and `right_inv_on.maps_to`. -/
theorem inv_on.bij_on (h : inv_on f' f s t) (hf : maps_to f s t) (hf' : maps_to f' t s) :
bij_on f s t :=
⟨hf, h.left.inj_on, h.right.surj_on hf'⟩
lemma bij_on.symm {g : β → α} (h : inv_on f g t s) (hf : bij_on f s t) : bij_on g t s :=
⟨h.2.maps_to hf.surj_on, h.1.inj_on, h.2.surj_on hf.maps_to⟩
lemma bij_on_comm {g : β → α} (h : inv_on f g t s) : bij_on f s t ↔ bij_on g t s :=
⟨bij_on.symm h, bij_on.symm h.symm⟩
end set
/-! ### `inv_fun_on` is a left/right inverse -/
namespace function
variables [nonempty α] {s : set α} {f : α → β} {a : α} {b : β}
local attribute [instance, priority 10] classical.prop_decidable
/-- Construct the inverse for a function `f` on domain `s`. This function is a right inverse of `f`
on `f '' s`. For a computable version, see `function.injective.inv_of_mem_range`. -/
noncomputable def inv_fun_on (f : α → β) (s : set α) (b : β) : α :=
if h : ∃a, a ∈ s ∧ f a = b then classical.some h else classical.choice ‹nonempty α›
theorem inv_fun_on_pos (h : ∃a∈s, f a = b) : inv_fun_on f s b ∈ s ∧ f (inv_fun_on f s b) = b :=
by rw [bex_def] at h; rw [inv_fun_on, dif_pos h]; exact classical.some_spec h
theorem inv_fun_on_mem (h : ∃a∈s, f a = b) : inv_fun_on f s b ∈ s := (inv_fun_on_pos h).left
theorem inv_fun_on_eq (h : ∃a∈s, f a = b) : f (inv_fun_on f s b) = b := (inv_fun_on_pos h).right
theorem inv_fun_on_neg (h : ¬ ∃a∈s, f a = b) : inv_fun_on f s b = classical.choice ‹nonempty α› :=
by rw [bex_def] at h; rw [inv_fun_on, dif_neg h]
@[simp] theorem inv_fun_on_apply_mem (h : a ∈ s) : inv_fun_on f s (f a) ∈ s :=
inv_fun_on_mem ⟨a, h, rfl⟩
theorem inv_fun_on_apply_eq (h : a ∈ s) : f (inv_fun_on f s (f a)) = f a :=
inv_fun_on_eq ⟨a, h, rfl⟩
end function
open function
namespace set
variables {s s₁ s₂ : set α} {t : set β} {f : α → β}
theorem inj_on.left_inv_on_inv_fun_on [nonempty α] (h : inj_on f s) :
left_inv_on (inv_fun_on f s) f s :=
λ a ha, h (inv_fun_on_apply_mem ha) ha (inv_fun_on_apply_eq ha)
lemma inj_on.inv_fun_on_image [nonempty α] (h : inj_on f s₂) (ht : s₁ ⊆ s₂) :
(inv_fun_on f s₂) '' (f '' s₁) = s₁ :=
h.left_inv_on_inv_fun_on.image_image' ht
theorem surj_on.right_inv_on_inv_fun_on [nonempty α] (h : surj_on f s t) :
right_inv_on (inv_fun_on f s) f t :=
λ y hy, inv_fun_on_eq $ mem_image_iff_bex.1 $ h hy
theorem bij_on.inv_on_inv_fun_on [nonempty α] (h : bij_on f s t) :
inv_on (inv_fun_on f s) f s t :=
⟨h.inj_on.left_inv_on_inv_fun_on, h.surj_on.right_inv_on_inv_fun_on⟩
theorem surj_on.inv_on_inv_fun_on [nonempty α] (h : surj_on f s t) :
inv_on (inv_fun_on f s) f (inv_fun_on f s '' t) t :=
begin
refine ⟨_, h.right_inv_on_inv_fun_on⟩,
rintros _ ⟨y, hy, rfl⟩,
rw [h.right_inv_on_inv_fun_on hy]
end
theorem surj_on.maps_to_inv_fun_on [nonempty α] (h : surj_on f s t) :
maps_to (inv_fun_on f s) t s :=
λ y hy, mem_preimage.2 $ inv_fun_on_mem $ mem_image_iff_bex.1 $ h hy
theorem surj_on.bij_on_subset [nonempty α] (h : surj_on f s t) :
bij_on f (inv_fun_on f s '' t) t :=
begin
refine h.inv_on_inv_fun_on.bij_on _ (maps_to_image _ _),
rintros _ ⟨y, hy, rfl⟩,
rwa [h.right_inv_on_inv_fun_on hy]
end
theorem surj_on_iff_exists_bij_on_subset :
surj_on f s t ↔ ∃ s' ⊆ s, bij_on f s' t :=
begin
split,
{ rcases eq_empty_or_nonempty t with rfl|ht,
{ exact λ _, ⟨∅, empty_subset _, bij_on_empty f⟩ },
{ assume h,
haveI : nonempty α := ⟨classical.some (h.comap_nonempty ht)⟩,
exact ⟨_, h.maps_to_inv_fun_on.image_subset, h.bij_on_subset⟩ }},
{ rintros ⟨s', hs', hfs'⟩,
exact hfs'.surj_on.mono hs' (subset.refl _) }
end
lemma preimage_inv_fun_of_mem [n : nonempty α] {f : α → β} (hf : injective f) {s : set α}
(h : classical.choice n ∈ s) : inv_fun f ⁻¹' s = f '' s ∪ (range f)ᶜ :=
begin
ext x,
rcases em (x ∈ range f) with ⟨a, rfl⟩|hx,
{ simp [left_inverse_inv_fun hf _, hf.mem_set_image] },
{ simp [mem_preimage, inv_fun_neg hx, h, hx] }
end
lemma preimage_inv_fun_of_not_mem [n : nonempty α] {f : α → β} (hf : injective f)
{s : set α} (h : classical.choice n ∉ s) : inv_fun f ⁻¹' s = f '' s :=
begin
ext x,
rcases em (x ∈ range f) with ⟨a, rfl⟩|hx,
{ rw [mem_preimage, left_inverse_inv_fun hf, hf.mem_set_image] },
{ have : x ∉ f '' s, from λ h', hx (image_subset_range _ _ h'),
simp only [mem_preimage, inv_fun_neg hx, h, this] },
end
end set
/-! ### Monotone -/
namespace monotone
variables [preorder α] [preorder β] {f : α → β}
protected lemma restrict (h : monotone f) (s : set α) : monotone (s.restrict f) :=
λ x y hxy, h hxy
protected lemma cod_restrict (h : monotone f) {s : set β} (hs : ∀ x, f x ∈ s) :
monotone (s.cod_restrict f hs) := h
protected lemma range_factorization (h : monotone f) : monotone (set.range_factorization f) := h
end monotone
/-! ### Piecewise defined function -/
namespace set
variables {δ : α → Sort y} (s : set α) (f g : Πi, δ i)
@[simp] lemma piecewise_empty [∀i : α, decidable (i ∈ (∅ : set α))] : piecewise ∅ f g = g :=
by { ext i, simp [piecewise] }
@[simp] lemma piecewise_univ [∀i : α, decidable (i ∈ (set.univ : set α))] :
piecewise set.univ f g = f :=
by { ext i, simp [piecewise] }
@[simp] lemma piecewise_insert_self {j : α} [∀i, decidable (i ∈ insert j s)] :
(insert j s).piecewise f g j = f j :=
by simp [piecewise]
variable [∀j, decidable (j ∈ s)]
instance compl.decidable_mem (j : α) : decidable (j ∈ sᶜ) := not.decidable
lemma piecewise_insert [decidable_eq α] (j : α) [∀i, decidable (i ∈ insert j s)] :
(insert j s).piecewise f g = function.update (s.piecewise f g) j (f j) :=
begin
simp [piecewise],
ext i,
by_cases h : i = j,
{ rw h, simp },
{ by_cases h' : i ∈ s; simp [h, h'] }
end
@[simp, priority 990]
lemma piecewise_eq_of_mem {i : α} (hi : i ∈ s) : s.piecewise f g i = f i := if_pos hi
@[simp, priority 990]
lemma piecewise_eq_of_not_mem {i : α} (hi : i ∉ s) : s.piecewise f g i = g i := if_neg hi
lemma piecewise_singleton (x : α) [Π y, decidable (y ∈ ({x} : set α))] [decidable_eq α]
(f g : α → β) : piecewise {x} f g = function.update g x (f x) :=
by { ext y, by_cases hy : y = x, { subst y, simp }, { simp [hy] } }
lemma piecewise_eq_on (f g : α → β) : eq_on (s.piecewise f g) f s :=
λ _, piecewise_eq_of_mem _ _ _
lemma piecewise_eq_on_compl (f g : α → β) : eq_on (s.piecewise f g) g sᶜ :=
λ _, piecewise_eq_of_not_mem _ _ _
lemma piecewise_le {δ : α → Type*} [Π i, preorder (δ i)] {s : set α} [Π j, decidable (j ∈ s)]
{f₁ f₂ g : Π i, δ i} (h₁ : ∀ i ∈ s, f₁ i ≤ g i) (h₂ : ∀ i ∉ s, f₂ i ≤ g i) :
s.piecewise f₁ f₂ ≤ g :=
λ i, if h : i ∈ s then by simp * else by simp *
lemma le_piecewise {δ : α → Type*} [Π i, preorder (δ i)] {s : set α} [Π j, decidable (j ∈ s)]
{f₁ f₂ g : Π i, δ i} (h₁ : ∀ i ∈ s, g i ≤ f₁ i) (h₂ : ∀ i ∉ s, g i ≤ f₂ i) :
g ≤ s.piecewise f₁ f₂ :=
@piecewise_le α (λ i, (δ i)ᵒᵈ) _ s _ _ _ _ h₁ h₂
lemma piecewise_le_piecewise {δ : α → Type*} [Π i, preorder (δ i)] {s : set α}
[Π j, decidable (j ∈ s)] {f₁ f₂ g₁ g₂ : Π i, δ i} (h₁ : ∀ i ∈ s, f₁ i ≤ g₁ i)
(h₂ : ∀ i ∉ s, f₂ i ≤ g₂ i) :
s.piecewise f₁ f₂ ≤ s.piecewise g₁ g₂ :=
by apply piecewise_le; intros; simp *
@[simp, priority 990]
lemma piecewise_insert_of_ne {i j : α} (h : i ≠ j) [∀i, decidable (i ∈ insert j s)] :
(insert j s).piecewise f g i = s.piecewise f g i :=
by simp [piecewise, h]
@[simp] lemma piecewise_compl [∀ i, decidable (i ∈ sᶜ)] : sᶜ.piecewise f g = s.piecewise g f :=
funext $ λ x, if hx : x ∈ s then by simp [hx] else by simp [hx]
@[simp] lemma piecewise_range_comp {ι : Sort*} (f : ι → α) [Π j, decidable (j ∈ range f)]
(g₁ g₂ : α → β) :
(range f).piecewise g₁ g₂ ∘ f = g₁ ∘ f :=
eq_on.comp_eq $ piecewise_eq_on _ _ _
theorem maps_to.piecewise_ite {s s₁ s₂ : set α} {t t₁ t₂ : set β} {f₁ f₂ : α → β}
[∀ i, decidable (i ∈ s)]
(h₁ : maps_to f₁ (s₁ ∩ s) (t₁ ∩ t)) (h₂ : maps_to f₂ (s₂ ∩ sᶜ) (t₂ ∩ tᶜ)) :
maps_to (s.piecewise f₁ f₂) (s.ite s₁ s₂) (t.ite t₁ t₂) :=
begin
refine (h₁.congr _).union_union (h₂.congr _),
exacts [(piecewise_eq_on s f₁ f₂).symm.mono (inter_subset_right _ _),
(piecewise_eq_on_compl s f₁ f₂).symm.mono (inter_subset_right _ _)]
end
theorem eq_on_piecewise {f f' g : α → β} {t} :
eq_on (s.piecewise f f') g t ↔ eq_on f g (t ∩ s) ∧ eq_on f' g (t ∩ sᶜ) :=
begin
simp only [eq_on, ← forall_and_distrib],
refine forall_congr (λ a, _), by_cases a ∈ s; simp *
end
theorem eq_on.piecewise_ite' {f f' g : α → β} {t t'} (h : eq_on f g (t ∩ s))
(h' : eq_on f' g (t' ∩ sᶜ)) :
eq_on (s.piecewise f f') g (s.ite t t') :=
by simp [eq_on_piecewise, *]
theorem eq_on.piecewise_ite {f f' g : α → β} {t t'} (h : eq_on f g t)
(h' : eq_on f' g t') :
eq_on (s.piecewise f f') g (s.ite t t') :=
(h.mono (inter_subset_left _ _)).piecewise_ite' s (h'.mono (inter_subset_left _ _))
lemma piecewise_preimage (f g : α → β) (t) :
s.piecewise f g ⁻¹' t = s.ite (f ⁻¹' t) (g ⁻¹' t) :=
ext $ λ x, by by_cases x ∈ s; simp [*, set.ite]
lemma apply_piecewise {δ' : α → Sort*} (h : Π i, δ i → δ' i) {x : α} :
h x (s.piecewise f g x) = s.piecewise (λ x, h x (f x)) (λ x, h x (g x)) x :=
by by_cases hx : x ∈ s; simp [hx]
lemma apply_piecewise₂ {δ' δ'' : α → Sort*} (f' g' : Π i, δ' i) (h : Π i, δ i → δ' i → δ'' i)
{x : α} :
h x (s.piecewise f g x) (s.piecewise f' g' x) =
s.piecewise (λ x, h x (f x) (f' x)) (λ x, h x (g x) (g' x)) x :=
by by_cases hx : x ∈ s; simp [hx]
lemma piecewise_op {δ' : α → Sort*} (h : Π i, δ i → δ' i) :
s.piecewise (λ x, h x (f x)) (λ x, h x (g x)) = λ x, h x (s.piecewise f g x) :=
funext $ λ x, (apply_piecewise _ _ _ _).symm
lemma piecewise_op₂ {δ' δ'' : α → Sort*} (f' g' : Π i, δ' i) (h : Π i, δ i → δ' i → δ'' i) :
s.piecewise (λ x, h x (f x) (f' x)) (λ x, h x (g x) (g' x)) =
λ x, h x (s.piecewise f g x) (s.piecewise f' g' x) :=
funext $ λ x, (apply_piecewise₂ _ _ _ _ _ _).symm
@[simp] lemma piecewise_same : s.piecewise f f = f :=
by { ext x, by_cases hx : x ∈ s; simp [hx] }
lemma range_piecewise (f g : α → β) : range (s.piecewise f g) = f '' s ∪ g '' sᶜ :=
begin
ext y, split,
{ rintro ⟨x, rfl⟩, by_cases h : x ∈ s;[left, right]; use x; simp [h] },
{ rintro (⟨x, hx, rfl⟩|⟨x, hx, rfl⟩); use x; simp * at * }
end
lemma injective_piecewise_iff {f g : α → β} :
injective (s.piecewise f g) ↔ inj_on f s ∧ inj_on g sᶜ ∧ (∀ (x ∈ s) (y ∉ s), f x ≠ g y) :=
begin
rw [injective_iff_inj_on_univ, ← union_compl_self s, inj_on_union (@disjoint_compl_right _ _ s),
(piecewise_eq_on s f g).inj_on_iff, (piecewise_eq_on_compl s f g).inj_on_iff],
refine and_congr iff.rfl (and_congr iff.rfl $ forall₄_congr $ λ x hx y hy, _),
rw [piecewise_eq_of_mem s f g hx, piecewise_eq_of_not_mem s f g hy]
end
lemma piecewise_mem_pi {δ : α → Type*} {t : set α} {t' : Π i, set (δ i)}
{f g} (hf : f ∈ pi t t') (hg : g ∈ pi t t') :
s.piecewise f g ∈ pi t t' :=
by { intros i ht, by_cases hs : i ∈ s; simp [hf i ht, hg i ht, hs] }
@[simp] lemma pi_piecewise {ι : Type*} {α : ι → Type*} (s s' : set ι)
(t t' : Π i, set (α i)) [Π x, decidable (x ∈ s')] :
pi s (s'.piecewise t t') = pi (s ∩ s') t ∩ pi (s \ s') t' :=
begin
ext x,
simp only [mem_pi, mem_inter_iff, ← forall_and_distrib],
refine forall_congr (λ i, _),
by_cases hi : i ∈ s'; simp *
end
lemma univ_pi_piecewise {ι : Type*} {α : ι → Type*} (s : set ι)
(t : Π i, set (α i)) [Π x, decidable (x ∈ s)] :
pi univ (s.piecewise t (λ _, univ)) = pi s t :=
by simp
end set
open set
lemma strict_mono_on.inj_on [linear_order α] [preorder β] {f : α → β} {s : set α}
(H : strict_mono_on f s) :
s.inj_on f :=
λ x hx y hy hxy, show ordering.eq.compares x y, from (H.compares hx hy).1 hxy
lemma strict_anti_on.inj_on [linear_order α] [preorder β] {f : α → β} {s : set α}
(H : strict_anti_on f s) :
s.inj_on f :=
@strict_mono_on.inj_on α βᵒᵈ _ _ f s H
lemma strict_mono_on.comp [preorder α] [preorder β] [preorder γ]
{g : β → γ} {f : α → β} {s : set α} {t : set β} (hg : strict_mono_on g t)
(hf : strict_mono_on f s) (hs : set.maps_to f s t) :
strict_mono_on (g ∘ f) s :=
λ x hx y hy hxy, hg (hs hx) (hs hy) $ hf hx hy hxy
lemma strict_mono_on.comp_strict_anti_on [preorder α] [preorder β] [preorder γ]
{g : β → γ} {f : α → β} {s : set α} {t : set β} (hg : strict_mono_on g t)
(hf : strict_anti_on f s) (hs : set.maps_to f s t) :
strict_anti_on (g ∘ f) s :=
λ x hx y hy hxy, hg (hs hy) (hs hx) $ hf hx hy hxy
lemma strict_anti_on.comp [preorder α] [preorder β] [preorder γ]
{g : β → γ} {f : α → β} {s : set α} {t : set β} (hg : strict_anti_on g t)
(hf : strict_anti_on f s) (hs : set.maps_to f s t) :
strict_mono_on (g ∘ f) s :=
λ x hx y hy hxy, hg (hs hy) (hs hx) $ hf hx hy hxy
lemma strict_anti_on.comp_strict_mono_on [preorder α] [preorder β] [preorder γ]
{g : β → γ} {f : α → β} {s : set α} {t : set β} (hg : strict_anti_on g t)
(hf : strict_mono_on f s) (hs : set.maps_to f s t) :
strict_anti_on (g ∘ f) s :=
λ x hx y hy hxy, hg (hs hx) (hs hy) $ hf hx hy hxy
@[simp] lemma strict_mono_restrict [preorder α] [preorder β] {f : α → β} {s : set α} :
strict_mono (s.restrict f) ↔ strict_mono_on f s :=
by simp [set.restrict, strict_mono, strict_mono_on]
alias strict_mono_restrict ↔ _root_.strict_mono.of_restrict _root_.strict_mono_on.restrict
lemma strict_mono.cod_restrict [preorder α] [preorder β] {f : α → β} (hf : strict_mono f)
{s : set β} (hs : ∀ x, f x ∈ s) :
strict_mono (set.cod_restrict f s hs) :=
hf
namespace function
open set
variables {fa : α → α} {fb : β → β} {f : α → β} {g : β → γ} {s t : set α}
lemma injective.comp_inj_on (hg : injective g) (hf : s.inj_on f) : s.inj_on (g ∘ f) :=
(hg.inj_on univ).comp hf (maps_to_univ _ _)
lemma surjective.surj_on (hf : surjective f) (s : set β) :
surj_on f univ s :=
(surjective_iff_surj_on_univ.1 hf).mono (subset.refl _) (subset_univ _)
lemma left_inverse.left_inv_on {g : β → α} (h : left_inverse f g) (s : set β) :
left_inv_on f g s :=
λ x hx, h x
lemma right_inverse.right_inv_on {g : β → α} (h : right_inverse f g) (s : set α) :
right_inv_on f g s :=
λ x hx, h x
lemma left_inverse.right_inv_on_range {g : β → α} (h : left_inverse f g) :
right_inv_on f g (range g) :=
forall_range_iff.2 $ λ i, congr_arg g (h i)
namespace semiconj
lemma maps_to_image (h : semiconj f fa fb) (ha : maps_to fa s t) :
maps_to fb (f '' s) (f '' t) :=
λ y ⟨x, hx, hy⟩, hy ▸ ⟨fa x, ha hx, h x⟩
lemma maps_to_range (h : semiconj f fa fb) : maps_to fb (range f) (range f) :=
λ y ⟨x, hy⟩, hy ▸ ⟨fa x, h x⟩
lemma surj_on_image (h : semiconj f fa fb) (ha : surj_on fa s t) :
surj_on fb (f '' s) (f '' t) :=
begin
rintros y ⟨x, hxt, rfl⟩,
rcases ha hxt with ⟨x, hxs, rfl⟩,
rw [h x],
exact mem_image_of_mem _ (mem_image_of_mem _ hxs)
end
lemma surj_on_range (h : semiconj f fa fb) (ha : surjective fa) :
surj_on fb (range f) (range f) :=
by { rw ← image_univ, exact h.surj_on_image (ha.surj_on univ) }
lemma inj_on_image (h : semiconj f fa fb) (ha : inj_on fa s) (hf : inj_on f (fa '' s)) :
inj_on fb (f '' s) :=
begin
rintros _ ⟨x, hx, rfl⟩ _ ⟨y, hy, rfl⟩ H,
simp only [← h.eq] at H,
exact congr_arg f (ha hx hy $ hf (mem_image_of_mem fa hx) (mem_image_of_mem fa hy) H)
end
lemma inj_on_range (h : semiconj f fa fb) (ha : injective fa) (hf : inj_on f (range fa)) :
inj_on fb (range f) :=
by { rw ← image_univ at *, exact h.inj_on_image (ha.inj_on univ) hf }
lemma bij_on_image (h : semiconj f fa fb) (ha : bij_on fa s t) (hf : inj_on f t) :
bij_on fb (f '' s) (f '' t) :=
⟨h.maps_to_image ha.maps_to, h.inj_on_image ha.inj_on (ha.image_eq.symm ▸ hf),
h.surj_on_image ha.surj_on⟩
lemma bij_on_range (h : semiconj f fa fb) (ha : bijective fa) (hf : injective f) :
bij_on fb (range f) (range f) :=
begin
rw [← image_univ],
exact h.bij_on_image (bijective_iff_bij_on_univ.1 ha) (hf.inj_on univ)
end
lemma maps_to_preimage (h : semiconj f fa fb) {s t : set β} (hb : maps_to fb s t) :
maps_to fa (f ⁻¹' s) (f ⁻¹' t) :=
λ x hx, by simp only [mem_preimage, h x, hb hx]
lemma inj_on_preimage (h : semiconj f fa fb) {s : set β} (hb : inj_on fb s)
(hf : inj_on f (f ⁻¹' s)) :
inj_on fa (f ⁻¹' s) :=
begin
intros x hx y hy H,
have := congr_arg f H,
rw [h.eq, h.eq] at this,
exact hf hx hy (hb hx hy this)
end
end semiconj
lemma update_comp_eq_of_not_mem_range' {α β : Sort*} {γ : β → Sort*} [decidable_eq β]
(g : Π b, γ b) {f : α → β} {i : β} (a : γ i) (h : i ∉ set.range f) :
(λ j, (function.update g i a) (f j)) = (λ j, g (f j)) :=
update_comp_eq_of_forall_ne' _ _ $ λ x hx, h ⟨x, hx⟩
/-- Non-dependent version of `function.update_comp_eq_of_not_mem_range'` -/
lemma update_comp_eq_of_not_mem_range {α β γ : Sort*} [decidable_eq β]
(g : β → γ) {f : α → β} {i : β} (a : γ) (h : i ∉ set.range f) :
(function.update g i a) ∘ f = g ∘ f :=
update_comp_eq_of_not_mem_range' g a h
lemma insert_inj_on (s : set α) : sᶜ.inj_on (λ a, insert a s) := λ a ha b _, (insert_inj ha).1
lemma monotone_on_of_right_inv_on_of_maps_to
[partial_order α] [linear_order β] {φ : β → α} {ψ : α → β} {t : set β} {s : set α}
(hφ : monotone_on φ t) (φψs : set.right_inv_on ψ φ s) (ψts : set.maps_to ψ s t) :
monotone_on ψ s :=
begin
rintro x xs y ys l,
rcases le_total (ψ x) (ψ y) with (ψxy|ψyx),
{ exact ψxy, },
{ cases le_antisymm l (φψs.eq ys ▸ φψs.eq xs ▸ hφ (ψts ys) (ψts xs) ψyx), refl, },
end
lemma antitone_on_of_right_inv_on_of_maps_to
[partial_order α] [linear_order β] {φ : β → α} {ψ : α → β} {t : set β} {s : set α}
(hφ : antitone_on φ t) (φψs : set.right_inv_on ψ φ s) (ψts : set.maps_to ψ s t) :
antitone_on ψ s :=
(monotone_on_of_right_inv_on_of_maps_to hφ.dual_left φψs ψts).dual_right
end function
/-! ### Equivalences, permutations -/
namespace set
variables {p : β → Prop} [decidable_pred p] {f : α ≃ subtype p} {g g₁ g₂ : perm α} {s t : set α}
protected lemma maps_to.extend_domain (h : maps_to g s t) :
maps_to (g.extend_domain f) (coe ∘ f '' s) (coe ∘ f '' t) :=
by { rintro _ ⟨a, ha, rfl⟩, exact ⟨_, h ha, by rw extend_domain_apply_image⟩ }
protected lemma surj_on.extend_domain (h : surj_on g s t) :
surj_on (g.extend_domain f) (coe ∘ f '' s) (coe ∘ f '' t) :=
begin
rintro _ ⟨a, ha, rfl⟩,
obtain ⟨b, hb, rfl⟩ := h ha,
exact ⟨_, ⟨_, hb, rfl⟩, by rw extend_domain_apply_image⟩,
end
protected lemma bij_on.extend_domain (h : set.bij_on g s t) :
bij_on (g.extend_domain f) (coe ∘ f '' s) (coe ∘ f '' t) :=
⟨h.maps_to.extend_domain, (g.extend_domain f).injective.inj_on _, h.surj_on.extend_domain⟩
protected lemma left_inv_on.extend_domain (h : left_inv_on g₁ g₂ s) :
left_inv_on (g₁.extend_domain f) (g₂.extend_domain f) (coe ∘ f '' s) :=
by { rintro _ ⟨a, ha, rfl⟩, simp_rw [extend_domain_apply_image, h ha] }
protected lemma right_inv_on.extend_domain (h : right_inv_on g₁ g₂ t) :
right_inv_on (g₁.extend_domain f) (g₂.extend_domain f) (coe ∘ f '' t) :=
by { rintro _ ⟨a, ha, rfl⟩, simp_rw [extend_domain_apply_image, h ha] }
protected lemma inv_on.extend_domain (h : inv_on g₁ g₂ s t) :
inv_on (g₁.extend_domain f) (g₂.extend_domain f) (coe ∘ f '' s) (coe ∘ f '' t) :=
⟨h.1.extend_domain, h.2.extend_domain⟩
end set
namespace equiv
variables (e : α ≃ β) {s : set α} {t : set β}
lemma bij_on' (h₁ : maps_to e s t) (h₂ : maps_to e.symm t s) : bij_on e s t :=
⟨h₁, e.injective.inj_on _, λ b hb, ⟨e.symm b, h₂ hb, apply_symm_apply _ _⟩⟩
protected lemma bij_on (h : ∀ a, e a ∈ t ↔ a ∈ s) : bij_on e s t :=
e.bij_on' (λ a, (h _).2) $ λ b hb, (h _).1 $ by rwa apply_symm_apply
lemma inv_on : inv_on e e.symm t s :=
⟨e.right_inverse_symm.left_inv_on _, e.left_inverse_symm.left_inv_on _⟩
lemma bij_on_image : bij_on e s (e '' s) := (e.injective.inj_on _).bij_on_image
lemma bij_on_symm_image : bij_on e.symm (e '' s) s := e.bij_on_image.symm e.inv_on
variables {e}
@[simp] lemma bij_on_symm : bij_on e.symm t s ↔ bij_on e s t := bij_on_comm e.symm.inv_on
alias bij_on_symm ↔ _root_.set.bij_on.of_equiv_symm _root_.set.bij_on.equiv_symm
variables [decidable_eq α] {a b : α}
lemma bij_on_swap (ha : a ∈ s) (hb : b ∈ s) : bij_on (swap a b) s s :=
(swap a b).bij_on $ λ x, by obtain rfl | hxa := eq_or_ne x a; obtain rfl | hxb := eq_or_ne x b;
simp [*, swap_apply_of_ne_of_ne]
end equiv
|
e8929eef9fc0139b4fa8a5f62e75d24068c28457 | 35677d2df3f081738fa6b08138e03ee36bc33cad | /src/data/multiset.lean | 11b8841d61007858dd6a0753d7dec5b683227d4f | [
"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 | 135,241 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
Multisets.
-/
import logic.function order.boolean_algebra data.equiv.basic
import data.list.sort data.list.intervals data.list.antidiagonal
import data.quot data.string.basic
algebra.order_functions algebra.group_power algebra.ordered_group
category.traversable.lemmas tactic.interactive
category.traversable.instances category.basic
open list subtype nat
variables {α : Type*} {β : Type*} {γ : Type*}
open_locale add_monoid
/-- `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
/- 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
/- 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 ((perm_cons a).2 p))
notation a :: b := cons a b
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,
eq_singleton_of_perm $ (perm_app_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 [perm_cons]
@[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` failes 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,
list.rec_heq_of_perm h
(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 $ mem_of_perm e)
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 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
/- 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
/- multiset order -/
/-- `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₂, subset_of_subperm
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, subperm_of_sublist $ nil_sublist l
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],
⟨subperm_of_sublist (sublist_cons _ _),
λ p, ne_of_lt (lt_succ_self (length l)) (perm_length p)⟩
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 $ subperm_of_sublist $
(sublist_or_mem_of_sublist s).resolve_right m₁)
end
/- 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 (s : multiset α) : ℕ :=
quot.lift_on s length $ λ l₁ l₂, perm_length
@[simp] theorem coe_card (l : list α) : card (l : multiset α) = length l := rfl
@[simp] theorem card_zero : @card α 0 = 0 := rfl
@[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 -/
@[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⟩
/- add -/
/-- 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 $ perm_app p₁ 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_app_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_app_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 α }
@[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]
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
@[simp] theorem card_add (s t : multiset α) : card (s + t) = card s + card t :=
quotient.induction_on₂ s t length_append
lemma card_smul (s : multiset α) (n : ℕ) :
(n • s).card = n * s.card :=
by induction n; simp [succ_smul, *, nat.succ_mul]; cc
@[simp] theorem mem_add {a : α} {s t : multiset α} : a ∈ s + t ↔ a ∈ s ∨ a ∈ t :=
quotient.induction_on₂ s t $ λ l₁ l₂, mem_append
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⟩ := exists_perm_append_of_sublist s in ⟨l, quot.sound p⟩,
λ⟨u, e⟩, e.symm ▸ le_add_right s u⟩
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 }
/- 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).symm).symm, 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.symm).symm ▸ s, subperm_of_sublist⟩
/- range -/
/-- `range n` is the multiset lifted from the list `range n`,
that is, the set `{0, 1, ..., n-1}`. -/
def range (n : ℕ) : multiset ℕ := range n
@[simp] theorem range_zero : range 0 = 0 := rfl
@[simp] theorem range_succ (n : ℕ) : range (succ n) = n :: range n :=
by rw [range, range_concat, ← coe_add, add_comm]; refl
@[simp] theorem card_range (n : ℕ) : card (range n) = n := length_range _
theorem range_subset {m n : ℕ} : range m ⊆ range n ↔ m ≤ n := range_subset
@[simp] theorem mem_range {m n : ℕ} : m ∈ range n ↔ m < n := mem_range
@[simp] theorem not_mem_range_self {n : ℕ} : n ∉ range n := not_mem_range_self
/- erase -/
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 (erase_perm_erase a p))
@[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_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, subperm_of_sublist (erase_sublist a l)
@[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, subperm_of_sublist (erase_sublist_erase _ h)
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 _
/- 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 (perm_map f p))
@[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
@[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 _ }
@[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_inj {f : α → β} (H : function.injective f) {a : α} {s : multiset α} :
f a ∈ map f s ↔ a ∈ s :=
quot.induction_on s $ λ l, mem_map_of_inj 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, subperm_of_sublist $ map_sublist_map f h
@[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⟩
/- 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, foldl_eq_of_perm H p 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, foldr_eq_of_perm H p 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 _
@[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, (add_monoid.smul n m).prod = m.prod ^ n
| 0 := rfl
| (n + 1) :=
by rw [add_monoid.add_smul, add_monoid.one_smul, _root_.pow_add, _root_.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])
@[to_additive]
lemma prod_hom [comm_monoid α] [comm_monoid β] (s : multiset α) (f : α → β) [is_monoid_hom 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_semiring α] {a : α} {s : multiset α} : a ∈ s → a ∣ s.prod :=
quotient.induction_on s (λ l a h, by simpa using list.dvd_prod h) a
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 [discrete_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)))))
/- 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)
/- 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 -/
/-- 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 -/
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 ((mem_of_perm pp).1 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 $ perm_pmap f pp
@[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 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 $ perm_diff_right w₁ p₂ ▸ perm_diff_left _ 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])
/- inter -/
/-- `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 $ perm_bag_inter_right w₁ p₂ ▸ perm_bag_inter_left _ 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₂,
subperm_of_sublist $ bag_inter_sublist_left _ _
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] 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
/- 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 (p : α → Prop) [h : decidable_pred p] (s : multiset α) : multiset α :=
quot.lift_on s (λ l, (filter p l : multiset α))
(λ l₁ l₂ h, quot.sound $ perm_filter p h)
@[simp] theorem coe_filter (p : α → Prop) [h : decidable_pred p]
(l : list α) : filter p (↑l) = l.filter p := rfl
@[simp] theorem filter_zero (p : α → Prop) [h : decidable_pred p] : filter p 0 = 0 := rfl
@[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
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, subperm_of_sublist $ filter_sublist _
@[simp] theorem filter_subset (s : multiset α) : filter p s ⊆ s :=
subset_of_le $ filter_le _
@[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 filter_le_filter {s t} (h : s ≤ t) : filter p s ≤ filter p t :=
le_induction_on h $ λ l₁ l₂ h, subperm_of_sublist $ filter_sublist_filter h
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 h⟩
@[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 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]
/- filter_map -/
/-- `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 $perm_filter_map f h)
@[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 (p : α → Prop) [decidable_pred p] :
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 (p : α → Prop) [decidable_pred p] (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,
subperm_of_sublist $ filter_map_sublist_filter_map _ h
/- powerset -/
def powerset_aux (l : list α) : list (multiset α) :=
0 :: sublists_aux l (λ x y, x :: y)
theorem powerset_aux_eq_map_coe {l : list α} :
powerset_aux l = (sublists l).map coe :=
by simp [powerset_aux, sublists];
rw [← show @sublists_aux₁ α (multiset α) l (λ x, [↑x]) =
sublists_aux l (λ x, list.cons ↑x),
from sublists_aux₁_eq_sublists_aux _ _,
sublists_aux_cons_eq_sublists_aux₁,
← bind_ret_eq_map, sublists_aux₁_bind]; refl
@[simp] theorem mem_powerset_aux {l : list α} {s} :
s ∈ powerset_aux l ↔ s ≤ ↑l :=
quotient.induction_on s $
by simp [powerset_aux_eq_map_coe, subperm, and.comm]
def powerset_aux' (l : list α) : list (multiset α) := (sublists' l).map coe
theorem powerset_aux_perm_powerset_aux' {l : list α} :
powerset_aux l ~ powerset_aux' l :=
by rw powerset_aux_eq_map_coe; exact
perm_map _ (sublists_perm_sublists' _)
@[simp] theorem powerset_aux'_nil : powerset_aux' (@nil α) = [0] := rfl
@[simp] theorem powerset_aux'_cons (a : α) (l : list α) :
powerset_aux' (a::l) = powerset_aux' l ++ list.map (cons a) (powerset_aux' l) :=
by simp [powerset_aux']; refl
theorem powerset_aux'_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) :
powerset_aux' l₁ ~ powerset_aux' l₂ :=
begin
induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp},
{ simp, exact perm_app IH (perm_map _ IH) },
{ simp, apply perm_app_right,
rw [← append_assoc, ← append_assoc,
(by funext s; simp [cons_swap] : cons b ∘ cons a = cons a ∘ cons b)],
exact perm_app_left _ perm_app_comm },
{ exact IH₁.trans IH₂ }
end
theorem powerset_aux_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) :
powerset_aux l₁ ~ powerset_aux l₂ :=
powerset_aux_perm_powerset_aux'.trans $
(powerset_aux'_perm p).trans powerset_aux_perm_powerset_aux'.symm
def powerset (s : multiset α) : multiset (multiset α) :=
quot.lift_on s
(λ l, (powerset_aux l : multiset (multiset α)))
(λ l₁ l₂ h, quot.sound (powerset_aux_perm h))
theorem powerset_coe (l : list α) :
@powerset α l = ((sublists l).map coe : list (multiset α)) :=
congr_arg coe powerset_aux_eq_map_coe
@[simp] theorem powerset_coe' (l : list α) :
@powerset α l = ((sublists' l).map coe : list (multiset α)) :=
quot.sound powerset_aux_perm_powerset_aux'
@[simp] theorem powerset_zero : @powerset α 0 = 0::0 := rfl
@[simp] theorem powerset_cons (a : α) (s) :
powerset (a::s) = powerset s + map (cons a) (powerset s) :=
quotient.induction_on s $ λ l, by simp; refl
@[simp] theorem mem_powerset {s t : multiset α} :
s ∈ powerset t ↔ s ≤ t :=
quotient.induction_on₂ s t $ by simp [subperm, and.comm]
theorem map_single_le_powerset (s : multiset α) :
s.map (λ a, a::0) ≤ powerset s :=
quotient.induction_on s $ λ l, begin
simp [powerset_coe],
show l.map (coe ∘ list.ret) <+~ (sublists l).map coe,
rw ← list.map_map,
exact subperm_of_sublist
(map_sublist_map _ (map_ret_sublist_sublists _))
end
@[simp] theorem card_powerset (s : multiset α) :
card (powerset s) = 2 ^ card s :=
quotient.induction_on s $ by simp
/- antidiagonal -/
theorem revzip_powerset_aux {l : list α} ⦃x⦄
(h : x ∈ revzip (powerset_aux l)) : x.1 + x.2 = ↑l :=
begin
rw [revzip, powerset_aux_eq_map_coe, ← map_reverse, zip_map, ← revzip] at h,
simp at h, rcases h with ⟨l₁, l₂, h, rfl, rfl⟩,
exact quot.sound (revzip_sublists _ _ _ h)
end
theorem revzip_powerset_aux' {l : list α} ⦃x⦄
(h : x ∈ revzip (powerset_aux' l)) : x.1 + x.2 = ↑l :=
begin
rw [revzip, powerset_aux', ← map_reverse, zip_map, ← revzip] at h,
simp at h, rcases h with ⟨l₁, l₂, h, rfl, rfl⟩,
exact quot.sound (revzip_sublists' _ _ _ h)
end
theorem revzip_powerset_aux_lemma [decidable_eq α] (l : list α)
{l' : list (multiset α)} (H : ∀ ⦃x : _ × _⦄, x ∈ revzip l' → x.1 + x.2 = ↑l) :
revzip l' = l'.map (λ x, (x, ↑l - x)) :=
begin
have : forall₂ (λ (p : multiset α × multiset α) (s : multiset α), p = (s, ↑l - s))
(revzip l') ((revzip l').map prod.fst),
{ rw forall₂_map_right_iff,
apply forall₂_same, rintro ⟨s, t⟩ h,
dsimp, rw [← H h, add_sub_cancel_left] },
rw [← forall₂_eq_eq_eq, forall₂_map_right_iff], simpa
end
theorem revzip_powerset_aux_perm_aux' {l : list α} :
revzip (powerset_aux l) ~ revzip (powerset_aux' l) :=
begin
haveI := classical.dec_eq α,
rw [revzip_powerset_aux_lemma l revzip_powerset_aux,
revzip_powerset_aux_lemma l revzip_powerset_aux'],
exact perm_map _ powerset_aux_perm_powerset_aux',
end
theorem revzip_powerset_aux_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) :
revzip (powerset_aux l₁) ~ revzip (powerset_aux l₂) :=
begin
haveI := classical.dec_eq α,
simp [λ l:list α, revzip_powerset_aux_lemma l revzip_powerset_aux, coe_eq_coe.2 p],
exact perm_map _ (powerset_aux_perm p)
end
/-- The antidiagonal of a multiset `s` consists of all pairs `(t₁, t₂)`
such that `t₁ + t₂ = s`. These pairs are counted with multiplicities. -/
def antidiagonal (s : multiset α) : multiset (multiset α × multiset α) :=
quot.lift_on s
(λ l, (revzip (powerset_aux l) : multiset (multiset α × multiset α)))
(λ l₁ l₂ h, quot.sound (revzip_powerset_aux_perm h))
theorem antidiagonal_coe (l : list α) :
@antidiagonal α l = revzip (powerset_aux l) := rfl
@[simp] theorem antidiagonal_coe' (l : list α) :
@antidiagonal α l = revzip (powerset_aux' l) :=
quot.sound revzip_powerset_aux_perm_aux'
/-- A pair `(t₁, t₂)` of multisets is contained in `antidiagonal s`
if and only if `t₁ + t₂ = s`. -/
@[simp] theorem mem_antidiagonal {s : multiset α} {x : multiset α × multiset α} :
x ∈ antidiagonal s ↔ x.1 + x.2 = s :=
quotient.induction_on s $ λ l, begin
simp [antidiagonal_coe], refine ⟨λ h, revzip_powerset_aux h, λ h, _⟩,
haveI := classical.dec_eq α,
simp [revzip_powerset_aux_lemma l revzip_powerset_aux, h.symm],
cases x with x₁ x₂,
exact ⟨_, le_add_right _ _, by rw add_sub_cancel_left _ _⟩
end
@[simp] theorem antidiagonal_map_fst (s : multiset α) :
(antidiagonal s).map prod.fst = powerset s :=
quotient.induction_on s $ λ l,
by simp [powerset_aux']
@[simp] theorem antidiagonal_map_snd (s : multiset α) :
(antidiagonal s).map prod.snd = powerset s :=
quotient.induction_on s $ λ l,
by simp [powerset_aux']
@[simp] theorem antidiagonal_zero : @antidiagonal α 0 = (0, 0)::0 := rfl
@[simp] theorem antidiagonal_cons (a : α) (s) : antidiagonal (a::s) =
map (prod.map id (cons a)) (antidiagonal s) +
map (prod.map (cons a) id) (antidiagonal s) :=
quotient.induction_on s $ λ l, begin
simp only [revzip, reverse_append, quot_mk_to_coe, coe_eq_coe, powerset_aux'_cons, cons_coe,
coe_map, antidiagonal_coe', coe_add],
rw [← zip_map, ← zip_map, zip_append, (_ : _++_=_)],
{congr; simp}, {simp}
end
@[simp] theorem card_antidiagonal (s : multiset α) :
card (antidiagonal s) = 2 ^ card s :=
by have := card_powerset s;
rwa [← antidiagonal_map_fst, card_map] at this
lemma prod_map_add [comm_semiring β] {s : multiset α} {f g : α → β} :
prod (s.map (λa, f a + g a)) =
sum ((antidiagonal s).map (λp, (p.1.map f).prod * (p.2.map g).prod)) :=
begin
refine s.induction_on _ _,
{ simp },
{ assume a s ih,
simp [ih, add_mul, mul_comm, mul_left_comm, mul_assoc, sum_map_mul_left.symm],
cc },
end
/- powerset_len -/
def powerset_len_aux (n : ℕ) (l : list α) : list (multiset α) :=
sublists_len_aux n l coe []
theorem powerset_len_aux_eq_map_coe {n} {l : list α} :
powerset_len_aux n l = (sublists_len n l).map coe :=
by rw [powerset_len_aux, sublists_len_aux_eq, append_nil]
@[simp] theorem mem_powerset_len_aux {n} {l : list α} {s} :
s ∈ powerset_len_aux n l ↔ s ≤ ↑l ∧ card s = n :=
quotient.induction_on s $
by simp [powerset_len_aux_eq_map_coe, subperm]; exact
λ l₁, ⟨λ ⟨l₂, ⟨s, e⟩, p⟩, ⟨⟨_, p, s⟩, (perm_length p.symm).trans e⟩,
λ ⟨⟨l₂, p, s⟩, e⟩, ⟨_, ⟨s, (perm_length p).trans e⟩, p⟩⟩
@[simp] theorem powerset_len_aux_zero (l : list α) :
powerset_len_aux 0 l = [0] :=
by simp [powerset_len_aux_eq_map_coe]
@[simp] theorem powerset_len_aux_nil (n : ℕ) :
powerset_len_aux (n+1) (@nil α) = [] := rfl
@[simp] theorem powerset_len_aux_cons (n : ℕ) (a : α) (l : list α) :
powerset_len_aux (n+1) (a::l) =
powerset_len_aux (n+1) l ++ list.map (cons a) (powerset_len_aux n l) :=
by simp [powerset_len_aux_eq_map_coe]; refl
theorem powerset_len_aux_perm {n} {l₁ l₂ : list α} (p : l₁ ~ l₂) :
powerset_len_aux n l₁ ~ powerset_len_aux n l₂ :=
begin
induction n with n IHn generalizing l₁ l₂, {simp},
induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {refl},
{ simp, exact perm_app IH (perm_map _ (IHn p)) },
{ simp, apply perm_app_right,
cases n, {simp, apply perm.swap},
simp,
rw [← append_assoc, ← append_assoc,
(by funext s; simp [cons_swap] : cons b ∘ cons a = cons a ∘ cons b)],
exact perm_app_left _ perm_app_comm },
{ exact IH₁.trans IH₂ }
end
def powerset_len (n : ℕ) (s : multiset α) : multiset (multiset α) :=
quot.lift_on s
(λ l, (powerset_len_aux n l : multiset (multiset α)))
(λ l₁ l₂ h, quot.sound (powerset_len_aux_perm h))
theorem powerset_len_coe' (n) (l : list α) :
@powerset_len α n l = powerset_len_aux n l := rfl
theorem powerset_len_coe (n) (l : list α) :
@powerset_len α n l = ((sublists_len n l).map coe : list (multiset α)) :=
congr_arg coe powerset_len_aux_eq_map_coe
@[simp] theorem powerset_len_zero_left (s : multiset α) :
powerset_len 0 s = 0::0 :=
quotient.induction_on s $ λ l, by simp [powerset_len_coe']; refl
@[simp] theorem powerset_len_zero_right (n : ℕ) :
@powerset_len α (n + 1) 0 = 0 := rfl
@[simp] theorem powerset_len_cons (n : ℕ) (a : α) (s) :
powerset_len (n + 1) (a::s) =
powerset_len (n + 1) s + map (cons a) (powerset_len n s) :=
quotient.induction_on s $ λ l, by simp [powerset_len_coe']; refl
@[simp] theorem mem_powerset_len {n : ℕ} {s t : multiset α} :
s ∈ powerset_len n t ↔ s ≤ t ∧ card s = n :=
quotient.induction_on t $ λ l, by simp [powerset_len_coe']
@[simp] theorem card_powerset_len (n : ℕ) (s : multiset α) :
card (powerset_len n s) = nat.choose (card s) n :=
quotient.induction_on s $ by simp [powerset_len_coe]
theorem powerset_len_le_powerset (n : ℕ) (s : multiset α) :
powerset_len n s ≤ powerset s :=
quotient.induction_on s $ λ l, by simp [powerset_len_coe]; exact
subperm_of_sublist (map_sublist_map _ (sublists_len_sublist_sublists' _ _))
theorem powerset_len_mono (n : ℕ) {s t : multiset α} (h : s ≤ t) :
powerset_len n s ≤ powerset_len n t :=
le_induction_on h $ λ l₁ l₂ h, by simp [powerset_len_coe]; exact
subperm_of_sublist (map_sublist_map _ (sublists_len_sublist_of_sublist _ h))
/- countp -/
/-- `countp p s` counts the number of elements of `s` (with multiplicity) that
satisfy `p`. -/
def countp (p : α → Prop) [decidable_pred p] (s : multiset α) : ℕ :=
quot.lift_on s (countp p) (λ l₁ l₂, perm_countp p)
@[simp] theorem coe_countp (l : list α) : countp p l = l.countp p := rfl
@[simp] theorem countp_zero (p : α → Prop) [decidable_pred p] : countp p 0 = 0 := rfl
@[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
@[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
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 _ }
theorem countp_pos {s} : 0 < countp p s ↔ ∃ a ∈ s, p a :=
by simp [countp_eq_card_filter, card_pos_iff_exists_mem]
@[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_pos_of_mem {s a} (h : a ∈ s) (pa : p a) : 0 < countp p s :=
countp_pos.2 ⟨_, h, pa⟩
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 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]
end
/- count -/
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_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_smul', 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')
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
@[simp] theorem count_repeat (a : α) (n : ℕ) : count a (repeat a n) = n :=
by simp [repeat]
@[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_bind {m : multiset β} {f : β → multiset α} {a : α} :
count a (bind m f) = sum (m.map $ λb, count a $ f b) :=
multiset.induction_on m (by simp) (by simp)
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 {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
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
/- relator -/
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`. -/
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)
run_cmd tactic.mk_iff_of_inductive_prop `multiset.rel `multiset.rel_iff
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 injective_map {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 -/
/-- `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) :=
begin
simp [disjoint],
split,
from assume h a ha b hb eq, h _ ha rfl _ hb eq.symm,
from assume h c a ha eq₁ b hb eq₂, h _ ha _ hb (eq₂.symm ▸ eq₁)
end
/-- `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⟩, (list.perm_pairwise hr (quotient.exact eq)).2 h)
(assume h, ⟨l, rfl, h⟩)
/- nodup -/
/-- `nodup s` means that `s` has no duplicates, i.e. the multiplicity of
any element is at most 1. -/
def nodup (s : multiset α) : Prop :=
quot.lift_on s nodup (λ s t p, propext $ perm_nodup p)
@[simp] theorem coe_nodup {l : list α} : @nodup α l ↔ l.nodup := iff.rfl
@[simp] theorem nodup_zero : @nodup α 0 := pairwise.nil
@[simp] theorem nodup_cons {a : α} {s : multiset α} : nodup (a::s) ↔ a ∉ s ∧ nodup s :=
quot.induction_on s $ λ l, nodup_cons
theorem nodup_cons_of_nodup {a : α} {s : multiset α} (m : a ∉ s) (n : nodup s) : nodup (a::s) :=
nodup_cons.2 ⟨m, n⟩
theorem nodup_singleton : ∀ a : α, nodup (a::0) := nodup_singleton
theorem nodup_of_nodup_cons {a : α} {s : multiset α} (h : nodup (a::s)) : nodup s :=
(nodup_cons.1 h).2
theorem not_mem_of_nodup_cons {a : α} {s : multiset α} (h : nodup (a::s)) : a ∉ s :=
(nodup_cons.1 h).1
theorem nodup_of_le {s t : multiset α} (h : s ≤ t) : nodup t → nodup s :=
le_induction_on h $ λ l₁ l₂, nodup_of_sublist
theorem not_nodup_pair : ∀ a : α, ¬ nodup (a::a::0) := not_nodup_pair
theorem nodup_iff_le {s : multiset α} : nodup s ↔ ∀ a : α, ¬ a::a::0 ≤ s :=
quot.induction_on s $ λ l, nodup_iff_sublist.trans $ forall_congr $ λ a,
not_congr (@repeat_le_coe _ a 2 _).symm
theorem nodup_iff_count_le_one [decidable_eq α] {s : multiset α} : nodup s ↔ ∀ a, count a s ≤ 1 :=
quot.induction_on s $ λ l, nodup_iff_count_le_one
@[simp] theorem count_eq_one_of_mem [decidable_eq α] {a : α} {s : multiset α}
(d : nodup s) (h : a ∈ s) : count a s = 1 :=
le_antisymm (nodup_iff_count_le_one.1 d a) (count_pos.2 h)
lemma pairwise_of_nodup {r : α → α → Prop} {s : multiset α} :
(∀a∈s, ∀b∈s, a ≠ b → r a b) → nodup s → pairwise r s :=
quotient.induction_on s $ assume l h hl, ⟨l, rfl, hl.imp_of_mem $ assume a b ha hb, h a ha b hb⟩
lemma forall_of_pairwise {r : α → α → Prop} (H : symmetric r) {s : multiset α}
(hs : pairwise r s) : (∀a∈s, ∀b∈s, a ≠ b → r a b) :=
let ⟨l, hl₁, hl₂⟩ := hs in hl₁.symm ▸ list.forall_of_pairwise H hl₂
theorem nodup_add {s t : multiset α} : nodup (s + t) ↔ nodup s ∧ nodup t ∧ disjoint s t :=
quotient.induction_on₂ s t $ λ l₁ l₂, nodup_append
theorem disjoint_of_nodup_add {s t : multiset α} (d : nodup (s + t)) : disjoint s t :=
(nodup_add.1 d).2.2
theorem nodup_add_of_nodup {s t : multiset α} (d₁ : nodup s) (d₂ : nodup t) : nodup (s + t) ↔ disjoint s t :=
by simp [nodup_add, d₁, d₂]
theorem nodup_of_nodup_map (f : α → β) {s : multiset α} : nodup (map f s) → nodup s :=
quot.induction_on s $ λ l, nodup_of_nodup_map f
theorem nodup_map_on {f : α → β} {s : multiset α} : (∀x∈s, ∀y∈s, f x = f y → x = y) →
nodup s → nodup (map f s) :=
quot.induction_on s $ λ l, nodup_map_on
theorem nodup_map {f : α → β} {s : multiset α} (hf : function.injective f) : nodup s → nodup (map f s) :=
nodup_map_on (λ x _ y _ h, hf h)
theorem nodup_filter (p : α → Prop) [decidable_pred p] {s} : nodup s → nodup (filter p s) :=
quot.induction_on s $ λ l, nodup_filter p
@[simp] theorem nodup_attach {s : multiset α} : nodup (attach s) ↔ nodup s :=
quot.induction_on s $ λ l, nodup_attach
theorem nodup_pmap {p : α → Prop} {f : Π a, p a → β} {s : multiset α} {H}
(hf : ∀ a ha b hb, f a ha = f b hb → a = b) : nodup s → nodup (pmap f s H) :=
quot.induction_on s (λ l H, nodup_pmap hf) H
instance nodup_decidable [decidable_eq α] (s : multiset α) : decidable (nodup s) :=
quotient.rec_on_subsingleton s $ λ l, l.nodup_decidable
theorem nodup_erase_eq_filter [decidable_eq α] (a : α) {s} : nodup s → s.erase a = filter (≠ a) s :=
quot.induction_on s $ λ l d, congr_arg coe $ nodup_erase_eq_filter a d
theorem nodup_erase_of_nodup [decidable_eq α] (a : α) {l} : nodup l → nodup (l.erase a) :=
nodup_of_le (erase_le _ _)
theorem mem_erase_iff_of_nodup [decidable_eq α] {a b : α} {l} (d : nodup l) :
a ∈ l.erase b ↔ a ≠ b ∧ a ∈ l :=
by rw nodup_erase_eq_filter b d; simp [and_comm]
theorem mem_erase_of_nodup [decidable_eq α] {a : α} {l} (h : nodup l) : a ∉ l.erase a :=
by rw mem_erase_iff_of_nodup h; simp
theorem nodup_product {s : multiset α} {t : multiset β} : nodup s → nodup t → nodup (product s t) :=
quotient.induction_on₂ s t $ λ l₁ l₂ d₁ d₂, by simp [nodup_product d₁ d₂]
theorem nodup_sigma {σ : α → Type*} {s : multiset α} {t : Π a, multiset (σ a)} :
nodup s → (∀ a, nodup (t a)) → nodup (s.sigma t) :=
quot.induction_on s $ assume l₁,
begin
choose f hf using assume a, quotient.exists_rep (t a),
rw show t = λ a, f a, from (eq.symm $ funext $ λ a, hf a),
simpa using nodup_sigma
end
theorem nodup_filter_map (f : α → option β) {s : multiset α}
(H : ∀ (a a' : α) (b : β), b ∈ f a → b ∈ f a' → a = a') :
nodup s → nodup (filter_map f s) :=
quot.induction_on s $ λ l, nodup_filter_map H
theorem nodup_range (n : ℕ) : nodup (range n) := nodup_range _
theorem nodup_inter_left [decidable_eq α] {s : multiset α} (t) : nodup s → nodup (s ∩ t) :=
nodup_of_le $ inter_le_left _ _
theorem nodup_inter_right [decidable_eq α] (s) {t : multiset α} : nodup t → nodup (s ∩ t) :=
nodup_of_le $ inter_le_right _ _
@[simp] theorem nodup_union [decidable_eq α] {s t : multiset α} : nodup (s ∪ t) ↔ nodup s ∧ nodup t :=
⟨λ h, ⟨nodup_of_le (le_union_left _ _) h, nodup_of_le (le_union_right _ _) h⟩,
λ ⟨h₁, h₂⟩, nodup_iff_count_le_one.2 $ λ a, by rw [count_union]; exact
max_le (nodup_iff_count_le_one.1 h₁ a) (nodup_iff_count_le_one.1 h₂ a)⟩
@[simp] theorem nodup_powerset {s : multiset α} : nodup (powerset s) ↔ nodup s :=
⟨λ h, nodup_of_nodup_map _ (nodup_of_le (map_single_le_powerset _) h),
quotient.induction_on s $ λ l h,
by simp; refine list.nodup_map_on _ (nodup_sublists'.2 h); exact
λ x sx y sy e,
(perm_ext_sublist_nodup h (mem_sublists'.1 sx) (mem_sublists'.1 sy)).1
(quotient.exact e)⟩
theorem nodup_powerset_len {n : ℕ} {s : multiset α}
(h : nodup s) : nodup (powerset_len n s) :=
nodup_of_le (powerset_len_le_powerset _ _) (nodup_powerset.2 h)
@[simp] lemma nodup_bind {s : multiset α} {t : α → multiset β} :
nodup (bind s t) ↔ ((∀a∈s, nodup (t a)) ∧ (s.pairwise (λa b, disjoint (t a) (t b)))) :=
have h₁ : ∀a, ∃l:list β, t a = l, from
assume a, quot.induction_on (t a) $ assume l, ⟨l, rfl⟩,
let ⟨t', h'⟩ := classical.axiom_of_choice h₁ in
have t = λa, t' a, from funext h',
have hd : symmetric (λa b, list.disjoint (t' a) (t' b)), from assume a b h, h.symm,
quot.induction_on s $ by simp [this, list.nodup_bind, pairwise_coe_iff_pairwise hd]
theorem nodup_ext {s t : multiset α} : nodup s → nodup t → (s = t ↔ ∀ a, a ∈ s ↔ a ∈ t) :=
quotient.induction_on₂ s t $ λ l₁ l₂ d₁ d₂, quotient.eq.trans $ perm_ext d₁ d₂
theorem le_iff_subset {s t : multiset α} : nodup s → (s ≤ t ↔ s ⊆ t) :=
quotient.induction_on₂ s t $ λ l₁ l₂ d, ⟨subset_of_le, subperm_of_subset_nodup d⟩
theorem range_le {m n : ℕ} : range m ≤ range n ↔ m ≤ n :=
(le_iff_subset (nodup_range _)).trans range_subset
theorem mem_sub_of_nodup [decidable_eq α] {a : α} {s t : multiset α} (d : nodup s) :
a ∈ s - t ↔ a ∈ s ∧ a ∉ t :=
⟨λ h, ⟨mem_of_le (sub_le_self _ _) h, λ h',
by refine count_eq_zero.1 _ h; rw [count_sub a s t, nat.sub_eq_zero_iff_le];
exact le_trans (nodup_iff_count_le_one.1 d _) (count_pos.2 h')⟩,
λ ⟨h₁, h₂⟩, or.resolve_right (mem_add.1 $ mem_of_le (le_sub_add _ _) h₁) h₂⟩
lemma map_eq_map_of_bij_of_nodup (f : α → γ) (g : β → γ) {s : multiset α} {t : multiset β}
(hs : s.nodup) (ht : t.nodup) (i : Πa∈s, β)
(hi : ∀a ha, i a ha ∈ t) (h : ∀a ha, f a = g (i a ha))
(i_inj : ∀a₁ a₂ ha₁ ha₂, i a₁ ha₁ = i a₂ ha₂ → a₁ = a₂)
(i_surj : ∀b∈t, ∃a ha, b = i a ha) :
s.map f = t.map g :=
have t = s.attach.map (λ x, i x.1 x.2),
from (nodup_ext ht (nodup_map
(show function.injective (λ x : {x // x ∈ s}, i x.1 x.2), from λ x y hxy,
subtype.eq (i_inj x.1 y.1 x.2 y.2 hxy))
(nodup_attach.2 hs))).2
(λ x, by simp only [mem_map, true_and, subtype.exists, eq_comm, mem_attach];
exact ⟨i_surj _, λ ⟨y, hy⟩, hy.snd.symm ▸ hi _ _⟩),
calc s.map f = s.pmap (λ x _, f x) (λ _, id) : by rw [pmap_eq_map]
... = s.attach.map (λ x, f x.1) : by rw [pmap_eq_map_attach]
... = t.map g : by rw [this, multiset.map_map]; exact map_congr (λ x _, h _ _)
section
variable [decidable_eq α]
/- erase_dup -/
/-- `erase_dup s` removes duplicates from `s`, yielding a `nodup` multiset. -/
def erase_dup (s : multiset α) : multiset α :=
quot.lift_on s (λ l, (l.erase_dup : multiset α))
(λ s t p, quot.sound (perm_erase_dup_of_perm p))
@[simp] theorem coe_erase_dup (l : list α) : @erase_dup α _ l = l.erase_dup := rfl
@[simp] theorem erase_dup_zero : @erase_dup α _ 0 = 0 := rfl
@[simp] theorem mem_erase_dup {a : α} {s : multiset α} : a ∈ erase_dup s ↔ a ∈ s :=
quot.induction_on s $ λ l, mem_erase_dup
@[simp] theorem erase_dup_cons_of_mem {a : α} {s : multiset α} : a ∈ s →
erase_dup (a::s) = erase_dup s :=
quot.induction_on s $ λ l m, @congr_arg _ _ _ _ coe $ erase_dup_cons_of_mem m
@[simp] theorem erase_dup_cons_of_not_mem {a : α} {s : multiset α} : a ∉ s →
erase_dup (a::s) = a :: erase_dup s :=
quot.induction_on s $ λ l m, congr_arg coe $ erase_dup_cons_of_not_mem m
theorem erase_dup_le (s : multiset α) : erase_dup s ≤ s :=
quot.induction_on s $ λ l, subperm_of_sublist $ erase_dup_sublist _
theorem erase_dup_subset (s : multiset α) : erase_dup s ⊆ s :=
subset_of_le $ erase_dup_le _
theorem subset_erase_dup (s : multiset α) : s ⊆ erase_dup s :=
λ a, mem_erase_dup.2
@[simp] theorem erase_dup_subset' {s t : multiset α} : erase_dup s ⊆ t ↔ s ⊆ t :=
⟨subset.trans (subset_erase_dup _), subset.trans (erase_dup_subset _)⟩
@[simp] theorem subset_erase_dup' {s t : multiset α} : s ⊆ erase_dup t ↔ s ⊆ t :=
⟨λ h, subset.trans h (erase_dup_subset _), λ h, subset.trans h (subset_erase_dup _)⟩
@[simp] theorem nodup_erase_dup (s : multiset α) : nodup (erase_dup s) :=
quot.induction_on s nodup_erase_dup
theorem erase_dup_eq_self {s : multiset α} : erase_dup s = s ↔ nodup s :=
⟨λ e, e ▸ nodup_erase_dup s,
quot.induction_on s $ λ l h, congr_arg coe $ erase_dup_eq_self.2 h⟩
theorem erase_dup_eq_zero {s : multiset α} : erase_dup s = 0 ↔ s = 0 :=
⟨λ h, eq_zero_of_subset_zero $ h ▸ subset_erase_dup _,
λ h, h.symm ▸ erase_dup_zero⟩
@[simp] theorem erase_dup_singleton {a : α} : erase_dup (a :: 0) = a :: 0 :=
erase_dup_eq_self.2 $ nodup_singleton _
theorem le_erase_dup {s t : multiset α} : s ≤ erase_dup t ↔ s ≤ t ∧ nodup s :=
⟨λ h, ⟨le_trans h (erase_dup_le _), nodup_of_le h (nodup_erase_dup _)⟩,
λ ⟨l, d⟩, (le_iff_subset d).2 $ subset.trans (subset_of_le l) (subset_erase_dup _)⟩
theorem erase_dup_ext {s t : multiset α} : erase_dup s = erase_dup t ↔ ∀ a, a ∈ s ↔ a ∈ t :=
by simp [nodup_ext]
theorem erase_dup_map_erase_dup_eq [decidable_eq β] (f : α → β) (s : multiset α) :
erase_dup (map f (erase_dup s)) = erase_dup (map f s) := by simp [erase_dup_ext]
/- finset insert -/
/-- `ndinsert a s` is the lift of the list `insert` operation. This operation
does not respect multiplicities, unlike `cons`, but it is suitable as
an insert operation on `finset`. -/
def ndinsert (a : α) (s : multiset α) : multiset α :=
quot.lift_on s (λ l, (l.insert a : multiset α))
(λ s t p, quot.sound (perm_insert a p))
@[simp] theorem coe_ndinsert (a : α) (l : list α) : ndinsert a l = (insert a l : list α) := rfl
@[simp] theorem ndinsert_zero (a : α) : ndinsert a 0 = a::0 := rfl
@[simp, priority 980]
theorem ndinsert_of_mem {a : α} {s : multiset α} : a ∈ s → ndinsert a s = s :=
quot.induction_on s $ λ l h, congr_arg coe $ insert_of_mem h
@[simp, priority 980]
theorem ndinsert_of_not_mem {a : α} {s : multiset α} : a ∉ s → ndinsert a s = a :: s :=
quot.induction_on s $ λ l h, congr_arg coe $ insert_of_not_mem h
@[simp] theorem mem_ndinsert {a b : α} {s : multiset α} : a ∈ ndinsert b s ↔ a = b ∨ a ∈ s :=
quot.induction_on s $ λ l, mem_insert_iff
@[simp] theorem le_ndinsert_self (a : α) (s : multiset α) : s ≤ ndinsert a s :=
quot.induction_on s $ λ l, subperm_of_sublist $ sublist_of_suffix $ suffix_insert _ _
@[simp] theorem mem_ndinsert_self (a : α) (s : multiset α) : a ∈ ndinsert a s :=
mem_ndinsert.2 (or.inl rfl)
theorem mem_ndinsert_of_mem {a b : α} {s : multiset α} (h : a ∈ s) : a ∈ ndinsert b s :=
mem_ndinsert.2 (or.inr h)
@[simp, priority 980]
theorem length_ndinsert_of_mem {a : α} {s : multiset α} (h : a ∈ s) :
card (ndinsert a s) = card s :=
by simp [h]
@[simp, priority 980]
theorem length_ndinsert_of_not_mem {a : α} {s : multiset α} (h : a ∉ s) :
card (ndinsert a s) = card s + 1 :=
by simp [h]
theorem erase_dup_cons {a : α} {s : multiset α} :
erase_dup (a::s) = ndinsert a (erase_dup s) :=
by by_cases a ∈ s; simp [h]
theorem nodup_ndinsert (a : α) {s : multiset α} : nodup s → nodup (ndinsert a s) :=
quot.induction_on s $ λ l, nodup_insert
theorem ndinsert_le {a : α} {s t : multiset α} : ndinsert a s ≤ t ↔ s ≤ t ∧ a ∈ t :=
⟨λ h, ⟨le_trans (le_ndinsert_self _ _) h, mem_of_le h (mem_ndinsert_self _ _)⟩,
λ ⟨l, m⟩, if h : a ∈ s then by simp [h, l] else
by rw [ndinsert_of_not_mem h, ← cons_erase m, cons_le_cons_iff,
← le_cons_of_not_mem h, cons_erase m]; exact l⟩
lemma attach_ndinsert (a : α) (s : multiset α) :
(s.ndinsert a).attach =
ndinsert ⟨a, mem_ndinsert_self a s⟩ (s.attach.map $ λp, ⟨p.1, mem_ndinsert_of_mem p.2⟩) :=
have eq : ∀h : ∀(p : {x // x ∈ s}), p.1 ∈ s,
(λ (p : {x // x ∈ s}), ⟨p.val, h p⟩ : {x // x ∈ s} → {x // x ∈ s}) = id, from
assume h, funext $ assume p, subtype.eq rfl,
have ∀t (eq : s.ndinsert a = t), t.attach = ndinsert ⟨a, eq ▸ mem_ndinsert_self a s⟩
(s.attach.map $ λp, ⟨p.1, eq ▸ mem_ndinsert_of_mem p.2⟩),
begin
intros t ht,
by_cases a ∈ s,
{ rw [ndinsert_of_mem h] at ht,
subst ht,
rw [eq, map_id, ndinsert_of_mem (mem_attach _ _)] },
{ rw [ndinsert_of_not_mem h] at ht,
subst ht,
simp [attach_cons, h] }
end,
this _ rfl
@[simp] theorem disjoint_ndinsert_left {a : α} {s t : multiset α} :
disjoint (ndinsert a s) t ↔ a ∉ t ∧ disjoint s t :=
iff.trans (by simp [disjoint]) disjoint_cons_left
@[simp] theorem disjoint_ndinsert_right {a : α} {s t : multiset α} :
disjoint s (ndinsert a t) ↔ a ∉ s ∧ disjoint s t :=
by rw [disjoint_comm, disjoint_ndinsert_left]; tauto
/- finset union -/
/-- `ndunion s t` is the lift of the list `union` operation. This operation
does not respect multiplicities, unlike `s ∪ t`, but it is suitable as
a union operation on `finset`. (`s ∪ t` would also work as a union operation
on finset, but this is more efficient.) -/
def ndunion (s t : multiset α) : multiset α :=
quotient.lift_on₂ s t (λ l₁ l₂, (l₁.union l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂,
quot.sound $ perm_union p₁ p₂
@[simp] theorem coe_ndunion (l₁ l₂ : list α) : @ndunion α _ l₁ l₂ = (l₁ ∪ l₂ : list α) := rfl
@[simp] theorem zero_ndunion (s : multiset α) : ndunion 0 s = s :=
quot.induction_on s $ λ l, rfl
@[simp] theorem cons_ndunion (s t : multiset α) (a : α) : ndunion (a :: s) t = ndinsert a (ndunion s t) :=
quotient.induction_on₂ s t $ λ l₁ l₂, rfl
@[simp] theorem mem_ndunion {s t : multiset α} {a : α} : a ∈ ndunion s t ↔ a ∈ s ∨ a ∈ t :=
quotient.induction_on₂ s t $ λ l₁ l₂, list.mem_union
theorem le_ndunion_right (s t : multiset α) : t ≤ ndunion s t :=
quotient.induction_on₂ s t $ λ l₁ l₂,
subperm_of_sublist $ sublist_of_suffix $ suffix_union_right _ _
theorem ndunion_le_add (s t : multiset α) : ndunion s t ≤ s + t :=
quotient.induction_on₂ s t $ λ l₁ l₂, subperm_of_sublist $ union_sublist_append _ _
theorem ndunion_le {s t u : multiset α} : ndunion s t ≤ u ↔ s ⊆ u ∧ t ≤ u :=
multiset.induction_on s (by simp) (by simp [ndinsert_le, and_comm, and.left_comm] {contextual := tt})
theorem subset_ndunion_left (s t : multiset α) : s ⊆ ndunion s t :=
λ a h, mem_ndunion.2 $ or.inl h
theorem le_ndunion_left {s} (t : multiset α) (d : nodup s) : s ≤ ndunion s t :=
(le_iff_subset d).2 $ subset_ndunion_left _ _
theorem ndunion_le_union (s t : multiset α) : ndunion s t ≤ s ∪ t :=
ndunion_le.2 ⟨subset_of_le (le_union_left _ _), le_union_right _ _⟩
theorem nodup_ndunion (s : multiset α) {t : multiset α} : nodup t → nodup (ndunion s t) :=
quotient.induction_on₂ s t $ λ l₁ l₂, list.nodup_union _
@[simp, priority 980]
theorem ndunion_eq_union {s t : multiset α} (d : nodup s) : ndunion s t = s ∪ t :=
le_antisymm (ndunion_le_union _ _) $ union_le (le_ndunion_left _ d) (le_ndunion_right _ _)
theorem erase_dup_add (s t : multiset α) : erase_dup (s + t) = ndunion s (erase_dup t) :=
quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ erase_dup_append _ _
/- finset inter -/
/-- `ndinter s t` is the lift of the list `∩` operation. This operation
does not respect multiplicities, unlike `s ∩ t`, but it is suitable as
an intersection operation on `finset`. (`s ∩ t` would also work as a union operation
on finset, but this is more efficient.) -/
def ndinter (s t : multiset α) : multiset α := filter (∈ t) s
@[simp] theorem coe_ndinter (l₁ l₂ : list α) : @ndinter α _ l₁ l₂ = (l₁ ∩ l₂ : list α) := rfl
@[simp] theorem zero_ndinter (s : multiset α) : ndinter 0 s = 0 := rfl
@[simp, priority 980]
theorem cons_ndinter_of_mem {a : α} (s : multiset α) {t : multiset α} (h : a ∈ t) :
ndinter (a::s) t = a :: (ndinter s t) := by simp [ndinter, h]
@[simp, priority 980]
theorem ndinter_cons_of_not_mem {a : α} (s : multiset α) {t : multiset α} (h : a ∉ t) :
ndinter (a::s) t = ndinter s t := by simp [ndinter, h]
@[simp] theorem mem_ndinter {s t : multiset α} {a : α} : a ∈ ndinter s t ↔ a ∈ s ∧ a ∈ t :=
mem_filter
@[simp]
theorem nodup_ndinter {s : multiset α} (t : multiset α) : nodup s → nodup (ndinter s t) :=
nodup_filter _
theorem le_ndinter {s t u : multiset α} : s ≤ ndinter t u ↔ s ≤ t ∧ s ⊆ u :=
by simp [ndinter, le_filter, subset_iff]
theorem ndinter_le_left (s t : multiset α) : ndinter s t ≤ s :=
(le_ndinter.1 (le_refl _)).1
theorem ndinter_subset_right (s t : multiset α) : ndinter s t ⊆ t :=
(le_ndinter.1 (le_refl _)).2
theorem ndinter_le_right {s} (t : multiset α) (d : nodup s) : ndinter s t ≤ t :=
(le_iff_subset $ nodup_ndinter _ d).2 (ndinter_subset_right _ _)
theorem inter_le_ndinter (s t : multiset α) : s ∩ t ≤ ndinter s t :=
le_ndinter.2 ⟨inter_le_left _ _, subset_of_le $ inter_le_right _ _⟩
@[simp, priority 980]
theorem ndinter_eq_inter {s t : multiset α} (d : nodup s) : ndinter s t = s ∩ t :=
le_antisymm (le_inter (ndinter_le_left _ _) (ndinter_le_right _ d)) (inter_le_ndinter _ _)
theorem ndinter_eq_zero_iff_disjoint {s t : multiset α} : ndinter s t = 0 ↔ disjoint s t :=
by rw ← subset_zero; simp [subset_iff, disjoint]
end
/- fold -/
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 s` folds a commutative associative operation `op` over
the multiset `s`. -/
def fold : α → multiset α → α := foldr op (left_comm _ hc.comm ha.assoc)
theorem fold_eq_foldr (b : α) (s : multiset α) : fold op b s = foldr op (left_comm _ hc.comm ha.assoc) b s := rfl
@[simp] theorem coe_fold_r (b : α) (l : list α) : fold op b l = l.foldr op b := rfl
theorem coe_fold_l (b : α) (l : list α) : fold op b l = l.foldl op b :=
(coe_foldr_swap op _ b l).trans $ by simp [hc.comm]
theorem fold_eq_foldl (b : α) (s : multiset α) : fold op b s = foldl op (right_comm _ hc.comm ha.assoc) b s :=
quot.induction_on s $ λ l, coe_fold_l _ _ _
@[simp] theorem fold_zero (b : α) : (0 : multiset α).fold op b = b := rfl
@[simp] theorem fold_cons_left : ∀ (b a : α) (s : multiset α),
(a :: s).fold op b = a * s.fold op b := foldr_cons _ _
theorem fold_cons_right (b a : α) (s : multiset α) : (a :: s).fold op b = s.fold op b * a :=
by simp [hc.comm]
theorem fold_cons'_right (b a : α) (s : multiset α) : (a :: s).fold op b = s.fold op (b * a) :=
by rw [fold_eq_foldl, foldl_cons, ← fold_eq_foldl]
theorem fold_cons'_left (b a : α) (s : multiset α) : (a :: s).fold op b = s.fold op (a * b) :=
by rw [fold_cons'_right, hc.comm]
theorem fold_add (b₁ b₂ : α) (s₁ s₂ : multiset α) : (s₁ + s₂).fold op (b₁ * b₂) = s₁.fold op b₁ * s₂.fold op b₂ :=
multiset.induction_on s₂
(by rw [add_zero, fold_zero, ← fold_cons'_right, ← fold_cons_right op])
(by simp {contextual := tt}; cc)
theorem fold_singleton (b a : α) : (a::0 : multiset α).fold op b = a * b := by simp
theorem fold_distrib {f g : β → α} (u₁ u₂ : α) (s : multiset β) :
(s.map (λx, f x * g x)).fold op (u₁ * u₂) = (s.map f).fold op u₁ * (s.map g).fold op u₂ :=
multiset.induction_on s (by simp) (by simp {contextual := tt}; cc)
theorem fold_hom {op' : β → β → β} [is_commutative β op'] [is_associative β op']
{m : α → β} (hm : ∀x y, m (op x y) = op' (m x) (m y)) (b : α) (s : multiset α) :
(s.map m).fold op' (m b) = m (s.fold op b) :=
multiset.induction_on s (by simp) (by simp [hm] {contextual := tt})
theorem fold_union_inter [decidable_eq α] (s₁ s₂ : multiset α) (b₁ b₂ : α) :
(s₁ ∪ s₂).fold op b₁ * (s₁ ∩ s₂).fold op b₂ = s₁.fold op b₁ * s₂.fold op b₂ :=
by rw [← fold_add op, union_add_inter, fold_add op]
@[simp] theorem fold_erase_dup_idem [decidable_eq α] [hi : is_idempotent α op] (s : multiset α) (b : α) :
(erase_dup s).fold op b = s.fold op b :=
multiset.induction_on s (by simp) $ λ a s IH, begin
by_cases a ∈ s; simp [IH, h],
show fold op b s = op a (fold op b s),
rw [← cons_erase h, fold_cons_left, ← ha.assoc, hi.idempotent],
end
end fold
theorem le_smul_erase_dup [decidable_eq α] (s : multiset α) :
∃ n : ℕ, s ≤ n • erase_dup s :=
⟨(s.map (λ a, count a s)).fold max 0, le_iff_count.2 $ λ a, begin
rw count_smul, by_cases a ∈ s,
{ refine le_trans _ (mul_le_mul_left _ $ count_pos.2 $ mem_erase_dup.2 h),
have : count a s ≤ fold max 0 (map (λ a, count a s) (a :: erase s a));
[simp [le_max_left], simpa [cons_erase h]] },
{ simp [count_eq_zero.2 h, nat.zero_le] }
end⟩
section sup
variables [semilattice_sup_bot α]
/-- Supremum of a multiset: `sup {a, b, c} = a ⊔ b ⊔ c` -/
def sup (s : multiset α) : α := s.fold (⊔) ⊥
@[simp] lemma sup_zero : (0 : multiset α).sup = ⊥ :=
fold_zero _ _
@[simp] lemma sup_cons (a : α) (s : multiset α) :
(a :: s).sup = a ⊔ s.sup :=
fold_cons_left _ _ _ _
@[simp] lemma sup_singleton {a : α} : (a::0).sup = a := by simp
@[simp] lemma sup_add (s₁ s₂ : multiset α) : (s₁ + s₂).sup = s₁.sup ⊔ s₂.sup :=
eq.trans (by simp [sup]) (fold_add _ _ _ _ _)
lemma sup_le {s : multiset α} {a : α} : s.sup ≤ a ↔ (∀b ∈ s, b ≤ a) :=
multiset.induction_on s (by simp)
(by simp [or_imp_distrib, forall_and_distrib] {contextual := tt})
lemma le_sup {s : multiset α} {a : α} (h : a ∈ s) : a ≤ s.sup :=
sup_le.1 (le_refl _) _ h
lemma sup_mono {s₁ s₂ : multiset α} (h : s₁ ⊆ s₂) : s₁.sup ≤ s₂.sup :=
sup_le.2 $ assume b hb, le_sup (h hb)
variables [decidable_eq α]
@[simp] lemma sup_erase_dup (s : multiset α) : (erase_dup s).sup = s.sup :=
fold_erase_dup_idem _ _ _
@[simp] lemma sup_ndunion (s₁ s₂ : multiset α) :
(ndunion s₁ s₂).sup = s₁.sup ⊔ s₂.sup :=
by rw [← sup_erase_dup, erase_dup_ext.2, sup_erase_dup, sup_add]; simp
@[simp] lemma sup_union (s₁ s₂ : multiset α) :
(s₁ ∪ s₂).sup = s₁.sup ⊔ s₂.sup :=
by rw [← sup_erase_dup, erase_dup_ext.2, sup_erase_dup, sup_add]; simp
@[simp] lemma sup_ndinsert (a : α) (s : multiset α) :
(ndinsert a s).sup = a ⊔ s.sup :=
by rw [← sup_erase_dup, erase_dup_ext.2, sup_erase_dup, sup_cons]; simp
end sup
section inf
variables [semilattice_inf_top α]
/-- Infimum of a multiset: `inf {a, b, c} = a ⊓ b ⊓ c` -/
def inf (s : multiset α) : α := s.fold (⊓) ⊤
@[simp] lemma inf_zero : (0 : multiset α).inf = ⊤ :=
fold_zero _ _
@[simp] lemma inf_cons (a : α) (s : multiset α) :
(a :: s).inf = a ⊓ s.inf :=
fold_cons_left _ _ _ _
@[simp] lemma inf_singleton {a : α} : (a::0).inf = a := by simp
@[simp] lemma inf_add (s₁ s₂ : multiset α) : (s₁ + s₂).inf = s₁.inf ⊓ s₂.inf :=
eq.trans (by simp [inf]) (fold_add _ _ _ _ _)
lemma le_inf {s : multiset α} {a : α} : a ≤ s.inf ↔ (∀b ∈ s, a ≤ b) :=
multiset.induction_on s (by simp)
(by simp [or_imp_distrib, forall_and_distrib] {contextual := tt})
lemma inf_le {s : multiset α} {a : α} (h : a ∈ s) : s.inf ≤ a :=
le_inf.1 (le_refl _) _ h
lemma inf_mono {s₁ s₂ : multiset α} (h : s₁ ⊆ s₂) : s₂.inf ≤ s₁.inf :=
le_inf.2 $ assume b hb, inf_le (h hb)
variables [decidable_eq α]
@[simp] lemma inf_erase_dup (s : multiset α) : (erase_dup s).inf = s.inf :=
fold_erase_dup_idem _ _ _
@[simp] lemma inf_ndunion (s₁ s₂ : multiset α) :
(ndunion s₁ s₂).inf = s₁.inf ⊓ s₂.inf :=
by rw [← inf_erase_dup, erase_dup_ext.2, inf_erase_dup, inf_add]; simp
@[simp] lemma inf_union (s₁ s₂ : multiset α) :
(s₁ ∪ s₂).inf = s₁.inf ⊓ s₂.inf :=
by rw [← inf_erase_dup, erase_dup_ext.2, inf_erase_dup, inf_add]; simp
@[simp] lemma inf_ndinsert (a : α) (s : multiset α) :
(ndinsert a s).inf = a ⊓ s.inf :=
by rw [← inf_erase_dup, erase_dup_ext.2, inf_erase_dup, inf_cons]; simp
end inf
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 multiset `s`.
(Uses merge sort algorithm.) -/
def sort (s : multiset α) : list α :=
quot.lift_on s (merge_sort r) $ λ a b h,
eq_of_sorted_of_perm
((perm_merge_sort _ _).trans $ h.trans (perm_merge_sort _ _).symm)
(sorted_merge_sort r _)
(sorted_merge_sort r _)
@[simp] theorem coe_sort (l : list α) : sort r l = merge_sort r l := rfl
@[simp] theorem sort_sorted (s : multiset α) : sorted r (sort r s) :=
quot.induction_on s $ λ l, sorted_merge_sort r _
@[simp] theorem sort_eq (s : multiset α) : ↑(sort r s) = s :=
quot.induction_on s $ λ l, quot.sound $ perm_merge_sort _ _
@[simp] theorem mem_sort {s : multiset α} {a : α} : a ∈ sort r s ↔ a ∈ s :=
by rw [← mem_coe, sort_eq]
@[simp] theorem length_sort {s : multiset α} : (sort r s).length = s.card :=
quot.induction_on s $ length_merge_sort _
end sort
instance [has_repr α] : has_repr (multiset α) :=
⟨λ s, "{" ++ string.intercalate ", " ((s.map repr).sort (≤)) ++ "}"⟩
section sections
def sections (s : multiset (multiset α)) : multiset (multiset α) :=
multiset.rec_on s {0} (λs _ c, s.bind $ λa, c.map ((::) a))
(assume a₀ a₁ s pi, by simp [map_bind, bind_bind a₀ a₁, cons_swap])
@[simp] lemma sections_zero : sections (0 : multiset (multiset α)) = 0::0 :=
rfl
@[simp] lemma sections_cons (s : multiset (multiset α)) (m : multiset α) :
sections (m :: s) = m.bind (λa, (sections s).map ((::) a)) :=
rec_on_cons m s
lemma coe_sections : ∀(l : list (list α)),
sections ((l.map (λl:list α, (l : multiset α))) : multiset (multiset α)) =
((l.sections.map (λl:list α, (l : multiset α))) : multiset (multiset α))
| [] := rfl
| (a :: l) :=
begin
simp,
rw [← cons_coe, sections_cons, bind_map_comm, coe_sections l],
simp [list.sections, (∘), list.bind]
end
@[simp] lemma sections_add (s t : multiset (multiset α)) :
sections (s + t) = (sections s).bind (λm, (sections t).map ((+) m)) :=
multiset.induction_on s (by simp)
(assume a s ih, by simp [ih, bind_assoc, map_bind, bind_map, -add_comm])
lemma mem_sections {s : multiset (multiset α)} :
∀{a}, a ∈ sections s ↔ s.rel (λs a, a ∈ s) a :=
multiset.induction_on s (by simp)
(assume a s ih a',
by simp [ih, rel_cons_left, -exists_and_distrib_left, exists_and_distrib_left.symm, eq_comm])
lemma card_sections {s : multiset (multiset α)} : card (sections s) = prod (s.map card) :=
multiset.induction_on s (by simp) (by simp {contextual := tt})
lemma prod_map_sum [comm_semiring α] {s : multiset (multiset α)} :
prod (s.map sum) = sum ((sections s).map prod) :=
multiset.induction_on s (by simp)
(assume a s ih, by simp [ih, map_bind, sum_map_mul_left, sum_map_mul_right])
end sections
section pi
variables [decidable_eq α] {δ : α → Type*}
open function
def pi.cons (m : multiset α) (a : α) (b : δ a) (f : Πa∈m, δ a) : Πa'∈a::m, δ a' :=
λa' ha', if h : a' = a then eq.rec b h.symm else f a' $ (mem_cons.1 ha').resolve_left h
def pi.empty (δ : α → Type*) : (Πa∈(0:multiset α), δ a) .
lemma pi.cons_same {m : multiset α} {a : α} {b : δ a} {f : Πa∈m, δ a} (h : a ∈ a :: m) :
pi.cons m a b f a h = b :=
dif_pos rfl
lemma pi.cons_ne {m : multiset α} {a a' : α} {b : δ a} {f : Πa∈m, δ a} (h' : a' ∈ a :: m) (h : a' ≠ a) :
pi.cons m a b f a' h' = f a' ((mem_cons.1 h').resolve_left h) :=
dif_neg h
lemma pi.cons_swap {a a' : α} {b : δ a} {b' : δ a'} {m : multiset α} {f : Πa∈m, δ a} (h : a ≠ a') :
pi.cons (a' :: m) a b (pi.cons m a' b' f) == pi.cons (a :: m) a' b' (pi.cons m a b f) :=
begin
apply hfunext, { refl }, intros a'' _ h, subst h,
apply hfunext, { rw [cons_swap] }, intros ha₁ ha₂ h,
by_cases h₁ : a'' = a; by_cases h₂ : a'' = a';
simp [*, pi.cons_same, pi.cons_ne] at *,
{ subst h₁, rw [pi.cons_same, pi.cons_same] },
{ subst h₂, rw [pi.cons_same, pi.cons_same] }
end
/-- `pi m t` constructs the Cartesian product over `t` indexed by `m`. -/
def pi (m : multiset α) (t : Πa, multiset (δ a)) : multiset (Πa∈m, δ a) :=
m.rec_on {pi.empty δ} (λa m (p : multiset (Πa∈m, δ a)), (t a).bind $ λb, p.map $ pi.cons m a b)
begin
intros a a' m n,
by_cases eq : a = a',
{ subst eq },
{ simp [map_bind, bind_bind (t a') (t a)],
apply bind_hcongr, { rw [cons_swap a a'] },
intros b hb,
apply bind_hcongr, { rw [cons_swap a a'] },
intros b' hb',
apply map_hcongr, { rw [cons_swap a a'] },
intros f hf,
exact pi.cons_swap eq }
end
@[simp] lemma pi_zero (t : Πa, multiset (δ a)) : pi 0 t = pi.empty δ :: 0 := rfl
@[simp] lemma pi_cons (m : multiset α) (t : Πa, multiset (δ a)) (a : α) :
pi (a :: m) t = ((t a).bind $ λb, (pi m t).map $ pi.cons m a b) :=
rec_on_cons a m
lemma injective_pi_cons {a : α} {b : δ a} {s : multiset α} (hs : a ∉ s) :
function.injective (pi.cons s a b) :=
assume f₁ f₂ eq, funext $ assume a', funext $ assume h',
have ne : a ≠ a', from assume h, hs $ h.symm ▸ h',
have a' ∈ a :: s, from mem_cons_of_mem h',
calc f₁ a' h' = pi.cons s a b f₁ a' this : by rw [pi.cons_ne this ne.symm]
... = pi.cons s a b f₂ a' this : by rw [eq]
... = f₂ a' h' : by rw [pi.cons_ne this ne.symm]
lemma card_pi (m : multiset α) (t : Πa, multiset (δ a)) :
card (pi m t) = prod (m.map $ λa, card (t a)) :=
multiset.induction_on m (by simp) (by simp [mul_comm] {contextual := tt})
lemma nodup_pi {s : multiset α} {t : Πa, multiset (δ a)} :
nodup s → (∀a∈s, nodup (t a)) → nodup (pi s t) :=
multiset.induction_on s (assume _ _, nodup_singleton _)
begin
assume a s ih hs ht,
have has : a ∉ s, by simp at hs; exact hs.1,
have hs : nodup s, by simp at hs; exact hs.2,
simp,
split,
{ assume b hb,
from nodup_map (injective_pi_cons has) (ih hs $ assume a' h', ht a' $ mem_cons_of_mem h') },
{ apply pairwise_of_nodup _ (ht a $ mem_cons_self _ _),
from assume b₁ hb₁ b₂ hb₂ neb, disjoint_map_map.2 (assume f hf g hg eq,
have pi.cons s a b₁ f a (mem_cons_self _ _) = pi.cons s a b₂ g a (mem_cons_self _ _),
by rw [eq],
neb $ show b₁ = b₂, by rwa [pi.cons_same, pi.cons_same] at this) }
end
lemma mem_pi (m : multiset α) (t : Πa, multiset (δ a)) :
∀f:Πa∈m, δ a, (f ∈ pi m t) ↔ (∀a (h : a ∈ m), f a h ∈ t a) :=
begin
refine multiset.induction_on m (λ f, _) (λ a m ih f, _),
{ simpa using show f = pi.empty δ, by funext a ha; exact ha.elim },
simp, split,
{ rintro ⟨b, hb, f', hf', rfl⟩ a' ha',
rw [ih] at hf',
by_cases a' = a,
{ subst h, rwa [pi.cons_same] },
{ rw [pi.cons_ne _ h], apply hf' } },
{ intro hf,
refine ⟨_, hf a (mem_cons_self a _), λa ha, f a (mem_cons_of_mem ha),
(ih _).2 (λ a' h', hf _ _), _⟩,
funext a' h',
by_cases a' = a,
{ subst h, rw [pi.cons_same] },
{ rw [pi.cons_ne _ h] } }
end
end pi
end multiset
namespace multiset
instance : functor multiset :=
{ map := @map }
instance : is_lawful_functor multiset :=
by refine { .. }; intros; simp
open is_lawful_traversable is_comm_applicative
variables {F : Type u_1 → Type u_1} [applicative F] [is_comm_applicative F]
variables {α' β' : Type u_1} (f : α' → F β')
def traverse : multiset α' → F (multiset β') :=
quotient.lift (functor.map coe ∘ traversable.traverse f)
begin
introv p, unfold function.comp,
induction p,
case perm.nil { refl },
case perm.skip {
have : multiset.cons <$> f p_x <*> (coe <$> traverse f p_l₁) =
multiset.cons <$> f p_x <*> (coe <$> traverse f p_l₂),
{ rw [p_ih] },
simpa with functor_norm },
case perm.swap {
have : (λa b (l:list β'), (↑(a :: b :: l) : multiset β')) <$> f p_y <*> f p_x =
(λa b l, ↑(a :: b :: l)) <$> f p_x <*> f p_y,
{ rw [is_comm_applicative.commutative_map],
congr, funext a b l, simpa [flip] using perm.swap b a l },
simp [(∘), this] with functor_norm },
case perm.trans { simp [*] }
end
instance : monad multiset :=
{ pure := λ α x, x::0,
bind := @bind,
.. multiset.functor }
instance : is_lawful_monad multiset :=
{ bind_pure_comp_eq_map := λ α β f s, multiset.induction_on s rfl $ λ a s ih,
by rw [bind_cons, map_cons, bind_zero, add_zero],
pure_bind := λ α β x f, by simp only [cons_bind, zero_bind, add_zero],
bind_assoc := @bind_assoc }
open functor
open traversable is_lawful_traversable
@[simp]
lemma lift_beta {α β : Type*} (x : list α) (f : list α → β)
(h : ∀ a b : list α, a ≈ b → f a = f b) :
quotient.lift f h (x : multiset α) = f x :=
quotient.lift_beta _ _ _
@[simp]
lemma map_comp_coe {α β} (h : α → β) :
functor.map h ∘ coe = (coe ∘ functor.map h : list α → multiset β) :=
by funext; simp [functor.map]
lemma id_traverse {α : Type*} (x : multiset α) :
traverse id.mk x = x :=
quotient.induction_on x
(by { intro, rw [traverse,quotient.lift_beta,function.comp],
simp, congr })
lemma comp_traverse {G H : Type* → Type*}
[applicative G] [applicative H]
[is_comm_applicative G] [is_comm_applicative H]
{α β γ : Type*}
(g : α → G β) (h : β → H γ) (x : multiset α) :
traverse (comp.mk ∘ functor.map h ∘ g) x =
comp.mk (functor.map (traverse h) (traverse g x)) :=
quotient.induction_on x
(by intro;
simp [traverse,comp_traverse] with functor_norm;
simp [(<$>),(∘)] with functor_norm)
lemma map_traverse {G : Type* → Type*}
[applicative G] [is_comm_applicative G]
{α β γ : Type*}
(g : α → G β) (h : β → γ)
(x : multiset α) :
functor.map (functor.map h) (traverse g x) =
traverse (functor.map h ∘ g) x :=
quotient.induction_on x
(by intro; simp [traverse] with functor_norm;
rw [comp_map,map_traverse])
lemma traverse_map {G : Type* → Type*}
[applicative G] [is_comm_applicative G]
{α β γ : Type*}
(g : α → β) (h : β → G γ)
(x : multiset α) :
traverse h (map g x) =
traverse (h ∘ g) x :=
quotient.induction_on x
(by intro; simp [traverse];
rw [← traversable.traverse_map h g];
[ refl, apply_instance ])
lemma naturality {G H : Type* → Type*}
[applicative G] [applicative H]
[is_comm_applicative G] [is_comm_applicative H]
(eta : applicative_transformation G H)
{α β : Type*} (f : α → G β) (x : multiset α) :
eta (traverse f x) = traverse (@eta _ ∘ f) x :=
quotient.induction_on x
(by intro; simp [traverse,is_lawful_traversable.naturality] with functor_norm)
section choose
variables (p : α → Prop) [decidable_pred p] (l : multiset α)
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
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
/- Ico -/
/-- `Ico n m` is the multiset lifted from the list `Ico n m`, e.g. the set `{n, n+1, ..., m-1}`. -/
def Ico (n m : ℕ) : multiset ℕ := Ico n m
namespace Ico
theorem map_add (n m k : ℕ) : (Ico n m).map ((+) k) = Ico (n + k) (m + k) :=
congr_arg coe $ list.Ico.map_add _ _ _
theorem map_sub (n m k : ℕ) (h : k ≤ n) : (Ico n m).map (λ x, x - k) = Ico (n - k) (m - k) :=
congr_arg coe $ list.Ico.map_sub _ _ _ h
theorem zero_bot (n : ℕ) : Ico 0 n = range n :=
congr_arg coe $ list.Ico.zero_bot _
@[simp] theorem card (n m : ℕ) : (Ico n m).card = m - n :=
list.Ico.length _ _
theorem nodup (n m : ℕ) : nodup (Ico n m) := Ico.nodup _ _
@[simp] theorem mem {n m l : ℕ} : l ∈ Ico n m ↔ n ≤ l ∧ l < m :=
list.Ico.mem
theorem eq_zero_of_le {n m : ℕ} (h : m ≤ n) : Ico n m = 0 :=
congr_arg coe $ list.Ico.eq_nil_of_le h
@[simp] theorem self_eq_zero {n : ℕ} : Ico n n = 0 :=
eq_zero_of_le $ le_refl n
@[simp] theorem eq_zero_iff {n m : ℕ} : Ico n m = 0 ↔ m ≤ n :=
iff.trans (coe_eq_zero _) list.Ico.eq_empty_iff
lemma add_consecutive {n m l : ℕ} (hnm : n ≤ m) (hml : m ≤ l) :
Ico n m + Ico m l = Ico n l :=
congr_arg coe $ list.Ico.append_consecutive hnm hml
@[simp] lemma inter_consecutive (n m l : ℕ) : Ico n m ∩ Ico m l = 0 :=
congr_arg coe $ list.Ico.bag_inter_consecutive n m l
@[simp] theorem succ_singleton {n : ℕ} : Ico n (n+1) = {n} :=
congr_arg coe $ list.Ico.succ_singleton
theorem succ_top {n m : ℕ} (h : n ≤ m) : Ico n (m + 1) = m :: Ico n m :=
by rw [Ico, list.Ico.succ_top h, ← coe_add, add_comm]; refl
theorem eq_cons {n m : ℕ} (h : n < m) : Ico n m = n :: Ico (n + 1) m :=
congr_arg coe $ list.Ico.eq_cons h
@[simp] theorem pred_singleton {m : ℕ} (h : 0 < m) : Ico (m - 1) m = {m - 1} :=
congr_arg coe $ list.Ico.pred_singleton h
@[simp] theorem not_mem_top {n m : ℕ} : m ∉ Ico n m :=
list.Ico.not_mem_top
lemma filter_lt_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, x < l) = Ico n m :=
congr_arg coe $ list.Ico.filter_lt_of_top_le hml
lemma filter_lt_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, x < l) = ∅ :=
congr_arg coe $ list.Ico.filter_lt_of_le_bot hln
lemma filter_lt_of_ge {n m l : ℕ} (hlm : l ≤ m) : (Ico n m).filter (λ x, x < l) = Ico n l :=
congr_arg coe $ list.Ico.filter_lt_of_ge hlm
@[simp] lemma filter_lt (n m l : ℕ) : (Ico n m).filter (λ x, x < l) = Ico n (min m l) :=
congr_arg coe $ list.Ico.filter_lt n m l
lemma filter_le_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, l ≤ x) = Ico n m :=
congr_arg coe $ list.Ico.filter_le_of_le_bot hln
lemma filter_le_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, l ≤ x) = ∅ :=
congr_arg coe $ list.Ico.filter_le_of_top_le hml
lemma filter_le_of_le {n m l : ℕ} (hnl : n ≤ l) : (Ico n m).filter (λ x, l ≤ x) = Ico l m :=
congr_arg coe $ list.Ico.filter_le_of_le hnl
@[simp] lemma filter_le (n m l : ℕ) : (Ico n m).filter (λ x, l ≤ x) = Ico (max n l) m :=
congr_arg coe $ list.Ico.filter_le n m l
end Ico
variable (α)
def subsingleton_equiv [subsingleton α] : list α ≃ multiset α :=
{ to_fun := coe,
inv_fun := quot.lift id $ λ (a b : list α) (h : a ~ b),
list.ext_le (perm_length h) $ λ n h₁ h₂, subsingleton.elim _ _,
left_inv := λ l, rfl,
right_inv := λ m, quot.induction_on m $ λ l, rfl }
namespace nat
/-- The antidiagonal of a natural number `n` is
the multiset of pairs `(i,j)` such that `i+j = n`. -/
def antidiagonal (n : ℕ) : multiset (ℕ × ℕ) :=
list.nat.antidiagonal n
/-- A pair (i,j) is contained in the antidiagonal of `n` if and only if `i+j=n`. -/
@[simp] lemma mem_antidiagonal {n : ℕ} {x : ℕ × ℕ} :
x ∈ antidiagonal n ↔ x.1 + x.2 = n :=
by rw [antidiagonal, mem_coe, list.nat.mem_antidiagonal]
/-- The cardinality of the antidiagonal of `n` is `n+1`. -/
@[simp] lemma card_antidiagonal (n : ℕ) : (antidiagonal n).card = n+1 :=
by rw [antidiagonal, coe_card, list.nat.length_antidiagonal]
/-- The antidiagonal of `0` is the list `[(0,0)]` -/
@[simp] lemma antidiagonal_zero : antidiagonal 0 = {(0, 0)} :=
by { rw [antidiagonal, list.nat.antidiagonal_zero], refl }
/-- The antidiagonal of `n` does not contain duplicate entries. -/
@[simp] lemma nodup_antidiagonal (n : ℕ) : nodup (antidiagonal n) :=
coe_nodup.2 $ list.nat.nodup_antidiagonal n
end nat
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
|
c3b1c01f3f6b6300798751d3a5d8706b2030127e | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/Lean3Lib/init/meta/type_context.lean | 50fb9d174aa4259e1959b6c156152f3df82e843f | [] | 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 | 631 | lean | import Mathlib.PrePort
import Mathlib.Lean3Lib.init.control.monad
import Mathlib.Lean3Lib.init.meta.local_context
import Mathlib.Lean3Lib.init.meta.tactic
import Mathlib.Lean3Lib.init.meta.fun_info
namespace Mathlib
namespace tactic.unsafe
/-- A monad that exposes the functionality of the C++ class `type_context_old`.
The idea is that the methods to `type_context` are more powerful but _unsafe_ in the
sense that you can create terms that do not typecheck or that are infinitely descending.
Under the hood, `type_context` is implemented as a reader monad, with a mutable `type_context` object.
-/
namespace type_context
|
dd913654098bd5fee9f1a5c74e282ddb6760edf2 | b074a51e20fdb737b2d4c635dd292fc54685e010 | /src/algebra/module.lean | 21e55db2c8b1b50e258843134edb6d68e487c9de | [
"Apache-2.0"
] | permissive | minchaowu/mathlib | 2daf6ffdb5a56eeca403e894af88bcaaf65aec5e | 879da1cf04c2baa9eaa7bd2472100bc0335e5c73 | refs/heads/master | 1,609,628,676,768 | 1,564,310,105,000 | 1,564,310,105,000 | 99,461,307 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 14,904 | lean | /-
Copyright (c) 2015 Nathaniel Thomas. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Nathaniel Thomas, Jeremy Avigad, Johannes Hölzl, Mario Carneiro
Modules over a ring.
-/
import algebra.ring algebra.big_operators group_theory.subgroup group_theory.group_action
open function
universes u v w x
variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x}
-- /-- Typeclass for types with a scalar multiplication operation, denoted `•` (`\bu`) -/
-- class has_scalar (α : Type u) (γ : Type v) := (smul : α → γ → γ)
-- infixr ` • `:73 := has_scalar.smul
/-- A semimodule is a generalization of vector spaces to a scalar semiring.
It consists of a scalar semiring `α` and an additive monoid of "vectors" `β`,
connected by a "scalar multiplication" operation `r • x : β`
(where `r : α` and `x : β`) with some natural associativity and
distributivity axioms similar to those on a ring. -/
class semimodule (α : Type u) (β : Type v) [semiring α]
[add_comm_monoid β] extends distrib_mul_action α β :=
(add_smul : ∀(r s : α) (x : β), (r + s) • x = r • x + s • x)
(zero_smul : ∀x : β, (0 : α) • x = 0)
section semimodule
variables [R:semiring α] [add_comm_monoid β] [semimodule α β] (r s : α) (x y : β)
include R
theorem add_smul : (r + s) • x = r • x + s • x := semimodule.add_smul r s x
variables (α)
@[simp] theorem zero_smul : (0 : α) • x = 0 := semimodule.zero_smul α x
lemma smul_smul : r • s • x = (r * s) • x := (mul_smul _ _ _).symm
instance smul.is_add_monoid_hom {r : α} : is_add_monoid_hom (λ x : β, r • x) :=
{ map_add := smul_add _, map_zero := smul_zero _ }
lemma semimodule.eq_zero_of_zero_eq_one (zero_eq_one : (0 : α) = 1) : x = 0 :=
by rw [←one_smul α x, ←zero_eq_one, zero_smul]
end semimodule
/-- A module is a generalization of vector spaces to a scalar ring.
It consists of a scalar ring `α` and an additive group of "vectors" `β`,
connected by a "scalar multiplication" operation `r • x : β`
(where `r : α` and `x : β`) with some natural associativity and
distributivity axioms similar to those on a ring. -/
class module (α : Type u) (β : Type v) [ring α] [add_comm_group β] extends semimodule α β
structure module.core (α β) [ring α] [add_comm_group β] extends has_scalar α β :=
(smul_add : ∀(r : α) (x y : β), r • (x + y) = r • x + r • y)
(add_smul : ∀(r s : α) (x : β), (r + s) • x = r • x + s • x)
(mul_smul : ∀(r s : α) (x : β), (r * s) • x = r • s • x)
(one_smul : ∀x : β, (1 : α) • x = x)
def module.of_core {α β} [ring α] [add_comm_group β] (M : module.core α β) : module α β :=
by letI := M.to_has_scalar; exact
{ zero_smul := λ x,
have (0 : α) • x + (0 : α) • x = (0 : α) • x + 0, by rw ← M.add_smul; simp,
add_left_cancel this,
smul_zero := λ r,
have r • (0:β) + r • 0 = r • 0 + 0, by rw ← M.smul_add; simp,
add_left_cancel this,
..M }
section module
variables [ring α] [add_comm_group β] [module α β] (r s : α) (x y : β)
@[simp] theorem neg_smul : -r • x = - (r • x) :=
eq_neg_of_add_eq_zero (by rw [← add_smul, add_left_neg, zero_smul])
variables (α)
theorem neg_one_smul (x : β) : (-1 : α) • x = -x := by simp
variables {α}
@[simp] theorem smul_neg : r • (-x) = -(r • x) :=
by rw [← neg_one_smul α, ← mul_smul, mul_neg_one, neg_smul]
theorem smul_sub (r : α) (x y : β) : r • (x - y) = r • x - r • y :=
by simp [smul_add]; rw smul_neg
theorem sub_smul (r s : α) (y : β) : (r - s) • y = r • y - s • y :=
by simp [add_smul]
end module
instance semiring.to_semimodule [r : semiring α] : semimodule α α :=
{ smul := (*),
smul_add := mul_add,
add_smul := add_mul,
mul_smul := mul_assoc,
one_smul := one_mul,
zero_smul := zero_mul,
smul_zero := mul_zero, ..r }
@[simp] lemma smul_eq_mul [semiring α] {a a' : α} : a • a' = a * a' := rfl
instance ring.to_module [r : ring α] : module α α :=
{ ..semiring.to_semimodule }
def is_ring_hom.to_module [ring α] [ring β] (f : α → β) [h : is_ring_hom f] : module α β :=
module.of_core
{ smul := λ r x, f r * x,
smul_add := λ r x y, by unfold has_scalar.smul; rw [mul_add],
add_smul := λ r s x, by unfold has_scalar.smul; rw [h.map_add, add_mul],
mul_smul := λ r s x, by unfold has_scalar.smul; rw [h.map_mul, mul_assoc],
one_smul := λ x, show f 1 * x = _, by rw [h.map_one, one_mul] }
class is_linear_map (α : Type u) {β : Type v} {γ : Type w}
[ring α] [add_comm_group β] [add_comm_group γ] [module α β] [module α γ]
(f : β → γ) : Prop :=
(add : ∀x y, f (x + y) = f x + f y)
(smul : ∀(c : α) x, f (c • x) = c • f x)
structure linear_map (α : Type u) (β : Type v) (γ : Type w)
[ring α] [add_comm_group β] [add_comm_group γ] [module α β] [module α γ] :=
(to_fun : β → γ)
(add : ∀x y, to_fun (x + y) = to_fun x + to_fun y)
(smul : ∀(c : α) x, to_fun (c • x) = c • to_fun x)
infixr ` →ₗ `:25 := linear_map _
notation β ` →ₗ[`:25 α:25 `] `:0 γ:0 := linear_map α β γ
namespace linear_map
variables [ring α] [add_comm_group β] [add_comm_group γ] [add_comm_group δ]
variables [module α β] [module α γ] [module α δ]
variables (f g : β →ₗ[α] γ)
include α
instance : has_coe_to_fun (β →ₗ[α] γ) := ⟨_, to_fun⟩
theorem is_linear : is_linear_map α f := {..f}
@[extensionality] theorem ext {f g : β →ₗ[α] γ} (H : ∀ x, f x = g x) : f = g :=
by cases f; cases g; congr'; exact funext H
theorem ext_iff {f g : β →ₗ[α] γ} : f = g ↔ ∀ x, f x = g x :=
⟨by rintro rfl; simp, ext⟩
@[simp] lemma map_add (x y : β) : f (x + y) = f x + f y := f.add x y
@[simp] lemma map_smul (c : α) (x : β) : f (c • x) = c • f x := f.smul c x
@[simp] lemma map_zero : f 0 = 0 :=
by rw [← zero_smul α, map_smul f 0 0, zero_smul]
instance : is_add_group_hom f := { map_add := map_add f }
@[simp] lemma map_neg (x : β) : f (- x) = - f x :=
by rw [← neg_one_smul α, map_smul, neg_one_smul]
@[simp] lemma map_sub (x y : β) : f (x - y) = f x - f y :=
by simp [map_neg, map_add]
@[simp] lemma map_sum {ι} {t : finset ι} {g : ι → β} :
f (t.sum g) = t.sum (λi, f (g i)) :=
(finset.sum_hom f).symm
def comp (f : γ →ₗ[α] δ) (g : β →ₗ[α] γ) : β →ₗ[α] δ := ⟨f ∘ g, by simp, by simp⟩
@[simp] lemma comp_apply (f : γ →ₗ[α] δ) (g : β →ₗ[α] γ) (x : β) : f.comp g x = f (g x) := rfl
def id : β →ₗ[α] β := ⟨id, by simp, by simp⟩
@[simp] lemma id_apply (x : β) : @id α β _ _ _ x = x := rfl
end linear_map
namespace is_linear_map
variables [ring α] [add_comm_group β] [add_comm_group γ]
variables [module α β] [module α γ]
include α
def mk' (f : β → γ) (H : is_linear_map α f) : β →ₗ γ := {to_fun := f, ..H}
@[simp] theorem mk'_apply {f : β → γ} (H : is_linear_map α f) (x : β) :
mk' f H x = f x := rfl
lemma is_linear_map_neg :
is_linear_map α (λ (z : β), -z) :=
is_linear_map.mk neg_add (λ x y, (smul_neg x y).symm)
lemma is_linear_map_smul {α R : Type*} [add_comm_group α] [comm_ring R] [module R α] (c : R) :
is_linear_map R (λ (z : α), c • z) :=
begin
refine is_linear_map.mk (smul_add c) _,
intros _ _,
simp [smul_smul],
ac_refl
end
--TODO: move
lemma is_linear_map_smul' {α R : Type*} [add_comm_group α] [comm_ring R] [module R α] (a : α) :
is_linear_map R (λ (c : R), c • a) :=
begin
refine is_linear_map.mk (λ x y, add_smul x y a) _,
intros _ _,
simp [smul_smul]
end
variables {f : β → γ} (lin : is_linear_map α f)
include β γ lin
@[simp] lemma map_zero : f (0 : β) = (0 : γ) :=
by rw [← zero_smul α (0 : β), lin.smul, zero_smul]
@[simp] lemma map_add (x y : β) : f (x + y) = f x + f y :=
by rw [lin.add]
@[simp] lemma map_neg (x : β) : f (- x) = - f x :=
by rw [← neg_one_smul α, lin.smul, neg_one_smul]
@[simp] lemma map_sub (x y : β) : f (x - y) = f x - f y :=
by simp [lin.map_neg, lin.map_add]
end is_linear_map
/-- A submodule of a module is one which is closed under vector operations.
This is a sufficient condition for the subset of vectors in the submodule
to themselves form a module. -/
structure submodule (α : Type u) (β : Type v) [ring α]
[add_comm_group β] [module α β] : Type v :=
(carrier : set β)
(zero : (0:β) ∈ carrier)
(add : ∀ {x y}, x ∈ carrier → y ∈ carrier → x + y ∈ carrier)
(smul : ∀ (c:α) {x}, x ∈ carrier → c • x ∈ carrier)
namespace submodule
variables [ring α] [add_comm_group β] [add_comm_group γ]
variables [module α β] [module α γ]
variables (p p' : submodule α β)
variables {r : α} {x y : β}
instance : has_coe (submodule α β) (set β) := ⟨submodule.carrier⟩
instance : has_mem β (submodule α β) := ⟨λ x p, x ∈ (p : set β)⟩
@[simp] theorem mem_coe : x ∈ (p : set β) ↔ x ∈ p := iff.rfl
theorem ext' {s t : submodule α β} (h : (s : set β) = t) : s = t :=
by cases s; cases t; congr'
protected theorem ext'_iff {s t : submodule α β} : (s : set β) = t ↔ s = t :=
⟨ext', λ h, h ▸ rfl⟩
@[extensionality] theorem ext {s t : submodule α β}
(h : ∀ x, x ∈ s ↔ x ∈ t) : s = t := ext' $ set.ext h
@[simp] lemma zero_mem : (0 : β) ∈ p := p.zero
lemma add_mem (h₁ : x ∈ p) (h₂ : y ∈ p) : x + y ∈ p := p.add h₁ h₂
lemma smul_mem (r : α) (h : x ∈ p) : r • x ∈ p := p.smul r h
lemma neg_mem (hx : x ∈ p) : -x ∈ p := by rw ← neg_one_smul α; exact p.smul_mem _ hx
lemma sub_mem (hx : x ∈ p) (hy : y ∈ p) : x - y ∈ p := p.add_mem hx (p.neg_mem hy)
lemma neg_mem_iff : -x ∈ p ↔ x ∈ p :=
⟨λ h, by simpa using neg_mem p h, neg_mem p⟩
lemma add_mem_iff_left (h₁ : y ∈ p) : x + y ∈ p ↔ x ∈ p :=
⟨λ h₂, by simpa using sub_mem _ h₂ h₁, λ h₂, add_mem _ h₂ h₁⟩
lemma add_mem_iff_right (h₁ : x ∈ p) : x + y ∈ p ↔ y ∈ p :=
⟨λ h₂, by simpa using sub_mem _ h₂ h₁, add_mem _ h₁⟩
lemma sum_mem {ι : Type w} [decidable_eq ι] {t : finset ι} {f : ι → β} :
(∀c∈t, f c ∈ p) → t.sum f ∈ p :=
finset.induction_on t (by simp [p.zero_mem]) (by simp [p.add_mem] {contextual := tt})
instance : has_add p := ⟨λx y, ⟨x.1 + y.1, add_mem _ x.2 y.2⟩⟩
instance : has_zero p := ⟨⟨0, zero_mem _⟩⟩
instance : has_neg p := ⟨λx, ⟨-x.1, neg_mem _ x.2⟩⟩
instance : has_scalar α p := ⟨λ c x, ⟨c • x.1, smul_mem _ c x.2⟩⟩
@[simp] lemma coe_add (x y : p) : (↑(x + y) : β) = ↑x + ↑y := rfl
@[simp] lemma coe_zero : ((0 : p) : β) = 0 := rfl
@[simp] lemma coe_neg (x : p) : ((-x : p) : β) = -x := rfl
@[simp] lemma coe_smul (r : α) (x : p) : ((r • x : p) : β) = r • ↑x := rfl
instance : add_comm_group p :=
by refine {add := (+), zero := 0, neg := has_neg.neg, ..};
{ intros, apply set_coe.ext, simp }
instance submodule_is_add_subgroup : is_add_subgroup (p : set β) :=
{ zero_mem := p.zero,
add_mem := p.add,
neg_mem := λ _, p.neg_mem }
lemma coe_sub (x y : p) : (↑(x - y) : β) = ↑x - ↑y := by simp
instance : module α p :=
by refine {smul := (•), ..};
{ intros, apply set_coe.ext, simp [smul_add, add_smul, mul_smul] }
protected def subtype : p →ₗ[α] β :=
by refine {to_fun := coe, ..}; simp [coe_smul]
@[simp] theorem subtype_apply (x : p) : p.subtype x = x := rfl
lemma subtype_eq_val (p : submodule α β) :
((submodule.subtype p) : p → β) = subtype.val := rfl
end submodule
@[reducible] def ideal (α : Type u) [comm_ring α] := submodule α α
namespace ideal
variables [comm_ring α] (I : ideal α) {a b : α}
protected lemma zero_mem : (0 : α) ∈ I := I.zero_mem
protected lemma add_mem : a ∈ I → b ∈ I → a + b ∈ I := I.add_mem
lemma neg_mem_iff : -a ∈ I ↔ a ∈ I := I.neg_mem_iff
lemma add_mem_iff_left : b ∈ I → (a + b ∈ I ↔ a ∈ I) := I.add_mem_iff_left
lemma add_mem_iff_right : a ∈ I → (a + b ∈ I ↔ b ∈ I) := I.add_mem_iff_right
protected lemma sub_mem : a ∈ I → b ∈ I → a - b ∈ I := I.sub_mem
lemma mul_mem_left : b ∈ I → a * b ∈ I := I.smul_mem _
lemma mul_mem_right (h : a ∈ I) : a * b ∈ I := mul_comm b a ▸ I.mul_mem_left h
end ideal
/-- A vector space is the same as a module, except the scalar ring is actually
a field. (This adds commutativity of the multiplication and existence of inverses.)
This is the traditional generalization of spaces like `ℝ^n`, which have a natural
addition operation and a way to multiply them by real numbers, but no multiplication
operation between vectors. -/
class vector_space (α : Type u) (β : Type v) [discrete_field α] [add_comm_group β] extends module α β
instance discrete_field.to_vector_space {α : Type*} [discrete_field α] : vector_space α α :=
{ .. ring.to_module }
/-- Subspace of a vector space. Defined to equal `submodule`. -/
@[reducible] def subspace (α : Type u) (β : Type v)
[discrete_field α] [add_comm_group β] [vector_space α β] : Type v :=
submodule α β
instance subspace.vector_space {α β}
{f : discrete_field α} [add_comm_group β] [vector_space α β]
(p : subspace α β) : vector_space α p := {..submodule.module p}
namespace submodule
variables {R:discrete_field α} [add_comm_group β] [add_comm_group γ]
variables [vector_space α β] [vector_space α γ]
variables (p p' : submodule α β)
variables {r : α} {x y : β}
include R
set_option class.instance_max_depth 36
theorem smul_mem_iff (r0 : r ≠ 0) : r • x ∈ p ↔ x ∈ p :=
⟨λ h, by simpa [smul_smul, inv_mul_cancel r0] using p.smul_mem (r⁻¹) h,
p.smul_mem r⟩
end submodule
namespace add_comm_monoid
open add_monoid
variables {M : Type*} [add_comm_monoid M]
instance : semimodule ℕ M :=
{ smul := smul,
smul_add := λ _ _ _, smul_add _ _ _,
add_smul := λ _ _ _, add_smul _ _ _,
mul_smul := λ _ _ _, mul_smul _ _ _,
one_smul := one_smul,
zero_smul := zero_smul,
smul_zero := smul_zero }
end add_comm_monoid
namespace add_comm_group
variables {M : Type*} [add_comm_group M]
instance : module ℤ M :=
{ smul := gsmul,
smul_add := λ _ _ _, gsmul_add _ _ _,
add_smul := λ _ _ _, add_gsmul _ _ _,
mul_smul := λ _ _ _, gsmul_mul _ _ _,
one_smul := one_gsmul,
zero_smul := zero_gsmul,
smul_zero := gsmul_zero }
end add_comm_group
def is_add_group_hom.to_linear_map [add_comm_group α] [add_comm_group β]
(f : α → β) [is_add_group_hom f] : α →ₗ[ℤ] β :=
{ to_fun := f,
add := is_add_hom.map_add f,
smul := λ i x, int.induction_on i (by rw [zero_smul, zero_smul, is_add_group_hom.map_zero f])
(λ i ih, by rw [add_smul, add_smul, is_add_hom.map_add f, ih, one_smul, one_smul])
(λ i ih, by rw [sub_smul, sub_smul, is_add_group_hom.map_sub f, ih, one_smul, one_smul]) }
|
e9421e05f83a73fce661b84ff04f37e372089e07 | 947fa6c38e48771ae886239b4edce6db6e18d0fb | /src/model_theory/semantics.lean | c4ed8a4946d183140ed8d257642b2d1a22fe35b9 | [
"Apache-2.0"
] | permissive | ramonfmir/mathlib | c5dc8b33155473fab97c38bd3aa6723dc289beaa | 14c52e990c17f5a00c0cc9e09847af16fabbed25 | refs/heads/master | 1,661,979,343,526 | 1,660,830,384,000 | 1,660,830,384,000 | 182,072,989 | 0 | 0 | null | 1,555,585,876,000 | 1,555,585,876,000 | null | UTF-8 | Lean | false | false | 37,098 | lean | /-
Copyright (c) 2021 Aaron Anderson, Jesse Michael Han, Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Aaron Anderson, Jesse Michael Han, Floris van Doorn
-/
import data.finset.basic
import model_theory.syntax
/-!
# Basics on First-Order Semantics
This file defines the interpretations of first-order terms, formulas, sentences, and theories
in a style inspired by the [Flypitch project](https://flypitch.github.io/).
## Main Definitions
* `first_order.language.term.realize` is defined so that `t.realize v` is the term `t` evaluated at
variables `v`.
* `first_order.language.bounded_formula.realize` is defined so that `φ.realize v xs` is the bounded
formula `φ` evaluated at tuples of variables `v` and `xs`.
* `first_order.language.formula.realize` is defined so that `φ.realize v` is the formula `φ`
evaluated at variables `v`.
* `first_order.language.sentence.realize` is defined so that `φ.realize M` is the sentence `φ`
evaluated in the structure `M`. Also denoted `M ⊨ φ`.
* `first_order.language.Theory.model` is defined so that `T.model M` is true if and only if every
sentence of `T` is realized in `M`. Also denoted `T ⊨ φ`.
## Main Results
* `first_order.language.bounded_formula.realize_to_prenex` shows that the prenex normal form of a
formula has the same realization as the original formula.
* Several results in this file show that syntactic constructions such as `relabel`, `cast_le`,
`lift_at`, `subst`, and the actions of language maps commute with realization of terms, formulas,
sentences, and theories.
## Implementation Notes
* Formulas use a modified version of de Bruijn variables. Specifically, a `L.bounded_formula α n`
is a formula with some variables indexed by a type `α`, which cannot be quantified over, and some
indexed by `fin n`, which can. For any `φ : L.bounded_formula α (n + 1)`, we define the formula
`∀' φ : L.bounded_formula α n` by universally quantifying over the variable indexed by
`n : fin (n + 1)`.
## References
For the Flypitch project:
- [J. Han, F. van Doorn, *A formal proof of the independence of the continuum hypothesis*]
[flypitch_cpp]
- [J. Han, F. van Doorn, *A formalization of forcing and the unprovability of
the continuum hypothesis*][flypitch_itp]
-/
universes u v w u' v'
namespace first_order
namespace language
variables {L : language.{u v}} {L' : language}
variables {M : Type w} {N P : Type*} [L.Structure M] [L.Structure N] [L.Structure P]
variables {α : Type u'} {β : Type v'}
open_locale first_order cardinal
open Structure cardinal fin
namespace term
/-- A term `t` with variables indexed by `α` can be evaluated by giving a value to each variable. -/
@[simp] def realize (v : α → M) :
∀ (t : L.term α), M
| (var k) := v k
| (func f ts) := fun_map f (λ i, (ts i).realize)
@[simp] lemma realize_relabel {t : L.term α} {g : α → β} {v : β → M} :
(t.relabel g).realize v = t.realize (v ∘ g) :=
begin
induction t with _ n f ts ih,
{ refl, },
{ simp [ih] }
end
@[simp] lemma realize_lift_at {n n' m : ℕ} {t : L.term (α ⊕ fin n)}
{v : α ⊕ fin (n + n') → M} :
(t.lift_at n' m).realize v = t.realize (v ∘
(sum.map id (λ i, if ↑i < m then fin.cast_add n' i else fin.add_nat n' i))) :=
realize_relabel
@[simp] lemma realize_constants {c : L.constants} {v : α → M} :
c.term.realize v = c :=
fun_map_eq_coe_constants
@[simp] lemma realize_functions_apply₁ {f : L.functions 1} {t : L.term α} {v : α → M} :
(f.apply₁ t).realize v = fun_map f ![t.realize v] :=
begin
rw [functions.apply₁, term.realize],
refine congr rfl (funext (λ i, _)),
simp only [matrix.cons_val_fin_one],
end
@[simp] lemma realize_functions_apply₂ {f : L.functions 2} {t₁ t₂ : L.term α} {v : α → M} :
(f.apply₂ t₁ t₂).realize v = fun_map f ![t₁.realize v, t₂.realize v] :=
begin
rw [functions.apply₂, term.realize],
refine congr rfl (funext (fin.cases _ _)),
{ simp only [matrix.cons_val_zero], },
{ simp only [matrix.cons_val_succ, matrix.cons_val_fin_one, forall_const] }
end
lemma realize_con {A : set M} {a : A} {v : α → M} :
(L.con a).term.realize v = a := rfl
@[simp] lemma realize_subst {t : L.term α} {tf : α → L.term β} {v : β → M} :
(t.subst tf).realize v = t.realize (λ a, (tf a).realize v) :=
begin
induction t with _ _ _ _ ih,
{ refl },
{ simp [ih] }
end
@[simp] lemma realize_restrict_var [decidable_eq α] {t : L.term α} {s : set α}
(h : ↑t.var_finset ⊆ s) {v : α → M} :
(t.restrict_var (set.inclusion h)).realize (v ∘ coe) = t.realize v :=
begin
induction t with _ _ _ _ ih,
{ refl },
{ simp_rw [var_finset, finset.coe_bUnion, set.Union_subset_iff] at h,
exact congr rfl (funext (λ i, ih i (h i (finset.mem_univ i)))) },
end
@[simp] lemma realize_restrict_var_left [decidable_eq α] {γ : Type*}
{t : L.term (α ⊕ γ)} {s : set α}
(h : ↑t.var_finset_left ⊆ s) {v : α → M} {xs : γ → M} :
(t.restrict_var_left (set.inclusion h)).realize (sum.elim (v ∘ coe) xs) =
t.realize (sum.elim v xs) :=
begin
induction t with a _ _ _ ih,
{ cases a;
refl },
{ simp_rw [var_finset_left, finset.coe_bUnion, set.Union_subset_iff] at h,
exact congr rfl (funext (λ i, ih i (h i (finset.mem_univ i)))) },
end
@[simp] lemma realize_constants_to_vars [L[[α]].Structure M]
[(Lhom_with_constants L α).is_expansion_on M]
{t : L[[α]].term β} {v : β → M} :
t.constants_to_vars.realize (sum.elim (λ a, ↑(L.con a)) v) = t.realize v :=
begin
induction t with _ n f _ ih,
{ simp },
{ cases n,
{ cases f,
{ simp [ih], },
{ simp only [realize, constants_to_vars, sum.elim_inl, fun_map_eq_coe_constants],
refl } },
{ cases f,
{ simp [ih] },
{ exact is_empty_elim f } } }
end
@[simp] lemma realize_vars_to_constants [L[[α]].Structure M]
[(Lhom_with_constants L α).is_expansion_on M]
{t : L.term (α ⊕ β)} {v : β → M} :
t.vars_to_constants.realize v = t.realize (sum.elim (λ a, ↑(L.con a)) v) :=
begin
induction t with ab n f ts ih,
{ cases ab;
simp [language.con], },
{ simp [ih], }
end
lemma realize_constants_vars_equiv_left [L[[α]].Structure M]
[(Lhom_with_constants L α).is_expansion_on M]
{n} {t : L[[α]].term (β ⊕ fin n)} {v : β → M} {xs : fin n → M} :
(constants_vars_equiv_left t).realize (sum.elim (sum.elim (λ a, ↑(L.con a)) v) xs) =
t.realize (sum.elim v xs) :=
begin
simp only [constants_vars_equiv_left, realize_relabel, equiv.coe_trans, function.comp_app,
constants_vars_equiv_apply, relabel_equiv_symm_apply],
refine trans _ (realize_constants_to_vars),
rcongr,
rcases x with (a | (b | i));
simp,
end
end term
namespace Lhom
@[simp] lemma realize_on_term [L'.Structure M] (φ : L →ᴸ L') [φ.is_expansion_on M]
(t : L.term α) (v : α → M) :
(φ.on_term t).realize v = t.realize v :=
begin
induction t with _ n f ts ih,
{ refl },
{ simp only [term.realize, Lhom.on_term, Lhom.map_on_function, ih] }
end
end Lhom
@[simp] lemma hom.realize_term (g : M →[L] N) {t : L.term α} {v : α → M} :
t.realize (g ∘ v) = g (t.realize v) :=
begin
induction t,
{ refl },
{ rw [term.realize, term.realize, g.map_fun],
refine congr rfl _,
ext x,
simp [t_ih x], },
end
@[simp] lemma embedding.realize_term {v : α → M}
(t : L.term α) (g : M ↪[L] N) :
t.realize (g ∘ v) = g (t.realize v) :=
g.to_hom.realize_term
@[simp] lemma equiv.realize_term {v : α → M}
(t : L.term α) (g : M ≃[L] N) :
t.realize (g ∘ v) = g (t.realize v) :=
g.to_hom.realize_term
variables {L} {α} {n : ℕ}
namespace bounded_formula
open term
/-- A bounded formula can be evaluated as true or false by giving values to each free variable. -/
def realize :
∀ {l} (f : L.bounded_formula α l) (v : α → M) (xs : fin l → M), Prop
| _ falsum v xs := false
| _ (bounded_formula.equal t₁ t₂) v xs := t₁.realize (sum.elim v xs) = t₂.realize (sum.elim v xs)
| _ (bounded_formula.rel R ts) v xs := rel_map R (λ i, (ts i).realize (sum.elim v xs))
| _ (bounded_formula.imp f₁ f₂) v xs := realize f₁ v xs → realize f₂ v xs
| _ (bounded_formula.all f) v xs := ∀(x : M), realize f v (snoc xs x)
variables {l : ℕ} {φ ψ : L.bounded_formula α l} {θ : L.bounded_formula α l.succ}
variables {v : α → M} {xs : fin l → M}
@[simp] lemma realize_bot :
(⊥ : L.bounded_formula α l).realize v xs ↔ false :=
iff.rfl
@[simp] lemma realize_not :
φ.not.realize v xs ↔ ¬ φ.realize v xs :=
iff.rfl
@[simp] lemma realize_bd_equal (t₁ t₂ : L.term (α ⊕ fin l)) :
(t₁.bd_equal t₂).realize v xs ↔
(t₁.realize (sum.elim v xs) = t₂.realize (sum.elim v xs)) :=
iff.rfl
@[simp] lemma realize_top :
(⊤ : L.bounded_formula α l).realize v xs ↔ true :=
by simp [has_top.top]
@[simp] lemma realize_inf : (φ ⊓ ψ).realize v xs ↔ (φ.realize v xs ∧ ψ.realize v xs) :=
by simp [has_inf.inf, realize]
@[simp] lemma realize_foldr_inf (l : list (L.bounded_formula α n))
(v : α → M) (xs : fin n → M) :
(l.foldr (⊓) ⊤).realize v xs ↔ ∀ φ ∈ l, bounded_formula.realize φ v xs :=
begin
induction l with φ l ih,
{ simp },
{ simp [ih] }
end
@[simp] lemma realize_imp : (φ.imp ψ).realize v xs ↔ (φ.realize v xs → ψ.realize v xs) :=
by simp only [realize]
@[simp] lemma realize_rel {k : ℕ} {R : L.relations k} {ts : fin k → L.term _} :
(R.bounded_formula ts).realize v xs ↔ rel_map R (λ i, (ts i).realize (sum.elim v xs)) :=
iff.rfl
@[simp] lemma realize_rel₁ {R : L.relations 1} {t : L.term _} :
(R.bounded_formula₁ t).realize v xs ↔ rel_map R ![t.realize (sum.elim v xs)] :=
begin
rw [relations.bounded_formula₁, realize_rel, iff_eq_eq],
refine congr rfl (funext (λ _, _)),
simp only [matrix.cons_val_fin_one],
end
@[simp] lemma realize_rel₂ {R : L.relations 2} {t₁ t₂ : L.term _} :
(R.bounded_formula₂ t₁ t₂).realize v xs ↔
rel_map R ![t₁.realize (sum.elim v xs), t₂.realize (sum.elim v xs)] :=
begin
rw [relations.bounded_formula₂, realize_rel, iff_eq_eq],
refine congr rfl (funext (fin.cases _ _)),
{ simp only [matrix.cons_val_zero]},
{ simp only [matrix.cons_val_succ, matrix.cons_val_fin_one, forall_const] }
end
@[simp] lemma realize_sup : (φ ⊔ ψ).realize v xs ↔ (φ.realize v xs ∨ ψ.realize v xs) :=
begin
simp only [realize, has_sup.sup, realize_not, eq_iff_iff],
tauto,
end
@[simp] lemma realize_foldr_sup (l : list (L.bounded_formula α n))
(v : α → M) (xs : fin n → M) :
(l.foldr (⊔) ⊥).realize v xs ↔ ∃ φ ∈ l, bounded_formula.realize φ v xs :=
begin
induction l with φ l ih,
{ simp },
{ simp_rw [list.foldr_cons, realize_sup, ih, exists_prop, list.mem_cons_iff,
or_and_distrib_right, exists_or_distrib, exists_eq_left] }
end
@[simp] lemma realize_all : (all θ).realize v xs ↔ ∀ (a : M), (θ.realize v (fin.snoc xs a)) :=
iff.rfl
@[simp] lemma realize_ex : θ.ex.realize v xs ↔ ∃ (a : M), (θ.realize v (fin.snoc xs a)) :=
begin
rw [bounded_formula.ex, realize_not, realize_all, not_forall],
simp_rw [realize_not, not_not],
end
@[simp] lemma realize_iff : (φ.iff ψ).realize v xs ↔ (φ.realize v xs ↔ ψ.realize v xs) :=
by simp only [bounded_formula.iff, realize_inf, realize_imp, and_imp, ← iff_def]
lemma realize_cast_le_of_eq {m n : ℕ} (h : m = n) {h' : m ≤ n} {φ : L.bounded_formula α m}
{v : α → M} {xs : fin n → M} :
(φ.cast_le h').realize v xs ↔ φ.realize v (xs ∘ fin.cast h) :=
begin
subst h,
simp only [cast_le_rfl, cast_refl, order_iso.coe_refl, function.comp.right_id],
end
lemma realize_map_term_rel_id [L'.Structure M]
{ft : ∀ n, L.term (α ⊕ fin n) → L'.term (β ⊕ fin n)}
{fr : ∀ n, L.relations n → L'.relations n}
{n} {φ : L.bounded_formula α n} {v : α → M} {v' : β → M} {xs : fin n → M}
(h1 : ∀ n (t : L.term (α ⊕ fin n)) (xs : fin n → M),
(ft n t).realize (sum.elim v' xs) = t.realize (sum.elim v xs))
(h2 : ∀ n (R : L.relations n) (x : fin n → M), rel_map (fr n R) x = rel_map R x) :
(φ.map_term_rel ft fr (λ _, id)).realize v' xs ↔ φ.realize v xs :=
begin
induction φ with _ _ _ _ _ _ _ _ _ _ _ ih1 ih2 _ _ ih,
{ refl },
{ simp [map_term_rel, realize, h1] },
{ simp [map_term_rel, realize, h1, h2] },
{ simp [map_term_rel, realize, ih1, ih2], },
{ simp only [map_term_rel, realize, ih, id.def] },
end
lemma realize_map_term_rel_add_cast_le [L'.Structure M]
{k : ℕ}
{ft : ∀ n, L.term (α ⊕ fin n) → L'.term (β ⊕ fin (k + n))}
{fr : ∀ n, L.relations n → L'.relations n}
{n} {φ : L.bounded_formula α n} (v : ∀ {n}, (fin (k + n) → M) → α → M) {v' : β → M}
(xs : fin (k + n) → M)
(h1 : ∀ n (t : L.term (α ⊕ fin n)) (xs' : fin (k + n) → M),
(ft n t).realize (sum.elim v' xs') =
t.realize (sum.elim (v xs') (xs' ∘ fin.nat_add _)))
(h2 : ∀ n (R : L.relations n) (x : fin n → M), rel_map (fr n R) x = rel_map R x)
(hv : ∀ n (xs : fin (k + n) → M) (x : M), @v (n+1) (snoc xs x : fin _ → M) = v xs):
(φ.map_term_rel ft fr (λ n, cast_le (add_assoc _ _ _).symm.le)).realize v' xs ↔
φ.realize (v xs) (xs ∘ fin.nat_add _) :=
begin
induction φ with _ _ _ _ _ _ _ _ _ _ _ ih1 ih2 _ _ ih,
{ refl },
{ simp [map_term_rel, realize, h1] },
{ simp [map_term_rel, realize, h1, h2] },
{ simp [map_term_rel, realize, ih1, ih2], },
{ simp [map_term_rel, realize, ih, hv] },
end
lemma realize_relabel {m n : ℕ}
{φ : L.bounded_formula α n} {g : α → β ⊕ fin m} {v : β → M} {xs : fin (m + n) → M} :
(φ.relabel g).realize v xs ↔
φ.realize (sum.elim v (xs ∘ fin.cast_add n) ∘ g) (xs ∘ fin.nat_add m) :=
by rw [relabel, realize_map_term_rel_add_cast_le]; intros; simp
lemma realize_lift_at {n n' m : ℕ} {φ : L.bounded_formula α n}
{v : α → M} {xs : fin (n + n') → M} (hmn : m + n' ≤ n + 1) :
(φ.lift_at n' m).realize v xs ↔ φ.realize v (xs ∘
(λ i, if ↑i < m then fin.cast_add n' i else fin.add_nat n' i)) :=
begin
rw lift_at,
induction φ with _ _ _ _ _ _ _ _ _ _ _ ih1 ih2 k _ ih3,
{ simp [realize, map_term_rel], },
{ simp [realize, map_term_rel, realize_rel, realize_lift_at, sum.elim_comp_map], },
{ simp [realize, map_term_rel, realize_rel, realize_lift_at, sum.elim_comp_map], },
{ simp only [map_term_rel, realize, ih1 hmn, ih2 hmn] },
{ have h : k + 1 + n' = k + n'+ 1,
{ rw [add_assoc, add_comm 1 n', ← add_assoc], },
simp only [map_term_rel, realize, realize_cast_le_of_eq h, ih3 (hmn.trans k.succ.le_succ)],
refine forall_congr (λ x, iff_eq_eq.mpr (congr rfl (funext (fin.last_cases _ (λ i, _))))),
{ simp only [function.comp_app, coe_last, snoc_last],
by_cases (k < m),
{ rw if_pos h,
refine (congr rfl (ext _)).trans (snoc_last _ _),
simp only [coe_cast, coe_cast_add, coe_last, self_eq_add_right],
refine le_antisymm (le_of_add_le_add_left ((hmn.trans (nat.succ_le_of_lt h)).trans _))
n'.zero_le,
rw add_zero },
{ rw if_neg h,
refine (congr rfl (ext _)).trans (snoc_last _ _),
simp } },
{ simp only [function.comp_app, fin.snoc_cast_succ],
refine (congr rfl (ext _)).trans (snoc_cast_succ _ _ _),
simp only [cast_refl, coe_cast_succ, order_iso.coe_refl, id.def],
split_ifs;
simp } }
end
lemma realize_lift_at_one {n m : ℕ} {φ : L.bounded_formula α n}
{v : α → M} {xs : fin (n + 1) → M} (hmn : m ≤ n) :
(φ.lift_at 1 m).realize v xs ↔ φ.realize v (xs ∘
(λ i, if ↑i < m then cast_succ i else i.succ)) :=
by simp_rw [realize_lift_at (add_le_add_right hmn 1), cast_succ, add_nat_one]
@[simp] lemma realize_lift_at_one_self {n : ℕ} {φ : L.bounded_formula α n}
{v : α → M} {xs : fin (n + 1) → M} :
(φ.lift_at 1 n).realize v xs ↔ φ.realize v (xs ∘ cast_succ) :=
begin
rw [realize_lift_at_one (refl n), iff_eq_eq],
refine congr rfl (congr rfl (funext (λ i, _))),
rw [if_pos i.is_lt],
end
lemma realize_subst {φ : L.bounded_formula α n} {tf : α → L.term β} {v : β → M} {xs : fin n → M} :
(φ.subst tf).realize v xs ↔ φ.realize (λ a, (tf a).realize v) xs :=
realize_map_term_rel_id (λ n t x, begin
rw term.realize_subst,
rcongr a,
{ cases a,
{ simp only [sum.elim_inl, term.realize_relabel, sum.elim_comp_inl] },
{ refl } }
end) (by simp)
@[simp] lemma realize_restrict_free_var [decidable_eq α] {n : ℕ} {φ : L.bounded_formula α n}
{s : set α} (h : ↑φ.free_var_finset ⊆ s) {v : α → M} {xs : fin n → M} :
(φ.restrict_free_var (set.inclusion h)).realize (v ∘ coe) xs ↔
φ.realize v xs :=
begin
induction φ with _ _ _ _ _ _ _ _ _ _ _ ih1 ih2 _ _ ih3,
{ refl },
{ simp [restrict_free_var, realize] },
{ simp [restrict_free_var, realize] },
{ simp [restrict_free_var, realize, ih1, ih2] },
{ simp [restrict_free_var, realize, ih3] },
end
lemma realize_constants_vars_equiv [L[[α]].Structure M]
[(Lhom_with_constants L α).is_expansion_on M]
{n} {φ : L[[α]].bounded_formula β n} {v : β → M} {xs : fin n → M} :
(constants_vars_equiv φ).realize (sum.elim (λ a, ↑(L.con a)) v) xs ↔ φ.realize v xs :=
begin
refine realize_map_term_rel_id (λ n t xs, realize_constants_vars_equiv_left) (λ n R xs, _),
rw ← (Lhom_with_constants L α).map_on_relation (equiv.sum_empty (L.relations n)
((constants_on α).relations n) R) xs,
rcongr,
cases R,
{ simp, },
{ exact is_empty_elim R }
end
variables [nonempty M]
lemma realize_all_lift_at_one_self {n : ℕ} {φ : L.bounded_formula α n}
{v : α → M} {xs : fin n → M} :
(φ.lift_at 1 n).all.realize v xs ↔ φ.realize v xs :=
begin
inhabit M,
simp only [realize_all, realize_lift_at_one_self],
refine ⟨λ h, _, λ h a, _⟩,
{ refine (congr rfl (funext (λ i, _))).mp (h default),
simp, },
{ refine (congr rfl (funext (λ i, _))).mp h,
simp }
end
lemma realize_to_prenex_imp_right {φ ψ : L.bounded_formula α n}
(hφ : is_qf φ) (hψ : is_prenex ψ) {v : α → M} {xs : fin n → M} :
(φ.to_prenex_imp_right ψ).realize v xs ↔ (φ.imp ψ).realize v xs :=
begin
revert φ,
induction hψ with _ _ hψ _ _ hψ ih _ _ hψ ih; intros φ hφ,
{ rw hψ.to_prenex_imp_right },
{ refine trans (forall_congr (λ _, ih hφ.lift_at)) _,
simp only [realize_imp, realize_lift_at_one_self, snoc_comp_cast_succ, realize_all],
exact ⟨λ h1 a h2, h1 h2 a, λ h1 h2 a, h1 a h2⟩, },
{ rw [to_prenex_imp_right, realize_ex],
refine trans (exists_congr (λ _, ih hφ.lift_at)) _,
simp only [realize_imp, realize_lift_at_one_self, snoc_comp_cast_succ, realize_ex],
refine ⟨_, λ h', _⟩,
{ rintro ⟨a, ha⟩ h,
exact ⟨a, ha h⟩ },
{ by_cases φ.realize v xs,
{ obtain ⟨a, ha⟩ := h' h,
exact ⟨a, λ _, ha⟩ },
{ inhabit M,
exact ⟨default, λ h'', (h h'').elim⟩ } } }
end
lemma realize_to_prenex_imp {φ ψ : L.bounded_formula α n}
(hφ : is_prenex φ) (hψ : is_prenex ψ) {v : α → M} {xs : fin n → M} :
(φ.to_prenex_imp ψ).realize v xs ↔ (φ.imp ψ).realize v xs :=
begin
revert ψ,
induction hφ with _ _ hφ _ _ hφ ih _ _ hφ ih; intros ψ hψ,
{ rw [hφ.to_prenex_imp],
exact realize_to_prenex_imp_right hφ hψ, },
{ rw [to_prenex_imp, realize_ex],
refine trans (exists_congr (λ _, ih hψ.lift_at)) _,
simp only [realize_imp, realize_lift_at_one_self, snoc_comp_cast_succ, realize_all],
refine ⟨_, λ h', _⟩,
{ rintro ⟨a, ha⟩ h,
exact ha (h a) },
{ by_cases ψ.realize v xs,
{ inhabit M,
exact ⟨default, λ h'', h⟩ },
{ obtain ⟨a, ha⟩ := not_forall.1 (h ∘ h'),
exact ⟨a, λ h, (ha h).elim⟩ } } },
{ refine trans (forall_congr (λ _, ih hψ.lift_at)) _,
simp, },
end
@[simp] lemma realize_to_prenex (φ : L.bounded_formula α n) {v : α → M} :
∀ {xs : fin n → M}, φ.to_prenex.realize v xs ↔ φ.realize v xs :=
begin
refine bounded_formula.rec_on φ
(λ _ _, iff.rfl)
(λ _ _ _ _, iff.rfl)
(λ _ _ _ _ _, iff.rfl)
(λ _ f1 f2 h1 h2 _, _)
(λ _ f h xs, _),
{ rw [to_prenex, realize_to_prenex_imp f1.to_prenex_is_prenex f2.to_prenex_is_prenex,
realize_imp, realize_imp, h1, h2],
apply_instance },
{ rw [realize_all, to_prenex, realize_all],
exact forall_congr (λ a, h) },
end
end bounded_formula
attribute [protected] bounded_formula.falsum bounded_formula.equal bounded_formula.rel
attribute [protected] bounded_formula.imp bounded_formula.all
namespace Lhom
open bounded_formula
@[simp] lemma realize_on_bounded_formula [L'.Structure M] (φ : L →ᴸ L') [φ.is_expansion_on M]
{n : ℕ} (ψ : L.bounded_formula α n) {v : α → M} {xs : fin n → M} :
(φ.on_bounded_formula ψ).realize v xs ↔ ψ.realize v xs :=
begin
induction ψ with _ _ _ _ _ _ _ _ _ _ _ ih1 ih2 _ _ ih3,
{ refl },
{ simp only [on_bounded_formula, realize_bd_equal, realize_on_term],
refl, },
{ simp only [on_bounded_formula, realize_rel, realize_on_term, Lhom.map_on_relation],
refl, },
{ simp only [on_bounded_formula, ih1, ih2, realize_imp], },
{ simp only [on_bounded_formula, ih3, realize_all], },
end
end Lhom
attribute [protected] bounded_formula.falsum bounded_formula.equal bounded_formula.rel
attribute [protected] bounded_formula.imp bounded_formula.all
namespace formula
/-- A formula can be evaluated as true or false by giving values to each free variable. -/
def realize (φ : L.formula α) (v : α → M) : Prop :=
φ.realize v default
variables {M} {φ ψ : L.formula α} {v : α → M}
@[simp] lemma realize_not :
(φ.not).realize v ↔ ¬ φ.realize v :=
iff.rfl
@[simp] lemma realize_bot :
(⊥ : L.formula α).realize v ↔ false :=
iff.rfl
@[simp] lemma realize_top :
(⊤ : L.formula α).realize v ↔ true :=
bounded_formula.realize_top
@[simp] lemma realize_inf : (φ ⊓ ψ).realize v ↔ (φ.realize v ∧ ψ.realize v) :=
bounded_formula.realize_inf
@[simp] lemma realize_imp : (φ.imp ψ).realize v ↔ (φ.realize v → ψ.realize v) :=
bounded_formula.realize_imp
@[simp] lemma realize_rel {k : ℕ} {R : L.relations k} {ts : fin k → L.term α} :
(R.formula ts).realize v ↔ rel_map R (λ i, (ts i).realize v) :=
bounded_formula.realize_rel.trans (by simp)
@[simp] lemma realize_rel₁ {R : L.relations 1} {t : L.term _} :
(R.formula₁ t).realize v ↔ rel_map R ![t.realize v] :=
begin
rw [relations.formula₁, realize_rel, iff_eq_eq],
refine congr rfl (funext (λ _, _)),
simp only [matrix.cons_val_fin_one],
end
@[simp] lemma realize_rel₂ {R : L.relations 2} {t₁ t₂ : L.term _} :
(R.formula₂ t₁ t₂).realize v ↔
rel_map R ![t₁.realize v, t₂.realize v] :=
begin
rw [relations.formula₂, realize_rel, iff_eq_eq],
refine congr rfl (funext (fin.cases _ _)),
{ simp only [matrix.cons_val_zero]},
{ simp only [matrix.cons_val_succ, matrix.cons_val_fin_one, forall_const] }
end
@[simp] lemma realize_sup : (φ ⊔ ψ).realize v ↔ (φ.realize v ∨ ψ.realize v) :=
bounded_formula.realize_sup
@[simp] lemma realize_iff : (φ.iff ψ).realize v ↔ (φ.realize v ↔ ψ.realize v) :=
bounded_formula.realize_iff
@[simp] lemma realize_relabel {φ : L.formula α} {g : α → β} {v : β → M} :
(φ.relabel g).realize v ↔ φ.realize (v ∘ g) :=
begin
rw [realize, realize, relabel, bounded_formula.realize_relabel,
iff_eq_eq, fin.cast_add_zero],
exact congr rfl (funext fin_zero_elim),
end
lemma realize_relabel_sum_inr (φ : L.formula (fin n)) {v : empty → M} {x : fin n → M} :
(bounded_formula.relabel sum.inr φ).realize v x ↔ φ.realize x :=
by rw [bounded_formula.realize_relabel, formula.realize, sum.elim_comp_inr, fin.cast_add_zero,
cast_refl, order_iso.coe_refl, function.comp.right_id,
subsingleton.elim (x ∘ (nat_add n : fin 0 → fin n)) default]
@[simp]
lemma realize_equal {t₁ t₂ : L.term α} {x : α → M} :
(t₁.equal t₂).realize x ↔ t₁.realize x = t₂.realize x :=
by simp [term.equal, realize]
@[simp]
lemma realize_graph {f : L.functions n} {x : fin n → M} {y : M} :
(formula.graph f).realize (fin.cons y x : _ → M) ↔ fun_map f x = y :=
begin
simp only [formula.graph, term.realize, realize_equal, fin.cons_zero, fin.cons_succ],
rw eq_comm,
end
end formula
@[simp] lemma Lhom.realize_on_formula [L'.Structure M] (φ : L →ᴸ L') [φ.is_expansion_on M]
(ψ : L.formula α) {v : α → M} :
(φ.on_formula ψ).realize v ↔ ψ.realize v :=
φ.realize_on_bounded_formula ψ
@[simp] lemma Lhom.set_of_realize_on_formula [L'.Structure M] (φ : L →ᴸ L') [φ.is_expansion_on M]
(ψ : L.formula α) :
(set_of (φ.on_formula ψ).realize : set (α → M)) = set_of ψ.realize :=
by { ext, simp }
variable (M)
/-- A sentence can be evaluated as true or false in a structure. -/
def sentence.realize (φ : L.sentence) : Prop :=
φ.realize (default : _ → M)
infix ` ⊨ `:51 := sentence.realize -- input using \|= or \vDash, but not using \models
@[simp] lemma sentence.realize_not {φ : L.sentence} :
M ⊨ φ.not ↔ ¬ M ⊨ φ :=
iff.rfl
@[simp] lemma Lhom.realize_on_sentence [L'.Structure M] (φ : L →ᴸ L') [φ.is_expansion_on M]
(ψ : L.sentence) :
M ⊨ φ.on_sentence ψ ↔ M ⊨ ψ :=
φ.realize_on_formula ψ
variables (L)
/-- The complete theory of a structure `M` is the set of all sentences `M` satisfies. -/
def complete_theory : L.Theory := { φ | M ⊨ φ }
variable (N)
/-- Two structures are elementarily equivalent when they satisfy the same sentences. -/
def elementarily_equivalent : Prop := L.complete_theory M = L.complete_theory N
localized "notation A ` ≅[`:25 L `] ` B:50 := first_order.language.elementarily_equivalent L A B"
in first_order
variables {L} {M} {N}
@[simp] lemma mem_complete_theory {φ : sentence L} : φ ∈ L.complete_theory M ↔ M ⊨ φ := iff.rfl
lemma elementarily_equivalent_iff : M ≅[L] N ↔ ∀ φ : L.sentence, M ⊨ φ ↔ N ⊨ φ :=
by simp only [elementarily_equivalent, set.ext_iff, complete_theory, set.mem_set_of_eq]
variables (M)
/-- A model of a theory is a structure in which every sentence is realized as true. -/
class Theory.model (T : L.Theory) : Prop :=
(realize_of_mem : ∀ φ ∈ T, M ⊨ φ)
infix ` ⊨ `:51 := Theory.model -- input using \|= or \vDash, but not using \models
variables {M} (T : L.Theory)
@[simp] lemma Theory.model_iff : M ⊨ T ↔ ∀ φ ∈ T, M ⊨ φ := ⟨λ h, h.realize_of_mem, λ h, ⟨h⟩⟩
lemma Theory.realize_sentence_of_mem [M ⊨ T] {φ : L.sentence} (h : φ ∈ T) :
M ⊨ φ :=
Theory.model.realize_of_mem φ h
@[simp] lemma Lhom.on_Theory_model [L'.Structure M] (φ : L →ᴸ L') [φ.is_expansion_on M]
(T : L.Theory) :
M ⊨ φ.on_Theory T ↔ M ⊨ T :=
by simp [Theory.model_iff, Lhom.on_Theory]
variables {M} {T}
instance model_empty : M ⊨ (∅ : L.Theory) := ⟨λ φ hφ, (set.not_mem_empty φ hφ).elim⟩
namespace Theory
lemma model.mono {T' : L.Theory} (h : M ⊨ T') (hs : T ⊆ T') :
M ⊨ T :=
⟨λ φ hφ, T'.realize_sentence_of_mem (hs hφ)⟩
lemma model.union {T' : L.Theory} (h : M ⊨ T) (h' : M ⊨ T') :
M ⊨ T ∪ T' :=
begin
simp only [model_iff, set.mem_union_eq] at *,
exact λ φ hφ, hφ.elim (h _) (h' _),
end
@[simp] lemma model_union_iff {T' : L.Theory} :
M ⊨ T ∪ T' ↔ M ⊨ T ∧ M ⊨ T' :=
⟨λ h, ⟨h.mono (T.subset_union_left T'), h.mono (T.subset_union_right T')⟩, λ h, h.1.union h.2⟩
lemma model_singleton_iff {φ : L.sentence} :
M ⊨ ({φ} : L.Theory) ↔ M ⊨ φ :=
by simp
theorem model_iff_subset_complete_theory :
M ⊨ T ↔ T ⊆ L.complete_theory M :=
T.model_iff
end Theory
instance model_complete_theory : M ⊨ L.complete_theory M :=
Theory.model_iff_subset_complete_theory.2 (subset_refl _)
variables (M N)
theorem realize_iff_of_model_complete_theory [N ⊨ L.complete_theory M] (φ : L.sentence) :
N ⊨ φ ↔ M ⊨ φ :=
begin
refine ⟨λ h, _, (L.complete_theory M).realize_sentence_of_mem⟩,
contrapose! h,
rw [← sentence.realize_not] at *,
exact (L.complete_theory M).realize_sentence_of_mem (mem_complete_theory.2 h)
end
variables {M N}
namespace bounded_formula
@[simp] lemma realize_alls {φ : L.bounded_formula α n} {v : α → M} :
φ.alls.realize v ↔
∀ (xs : fin n → M), (φ.realize v xs) :=
begin
induction n with n ih,
{ exact unique.forall_iff.symm },
{ simp only [alls, ih, realize],
exact ⟨λ h xs, (fin.snoc_init_self xs) ▸ h _ _, λ h xs x, h (fin.snoc xs x)⟩ }
end
@[simp] lemma realize_exs {φ : L.bounded_formula α n} {v : α → M} :
φ.exs.realize v ↔ ∃ (xs : fin n → M), (φ.realize v xs) :=
begin
induction n with n ih,
{ exact unique.exists_iff.symm },
{ simp only [bounded_formula.exs, ih, realize_ex],
split,
{ rintros ⟨xs, x, h⟩,
exact ⟨_, h⟩ },
{ rintros ⟨xs, h⟩,
rw ← fin.snoc_init_self xs at h,
exact ⟨_, _, h⟩ } }
end
@[simp] lemma realize_to_formula (φ : L.bounded_formula α n) (v : α ⊕ fin n → M) :
φ.to_formula.realize v ↔ φ.realize (v ∘ sum.inl) (v ∘ sum.inr) :=
begin
induction φ with _ _ _ _ _ _ _ _ _ _ _ ih1 ih2 _ _ ih3 a8 a9 a0,
{ refl },
{ simp [bounded_formula.realize] },
{ simp [bounded_formula.realize] },
{ rw [to_formula, formula.realize, realize_imp, ← formula.realize, ih1, ← formula.realize, ih2,
realize_imp], },
{ rw [to_formula, formula.realize, realize_all, realize_all],
refine forall_congr (λ a, _),
have h := ih3 (sum.elim (v ∘ sum.inl) (snoc (v ∘ sum.inr) a)),
simp only [sum.elim_comp_inl, sum.elim_comp_inr] at h,
rw [← h, realize_relabel, formula.realize],
rcongr,
{ cases x,
{ simp },
{ refine fin.last_cases _ (λ i, _) x,
{ rw [sum.elim_inr, snoc_last, function.comp_app, sum.elim_inr, function.comp_app,
fin_sum_fin_equiv_symm_last, sum.map_inr, sum.elim_inr, function.comp_app],
exact (congr rfl (subsingleton.elim _ _)).trans (snoc_last _ _) },
{ simp only [cast_succ, function.comp_app, sum.elim_inr,
fin_sum_fin_equiv_symm_apply_cast_add, sum.map_inl, sum.elim_inl],
rw [← cast_succ, snoc_cast_succ] } } },
{ exact subsingleton.elim _ _ } }
end
end bounded_formula
namespace equiv
@[simp] lemma realize_bounded_formula (g : M ≃[L] N) (φ : L.bounded_formula α n)
{v : α → M} {xs : fin n → M} :
φ.realize (g ∘ v) (g ∘ xs) ↔ φ.realize v xs :=
begin
induction φ with _ _ _ _ _ _ _ _ _ _ _ ih1 ih2 _ _ ih3,
{ refl },
{ simp only [bounded_formula.realize, ← sum.comp_elim, equiv.realize_term, g.injective.eq_iff] },
{ simp only [bounded_formula.realize, ← sum.comp_elim, equiv.realize_term, g.map_rel], },
{ rw [bounded_formula.realize, ih1, ih2, bounded_formula.realize] },
{ rw [bounded_formula.realize, bounded_formula.realize],
split,
{ intros h a,
have h' := h (g a),
rw [← fin.comp_snoc, ih3] at h',
exact h' },
{ intros h a,
have h' := h (g.symm a),
rw [← ih3, fin.comp_snoc, g.apply_symm_apply] at h',
exact h' }}
end
@[simp] lemma realize_formula (g : M ≃[L] N) (φ : L.formula α) {v : α → M} :
φ.realize (g ∘ v) ↔ φ.realize v :=
by rw [formula.realize, formula.realize, ← g.realize_bounded_formula φ,
iff_eq_eq, unique.eq_default (g ∘ default)]
lemma realize_sentence (g : M ≃[L] N) (φ : L.sentence) :
M ⊨ φ ↔ N ⊨ φ :=
by rw [sentence.realize, sentence.realize, ← g.realize_formula, unique.eq_default (g ∘ default)]
lemma Theory_model (g : M ≃[L] N) [M ⊨ T] : N ⊨ T :=
⟨λ φ hφ, (g.realize_sentence φ).1 (Theory.realize_sentence_of_mem T hφ)⟩
lemma elementarily_equivalent (g : M ≃[L] N) : M ≅[L] N :=
elementarily_equivalent_iff.2 g.realize_sentence
end equiv
namespace relations
open bounded_formula
variable {r : L.relations 2}
@[simp]
lemma realize_reflexive :
M ⊨ r.reflexive ↔ reflexive (λ (x y : M), rel_map r ![x,y]) :=
forall_congr (λ _, realize_rel₂)
@[simp]
lemma realize_irreflexive :
M ⊨ r.irreflexive ↔ irreflexive (λ (x y : M), rel_map r ![x,y]) :=
forall_congr (λ _, not_congr realize_rel₂)
@[simp]
lemma realize_symmetric :
M ⊨ r.symmetric ↔ symmetric (λ (x y : M), rel_map r ![x,y]) :=
forall_congr (λ _, forall_congr (λ _, imp_congr realize_rel₂ realize_rel₂))
@[simp]
lemma realize_antisymmetric :
M ⊨ r.antisymmetric ↔ anti_symmetric (λ (x y : M), rel_map r ![x,y]) :=
forall_congr (λ _, forall_congr (λ _, imp_congr realize_rel₂ (imp_congr realize_rel₂ iff.rfl)))
@[simp]
lemma realize_transitive :
M ⊨ r.transitive ↔ transitive (λ (x y : M), rel_map r ![x,y]) :=
forall_congr (λ _, forall_congr (λ _, forall_congr
(λ _, imp_congr realize_rel₂ (imp_congr realize_rel₂ realize_rel₂))))
@[simp]
lemma realize_total :
M ⊨ r.total ↔ total (λ (x y : M), rel_map r ![x,y]) :=
forall_congr (λ _, forall_congr (λ _, realize_sup.trans (or_congr realize_rel₂ realize_rel₂)))
end relations
section cardinality
variable (L)
@[simp] lemma sentence.realize_card_ge (n) : M ⊨ (sentence.card_ge L n) ↔ ↑n ≤ (# M) :=
begin
rw [← lift_mk_fin, ← lift_le, lift_lift, lift_mk_le, sentence.card_ge, sentence.realize,
bounded_formula.realize_exs],
simp_rw [bounded_formula.realize_foldr_inf],
simp only [function.comp_app, list.mem_map, prod.exists, ne.def, list.mem_product,
list.mem_fin_range, forall_exists_index, and_imp, list.mem_filter, true_and],
refine ⟨_, λ xs, ⟨xs.some, _⟩⟩,
{ rintro ⟨xs, h⟩,
refine ⟨⟨xs, λ i j ij, _⟩⟩,
contrapose! ij,
have hij := h _ i j ij rfl,
simp only [bounded_formula.realize_not, term.realize, bounded_formula.realize_bd_equal,
sum.elim_inr] at hij,
exact hij },
{ rintro _ i j ij rfl,
simp [ij] }
end
@[simp] lemma model_infinite_theory_iff : M ⊨ L.infinite_theory ↔ infinite M :=
by simp [infinite_theory, infinite_iff, aleph_0_le]
instance model_infinite_theory [h : infinite M] :
M ⊨ L.infinite_theory :=
L.model_infinite_theory_iff.2 h
@[simp] lemma model_nonempty_theory_iff :
M ⊨ L.nonempty_theory ↔ nonempty M :=
by simp only [nonempty_theory, Theory.model_iff, set.mem_singleton_iff, forall_eq,
sentence.realize_card_ge, nat.cast_one, one_le_iff_ne_zero, mk_ne_zero_iff]
instance model_nonempty [h : nonempty M] :
M ⊨ L.nonempty_theory :=
L.model_nonempty_theory_iff.2 h
lemma model_distinct_constants_theory {M : Type w} [L[[α]].Structure M] (s : set α) :
M ⊨ L.distinct_constants_theory s ↔ set.inj_on (λ (i : α), (L.con i : M)) s :=
begin
simp only [distinct_constants_theory, Theory.model_iff, set.mem_image,
set.mem_inter_eq, set.mem_prod, set.mem_compl_eq, prod.exists, forall_exists_index, and_imp],
refine ⟨λ h a as b bs ab, _, _⟩,
{ contrapose! ab,
have h' := h _ a b as bs ab rfl,
simp only [sentence.realize, formula.realize_not, formula.realize_equal,
term.realize_constants] at h',
exact h', },
{ rintros h φ a b as bs ab rfl,
simp only [sentence.realize, formula.realize_not, formula.realize_equal,
term.realize_constants],
exact λ contra, ab (h as bs contra) }
end
lemma card_le_of_model_distinct_constants_theory (s : set α) (M : Type w) [L[[α]].Structure M]
[h : M ⊨ L.distinct_constants_theory s] :
cardinal.lift.{w} (# s) ≤ cardinal.lift.{u'} (# M) :=
lift_mk_le'.2 ⟨⟨_, set.inj_on_iff_injective.1 ((L.model_distinct_constants_theory s).1 h)⟩⟩
end cardinality
namespace elementarily_equivalent
@[symm] lemma symm (h : M ≅[L] N) : N ≅[L] M := h.symm
@[trans] lemma trans (MN : M ≅[L] N) (NP : N ≅[L] P) : M ≅[L] P := MN.trans NP
lemma complete_theory_eq (h : M ≅[L] N) : L.complete_theory M = L.complete_theory N := h
lemma realize_sentence (h : M ≅[L] N) (φ : L.sentence) : M ⊨ φ ↔ N ⊨ φ :=
(elementarily_equivalent_iff.1 h) φ
lemma Theory_model_iff (h : M ≅[L] N) : M ⊨ T ↔ N ⊨ T :=
by rw [Theory.model_iff_subset_complete_theory, Theory.model_iff_subset_complete_theory,
h.complete_theory_eq]
lemma Theory_model [MT : M ⊨ T] (h : M ≅[L] N) : N ⊨ T :=
h.Theory_model_iff.1 MT
lemma nonempty_iff (h : M ≅[L] N) : nonempty M ↔ nonempty N :=
(model_nonempty_theory_iff L).symm.trans (h.Theory_model_iff.trans (model_nonempty_theory_iff L))
lemma nonempty [Mn : nonempty M] (h : M ≅[L] N) : nonempty N := h.nonempty_iff.1 Mn
lemma infinite_iff (h : M ≅[L] N) : infinite M ↔ infinite N :=
(model_infinite_theory_iff L).symm.trans (h.Theory_model_iff.trans (model_infinite_theory_iff L))
lemma infinite [Mi : infinite M] (h : M ≅[L] N) : infinite N := h.infinite_iff.1 Mi
end elementarily_equivalent
end language
end first_order
|
9a26f0047fc3b74ba1cd2a9cc6ab8afde13a3bfe | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /src/Lean/Parser/Basic.lean | e648c97cb808841cdd5207e935a11d17f6188aca | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | EdAyers/lean4 | 57ac632d6b0789cb91fab2170e8c9e40441221bd | 37ba0df5841bde51dbc2329da81ac23d4f6a4de4 | refs/heads/master | 1,676,463,245,298 | 1,660,619,433,000 | 1,660,619,433,000 | 183,433,437 | 1 | 0 | Apache-2.0 | 1,657,612,672,000 | 1,556,196,574,000 | Lean | UTF-8 | Lean | false | false | 76,312 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Sebastian Ullrich
-/
import Lean.Data.Trie
import Lean.Data.Position
import Lean.Syntax
import Lean.Environment
import Lean.Message
/-!
# Basic Lean parser infrastructure
The Lean parser was developed with the following primary goals in mind:
* flexibility: Lean's grammar is complex and includes indentation and other whitespace sensitivity. It should be
possible to introduce such custom "tweaks" locally without having to adjust the fundamental parsing approach.
* extensibility: Lean's grammar can be extended on the fly within a Lean file, and with Lean 4 we want to extend this
to cover embedding domain-specific languages that may look nothing like Lean, down to using a separate set of tokens.
* losslessness: The parser should produce a concrete syntax tree that preserves all whitespace and other "sub-token"
information for the use in tooling.
* performance: The overhead of the parser building blocks, and the overall parser performance on average-complexity
input, should be comparable with that of the previous parser hand-written in C++. No fancy optimizations should be
necessary for this.
Given these constraints, we decided to implement a combinatoric, non-monadic, lexer-less, memoizing recursive-descent
parser. Using combinators instead of some more formal and introspectible grammar representation ensures ultimate
flexibility as well as efficient extensibility: there is (almost) no pre-processing necessary when extending the grammar
with a new parser. However, because the all results the combinators produce are of the homogeneous `Syntax` type, the
basic parser type is not actually a monad but a monomorphic linear function `ParserState → ParserState`, avoiding
constructing and deconstructing countless monadic return values. Instead of explicitly returning syntax objects, parsers
push (zero or more of) them onto a syntax stack inside the linear state. Chaining parsers via `>>` accumulates their
output on the stack. Combinators such as `node` then pop off all syntax objects produced during their invocation and
wrap them in a single `Syntax.node` object that is again pushed on this stack. Instead of calling `node` directly, we
usually use the macro `leading_parser p`, which unfolds to `node k p` where the new syntax node kind `k` is the name of the
declaration being defined.
The lack of a dedicated lexer ensures we can modify and replace the lexical grammar at any point, and simplifies
detecting and propagating whitespace. The parser still has a concept of "tokens", however, and caches the most recent
one for performance: when `tokenFn` is called twice at the same position in the input, it will reuse the result of the
first call. `tokenFn` recognizes some built-in variable-length tokens such as identifiers as well as any fixed token in
the `ParserContext`'s `TokenTable` (a trie); however, the same cache field and strategy could be reused by custom token
parsers. Tokens also play a central role in the `prattParser` combinator, which selects a *leading* parser followed by
zero or more *trailing* parsers based on the current token (via `peekToken`); see the documentation of `prattParser`
for more details. Tokens are specified via the `symbol` parser, or with `symbolNoWs` for tokens that should not be preceded by whitespace.
The `Parser` type is extended with additional metadata over the mere parsing function to propagate token information:
`collectTokens` collects all tokens within a parser for registering. `firstTokens` holds information about the "FIRST"
token set used to speed up parser selection in `prattParser`. This approach of combining static and dynamic information
in the parser type is inspired by the paper "Deterministic, Error-Correcting Combinator Parsers" by Swierstra and Duponcheel.
If multiple parsers accept the same current token, `prattParser` tries all of them using the backtracking `longestMatchFn` combinator.
This is the only case where standard parsers might execute arbitrary backtracking. At the moment there is no memoization shared by these
parallel parsers apart from the first token, though we might change this in the future if the need arises.
Finally, error reporting follows the standard combinatoric approach of collecting a single unexpected token/... and zero
or more expected tokens (see `Error` below). Expected tokens are e.g. set by `symbol` and merged by `<|>`. Combinators
running multiple parsers should check if an error message is set in the parser state (`hasError`) and act accordingly.
Error recovery is left to the designer of the specific language; for example, Lean's top-level `parseCommand` loop skips
tokens until the next command keyword on error.
-/
namespace Lean
namespace Parser
abbrev mkAtom (info : SourceInfo) (val : String) : Syntax :=
Syntax.atom info val
abbrev mkIdent (info : SourceInfo) (rawVal : Substring) (val : Name) : Syntax :=
Syntax.ident info rawVal val []
/-- Return character after position `pos` -/
def getNext (input : String) (pos : String.Pos) : Char :=
input.get (input.next pos)
/-- Maximal (and function application) precedence.
In the standard lean language, no parser has precedence higher than `maxPrec`.
Note that nothing prevents users from using a higher precedence, but we strongly
discourage them from doing it. -/
def maxPrec : Nat := eval_prec max
def argPrec : Nat := eval_prec arg
def leadPrec : Nat := eval_prec lead
def minPrec : Nat := eval_prec min
abbrev Token := String
structure TokenCacheEntry where
startPos : String.Pos := 0
stopPos : String.Pos := 0
token : Syntax := Syntax.missing
structure ParserCache where
tokenCache : TokenCacheEntry
def initCacheForInput (input : String) : ParserCache := {
tokenCache := { startPos := input.endPos + ' ' /- make sure it is not a valid position -/}
}
abbrev TokenTable := Trie Token
abbrev SyntaxNodeKindSet := Std.PersistentHashMap SyntaxNodeKind Unit
def SyntaxNodeKindSet.insert (s : SyntaxNodeKindSet) (k : SyntaxNodeKind) : SyntaxNodeKindSet :=
Std.PersistentHashMap.insert s k ()
/--
Input string and related data. Recall that the `FileMap` is a helper structure for mapping
`String.Pos` in the input string to line/column information. -/
structure InputContext where
input : String
fileName : String
fileMap : FileMap
deriving Inhabited
/-- Input context derived from elaboration of previous commands. -/
structure ParserModuleContext where
env : Environment
options : Options
-- for name lookup
currNamespace : Name := Name.anonymous
openDecls : List OpenDecl := []
structure ParserContext extends InputContext, ParserModuleContext where
prec : Nat
tokens : TokenTable
-- used for bootstrapping only
quotDepth : Nat := 0
suppressInsideQuot : Bool := false
savedPos? : Option String.Pos := none
forbiddenTk? : Option Token := none
structure Error where
unexpected : String := ""
expected : List String := []
deriving Inhabited, BEq
namespace Error
private def expectedToString : List String → String
| [] => ""
| [e] => e
| [e1, e2] => e1 ++ " or " ++ e2
| e::es => e ++ ", " ++ expectedToString es
protected def toString (e : Error) : String :=
let unexpected := if e.unexpected == "" then [] else [e.unexpected]
let expected := if e.expected == [] then [] else
let expected := e.expected.toArray.qsort (fun e e' => e < e')
let expected := expected.toList.eraseReps
["expected " ++ expectedToString expected]
"; ".intercalate $ unexpected ++ expected
instance : ToString Error := ⟨Error.toString⟩
def merge (e₁ e₂ : Error) : Error :=
match e₂ with
| { unexpected := u, .. } => { unexpected := if u == "" then e₁.unexpected else u, expected := e₁.expected ++ e₂.expected }
end Error
structure ParserState where
stxStack : Array Syntax := #[]
/--
Set to the precedence of the preceding (not surrounding) parser by `runLongestMatchParser`
for the use of `checkLhsPrec` in trailing parsers.
Note that with chaining, the preceding parser can be another trailing parser:
in `1 * 2 + 3`, the preceding parser is '*' when '+' is executed. -/
lhsPrec : Nat := 0
pos : String.Pos := 0
cache : ParserCache
errorMsg : Option Error := none
namespace ParserState
@[inline] def hasError (s : ParserState) : Bool :=
s.errorMsg != none
@[inline] def stackSize (s : ParserState) : Nat :=
s.stxStack.size
def restore (s : ParserState) (iniStackSz : Nat) (iniPos : String.Pos) : ParserState :=
{ s with stxStack := s.stxStack.shrink iniStackSz, errorMsg := none, pos := iniPos }
def setPos (s : ParserState) (pos : String.Pos) : ParserState :=
{ s with pos := pos }
def setCache (s : ParserState) (cache : ParserCache) : ParserState :=
{ s with cache := cache }
def pushSyntax (s : ParserState) (n : Syntax) : ParserState :=
{ s with stxStack := s.stxStack.push n }
def popSyntax (s : ParserState) : ParserState :=
{ s with stxStack := s.stxStack.pop }
def shrinkStack (s : ParserState) (iniStackSz : Nat) : ParserState :=
{ s with stxStack := s.stxStack.shrink iniStackSz }
def next (s : ParserState) (input : String) (pos : String.Pos) : ParserState :=
{ s with pos := input.next pos }
def toErrorMsg (ctx : ParserContext) (s : ParserState) : String :=
match s.errorMsg with
| none => ""
| some msg =>
let pos := ctx.fileMap.toPosition s.pos
mkErrorStringWithPos ctx.fileName pos (toString msg)
def mkNode (s : ParserState) (k : SyntaxNodeKind) (iniStackSz : Nat) : ParserState :=
match s with
| ⟨stack, lhsPrec, pos, cache, err⟩ =>
if err != none && stack.size == iniStackSz then
-- If there is an error but there are no new nodes on the stack, use `missing` instead.
-- Thus we ensure the property that an syntax tree contains (at least) one `missing` node
-- if (and only if) there was a parse error.
-- We should not create an actual node of kind `k` in this case because it would mean we
-- choose an "arbitrary" node (in practice the last one) in an alternative of the form
-- `node k1 p1 <|> ... <|> node kn pn` when all parsers fail. With the code below we
-- instead return a less misleading single `missing` node without randomly selecting any `ki`.
let stack := stack.push Syntax.missing
⟨stack, lhsPrec, pos, cache, err⟩
else
let newNode := Syntax.node SourceInfo.none k (stack.extract iniStackSz stack.size)
let stack := stack.shrink iniStackSz
let stack := stack.push newNode
⟨stack, lhsPrec, pos, cache, err⟩
def mkTrailingNode (s : ParserState) (k : SyntaxNodeKind) (iniStackSz : Nat) : ParserState :=
match s with
| ⟨stack, lhsPrec, pos, cache, err⟩ =>
let newNode := Syntax.node SourceInfo.none k (stack.extract (iniStackSz - 1) stack.size)
let stack := stack.shrink (iniStackSz - 1)
let stack := stack.push newNode
⟨stack, lhsPrec, pos, cache, err⟩
def setError (s : ParserState) (msg : String) : ParserState :=
match s with
| ⟨stack, lhsPrec, pos, cache, _⟩ => ⟨stack, lhsPrec, pos, cache, some { expected := [ msg ] }⟩
def mkError (s : ParserState) (msg : String) : ParserState :=
match s with
| ⟨stack, lhsPrec, pos, cache, _⟩ => ⟨stack.push Syntax.missing, lhsPrec, pos, cache, some { expected := [ msg ] }⟩
def mkUnexpectedError (s : ParserState) (msg : String) (expected : List String := []) : ParserState :=
match s with
| ⟨stack, lhsPrec, pos, cache, _⟩ => ⟨stack.push Syntax.missing, lhsPrec, pos, cache, some { unexpected := msg, expected := expected }⟩
def mkEOIError (s : ParserState) (expected : List String := []) : ParserState :=
s.mkUnexpectedError "unexpected end of input" expected
def mkErrorAt (s : ParserState) (msg : String) (pos : String.Pos) (initStackSz? : Option Nat := none) : ParserState :=
match s, initStackSz? with
| ⟨stack, lhsPrec, _, cache, _⟩, none => ⟨stack.push Syntax.missing, lhsPrec, pos, cache, some { expected := [ msg ] }⟩
| ⟨stack, lhsPrec, _, cache, _⟩, some sz => ⟨stack.shrink sz |>.push Syntax.missing, lhsPrec, pos, cache, some { expected := [ msg ] }⟩
def mkErrorsAt (s : ParserState) (ex : List String) (pos : String.Pos) (initStackSz? : Option Nat := none) : ParserState :=
match s, initStackSz? with
| ⟨stack, lhsPrec, _, cache, _⟩, none => ⟨stack.push Syntax.missing, lhsPrec, pos, cache, some { expected := ex }⟩
| ⟨stack, lhsPrec, _, cache, _⟩, some sz => ⟨stack.shrink sz |>.push Syntax.missing, lhsPrec, pos, cache, some { expected := ex }⟩
def mkUnexpectedErrorAt (s : ParserState) (msg : String) (pos : String.Pos) : ParserState :=
match s with
| ⟨stack, lhsPrec, _, cache, _⟩ => ⟨stack.push Syntax.missing, lhsPrec, pos, cache, some { unexpected := msg }⟩
end ParserState
def ParserFn := ParserContext → ParserState → ParserState
instance : Inhabited ParserFn where
default := fun _ s => s
inductive FirstTokens where
| epsilon : FirstTokens
| unknown : FirstTokens
| tokens : List Token → FirstTokens
| optTokens : List Token → FirstTokens
deriving Inhabited
namespace FirstTokens
def seq : FirstTokens → FirstTokens → FirstTokens
| epsilon, tks => tks
| optTokens s₁, optTokens s₂ => optTokens (s₁ ++ s₂)
| optTokens s₁, tokens s₂ => tokens (s₁ ++ s₂)
| tks, _ => tks
def toOptional : FirstTokens → FirstTokens
| tokens tks => optTokens tks
| tks => tks
def merge : FirstTokens → FirstTokens → FirstTokens
| epsilon, tks => toOptional tks
| tks, epsilon => toOptional tks
| tokens s₁, tokens s₂ => tokens (s₁ ++ s₂)
| optTokens s₁, optTokens s₂ => optTokens (s₁ ++ s₂)
| tokens s₁, optTokens s₂ => optTokens (s₁ ++ s₂)
| optTokens s₁, tokens s₂ => optTokens (s₁ ++ s₂)
| _, _ => unknown
def toStr : FirstTokens → String
| epsilon => "epsilon"
| unknown => "unknown"
| tokens tks => toString tks
| optTokens tks => "?" ++ toString tks
instance : ToString FirstTokens := ⟨toStr⟩
end FirstTokens
structure ParserInfo where
collectTokens : List Token → List Token := id
collectKinds : SyntaxNodeKindSet → SyntaxNodeKindSet := id
firstTokens : FirstTokens := FirstTokens.unknown
deriving Inhabited
structure Parser where
info : ParserInfo := {}
fn : ParserFn
deriving Inhabited
abbrev TrailingParser := Parser
def dbgTraceStateFn (label : String) (p : ParserFn) : ParserFn :=
fun c s =>
let sz := s.stxStack.size
let s' := p c s
dbg_trace "{label}
pos: {s'.pos}
err: {s'.errorMsg}
out: {s'.stxStack.extract sz s'.stxStack.size}"
s'
def dbgTraceState (label : String) (p : Parser) : Parser where
fn := dbgTraceStateFn label p.fn
info := p.info
@[noinline] def epsilonInfo : ParserInfo :=
{ firstTokens := FirstTokens.epsilon }
@[inline] def checkStackTopFn (p : Syntax → Bool) (msg : String) : ParserFn := fun _ s =>
if p s.stxStack.back then s
else s.mkUnexpectedError msg
@[inline] def checkStackTop (p : Syntax → Bool) (msg : String) : Parser := {
info := epsilonInfo,
fn := checkStackTopFn p msg
}
@[inline] def andthenFn (p q : ParserFn) : ParserFn := fun c s =>
let s := p c s
if s.hasError then s else q c s
@[noinline] def andthenInfo (p q : ParserInfo) : ParserInfo := {
collectTokens := p.collectTokens ∘ q.collectTokens,
collectKinds := p.collectKinds ∘ q.collectKinds,
firstTokens := p.firstTokens.seq q.firstTokens
}
@[inline] def andthen (p q : Parser) : Parser := {
info := andthenInfo p.info q.info,
fn := andthenFn p.fn q.fn
}
instance : AndThen Parser where
andThen a b := andthen a (b ())
@[inline] def nodeFn (n : SyntaxNodeKind) (p : ParserFn) : ParserFn := fun c s =>
let iniSz := s.stackSize
let s := p c s
s.mkNode n iniSz
@[inline] def trailingNodeFn (n : SyntaxNodeKind) (p : ParserFn) : ParserFn := fun c s =>
let iniSz := s.stackSize
let s := p c s
s.mkTrailingNode n iniSz
@[noinline] def nodeInfo (n : SyntaxNodeKind) (p : ParserInfo) : ParserInfo := {
collectTokens := p.collectTokens,
collectKinds := fun s => (p.collectKinds s).insert n,
firstTokens := p.firstTokens
}
@[inline] def node (n : SyntaxNodeKind) (p : Parser) : Parser := {
info := nodeInfo n p.info,
fn := nodeFn n p.fn
}
def errorFn (msg : String) : ParserFn := fun _ s =>
s.mkUnexpectedError msg
@[inline] def error (msg : String) : Parser := {
info := epsilonInfo,
fn := errorFn msg
}
def errorAtSavedPosFn (msg : String) (delta : Bool) : ParserFn := fun c s =>
match c.savedPos? with
| none => s
| some pos =>
let pos := if delta then c.input.next pos else pos
match s with
| ⟨stack, lhsPrec, _, cache, _⟩ => ⟨stack.push Syntax.missing, lhsPrec, pos, cache, some { unexpected := msg }⟩
/-- Generate an error at the position saved with the `withPosition` combinator.
If `delta == true`, then it reports at saved position+1.
This useful to make sure a parser consumed at least one character. -/
@[inline] def errorAtSavedPos (msg : String) (delta : Bool) : Parser := {
fn := errorAtSavedPosFn msg delta
}
/-- Succeeds if `c.prec <= prec` -/
def checkPrecFn (prec : Nat) : ParserFn := fun c s =>
if c.prec <= prec then s
else s.mkUnexpectedError "unexpected token at this precedence level; consider parenthesizing the term"
@[inline] def checkPrec (prec : Nat) : Parser := {
info := epsilonInfo,
fn := checkPrecFn prec
}
/-- Succeeds if `c.lhsPrec >= prec` -/
def checkLhsPrecFn (prec : Nat) : ParserFn := fun _ s =>
if s.lhsPrec >= prec then s
else s.mkUnexpectedError "unexpected token at this precedence level; consider parenthesizing the term"
@[inline] def checkLhsPrec (prec : Nat) : Parser := {
info := epsilonInfo,
fn := checkLhsPrecFn prec
}
def setLhsPrecFn (prec : Nat) : ParserFn := fun _ s =>
if s.hasError then s
else { s with lhsPrec := prec }
@[inline] def setLhsPrec (prec : Nat) : Parser := {
info := epsilonInfo,
fn := setLhsPrecFn prec
}
private def addQuotDepthFn (i : Int) (p : ParserFn) : ParserFn := fun c s =>
p { c with quotDepth := c.quotDepth + i |>.toNat } s
@[inline] def incQuotDepth (p : Parser) : Parser := {
info := p.info,
fn := addQuotDepthFn 1 p.fn
}
@[inline] def decQuotDepth (p : Parser) : Parser := {
info := p.info,
fn := addQuotDepthFn (-1) p.fn
}
def suppressInsideQuotFn (p : ParserFn) : ParserFn := fun c s =>
p { c with suppressInsideQuot := true } s
@[inline] def suppressInsideQuot (p : Parser) : Parser := {
info := p.info,
fn := suppressInsideQuotFn p.fn
}
@[inline] def leadingNode (n : SyntaxNodeKind) (prec : Nat) (p : Parser) : Parser :=
checkPrec prec >> node n p >> setLhsPrec prec
@[inline] def trailingNodeAux (n : SyntaxNodeKind) (p : Parser) : TrailingParser := {
info := nodeInfo n p.info,
fn := trailingNodeFn n p.fn
}
@[inline] def trailingNode (n : SyntaxNodeKind) (prec lhsPrec : Nat) (p : Parser) : TrailingParser :=
checkPrec prec >> checkLhsPrec lhsPrec >> trailingNodeAux n p >> setLhsPrec prec
def mergeOrElseErrors (s : ParserState) (error1 : Error) (iniPos : String.Pos) (mergeErrors : Bool) : ParserState :=
match s with
| ⟨stack, lhsPrec, pos, cache, some error2⟩ =>
if pos == iniPos then ⟨stack, lhsPrec, pos, cache, some (if mergeErrors then error1.merge error2 else error2)⟩
else s
| other => other
-- When `p` in `p <|> q` parses exactly one antiquotation, ...
inductive OrElseOnAntiquotBehavior where
| acceptLhs -- return it
| takeLongest -- return result of `q` instead if it made more progress
| merge -- ... and create choice node if both made the same progress
deriving BEq
def orelseFnCore (p q : ParserFn) (antiquotBehavior := OrElseOnAntiquotBehavior.merge) : ParserFn := fun c s => Id.run do
let s0 := s
let iniSz := s.stackSize
let iniPos := s.pos
let mut s := p c s
match s.errorMsg with
| some errorMsg =>
if s.pos == iniPos then
mergeOrElseErrors (q c (s.restore iniSz iniPos)) errorMsg iniPos true
else
s
| none =>
let back := s.stxStack.back
if antiquotBehavior != .acceptLhs && s.stackSize == iniSz + 1 && back.isAntiquots then
let s' := q c s0
if !s'.hasError then
-- If `q` made more progress than `p`, we prefer its result.
-- Thus `(structInstField| $id := $val) is interpreted as
-- `(structInstField| $id:ident := $val:term), not
-- `(structInstField| $id:structInstField <ERROR: expected ')'>.
if s'.pos > s.pos then
return s'
else if antiquotBehavior == .merge && s'.stackSize == iniSz + 1 && s'.stxStack.back.isAntiquot then
if back.isOfKind choiceKind then
s := { s with stxStack := s.stxStack.pop ++ back.getArgs }
s := s.pushSyntax s'.stxStack.back
s := s.mkNode choiceKind iniSz
s
@[inline] def orelseFn (p q : ParserFn) : ParserFn :=
orelseFnCore p q
@[noinline] def orelseInfo (p q : ParserInfo) : ParserInfo := {
collectTokens := p.collectTokens ∘ q.collectTokens,
collectKinds := p.collectKinds ∘ q.collectKinds,
firstTokens := p.firstTokens.merge q.firstTokens
}
/--
Run `p`, falling back to `q` if `p` failed without consuming any input.
NOTE: In order for the pretty printer to retrace an `orelse`, `p` must be a call to `node` or some other parser
producing a single node kind. Nested `orelse` calls are flattened for this, i.e. `(node k1 p1 <|> node k2 p2) <|> ...`
is fine as well. -/
@[inline] def orelse (p q : Parser) : Parser := {
info := orelseInfo p.info q.info,
fn := orelseFn p.fn q.fn
}
instance : OrElse Parser where
orElse a b := orelse a (b ())
@[noinline] def noFirstTokenInfo (info : ParserInfo) : ParserInfo := {
collectTokens := info.collectTokens,
collectKinds := info.collectKinds
}
def atomicFn (p : ParserFn) : ParserFn := fun c s =>
let iniPos := s.pos
match p c s with
| ⟨stack, lhsPrec, _, cache, some msg⟩ => ⟨stack, lhsPrec, iniPos, cache, some msg⟩
| other => other
@[inline] def atomic (p : Parser) : Parser := {
info := p.info,
fn := atomicFn p.fn
}
def optionalFn (p : ParserFn) : ParserFn := fun c s =>
let iniSz := s.stackSize
let iniPos := s.pos
let s := p c s
let s := if s.hasError && s.pos == iniPos then s.restore iniSz iniPos else s
s.mkNode nullKind iniSz
@[noinline] def optionaInfo (p : ParserInfo) : ParserInfo := {
collectTokens := p.collectTokens,
collectKinds := p.collectKinds,
firstTokens := p.firstTokens.toOptional
}
@[inline] def optionalNoAntiquot (p : Parser) : Parser := {
info := optionaInfo p.info,
fn := optionalFn p.fn
}
def lookaheadFn (p : ParserFn) : ParserFn := fun c s =>
let iniSz := s.stackSize
let iniPos := s.pos
let s := p c s
if s.hasError then s else s.restore iniSz iniPos
@[inline] def lookahead (p : Parser) : Parser := {
info := p.info,
fn := lookaheadFn p.fn
}
def notFollowedByFn (p : ParserFn) (msg : String) : ParserFn := fun c s =>
let iniSz := s.stackSize
let iniPos := s.pos
let s := p c s
if s.hasError then
s.restore iniSz iniPos
else
let s := s.restore iniSz iniPos
s.mkUnexpectedError s!"unexpected {msg}"
@[inline] def notFollowedBy (p : Parser) (msg : String) : Parser := {
fn := notFollowedByFn p.fn msg
}
partial def manyAux (p : ParserFn) : ParserFn := fun c s => Id.run do
let iniSz := s.stackSize
let iniPos := s.pos
let mut s := p c s
if s.hasError then
return if iniPos == s.pos then s.restore iniSz iniPos else s
if iniPos == s.pos then
return s.mkUnexpectedError "invalid 'many' parser combinator application, parser did not consume anything"
if s.stackSize > iniSz + 1 then
s := s.mkNode nullKind iniSz
manyAux p c s
@[inline] def manyFn (p : ParserFn) : ParserFn := fun c s =>
let iniSz := s.stackSize
let s := manyAux p c s
s.mkNode nullKind iniSz
@[inline] def manyNoAntiquot (p : Parser) : Parser := {
info := noFirstTokenInfo p.info,
fn := manyFn p.fn
}
@[inline] def many1Fn (p : ParserFn) : ParserFn := fun c s =>
let iniSz := s.stackSize
let s := andthenFn p (manyAux p) c s
s.mkNode nullKind iniSz
@[inline] def many1NoAntiquot (p : Parser) : Parser := {
info := p.info,
fn := many1Fn p.fn
}
private partial def sepByFnAux (p : ParserFn) (sep : ParserFn) (allowTrailingSep : Bool) (iniSz : Nat) (pOpt : Bool) : ParserFn :=
let rec parse (pOpt : Bool) (c s) := Id.run do
let sz := s.stackSize
let pos := s.pos
let mut s := p c s
if s.hasError then
if s.pos > pos then
return s.mkNode nullKind iniSz
else if pOpt then
s := s.restore sz pos
return s.mkNode nullKind iniSz
else
-- append `Syntax.missing` to make clear that List is incomplete
s := s.pushSyntax Syntax.missing
return s.mkNode nullKind iniSz
if s.stackSize > sz + 1 then
s := s.mkNode nullKind sz
let sz := s.stackSize
let pos := s.pos
s := sep c s
if s.hasError then
s := s.restore sz pos
return s.mkNode nullKind iniSz
if s.stackSize > sz + 1 then
s := s.mkNode nullKind sz
parse allowTrailingSep c s
parse pOpt
def sepByFn (allowTrailingSep : Bool) (p : ParserFn) (sep : ParserFn) : ParserFn := fun c s =>
let iniSz := s.stackSize
sepByFnAux p sep allowTrailingSep iniSz true c s
def sepBy1Fn (allowTrailingSep : Bool) (p : ParserFn) (sep : ParserFn) : ParserFn := fun c s =>
let iniSz := s.stackSize
sepByFnAux p sep allowTrailingSep iniSz false c s
@[noinline] def sepByInfo (p sep : ParserInfo) : ParserInfo := {
collectTokens := p.collectTokens ∘ sep.collectTokens,
collectKinds := p.collectKinds ∘ sep.collectKinds
}
@[noinline] def sepBy1Info (p sep : ParserInfo) : ParserInfo := {
collectTokens := p.collectTokens ∘ sep.collectTokens,
collectKinds := p.collectKinds ∘ sep.collectKinds,
firstTokens := p.firstTokens
}
@[inline] def sepByNoAntiquot (p sep : Parser) (allowTrailingSep : Bool := false) : Parser := {
info := sepByInfo p.info sep.info,
fn := sepByFn allowTrailingSep p.fn sep.fn
}
@[inline] def sepBy1NoAntiquot (p sep : Parser) (allowTrailingSep : Bool := false) : Parser := {
info := sepBy1Info p.info sep.info,
fn := sepBy1Fn allowTrailingSep p.fn sep.fn
}
/-- Apply `f` to the syntax object produced by `p` -/
def withResultOfFn (p : ParserFn) (f : Syntax → Syntax) : ParserFn := fun c s =>
let s := p c s
if s.hasError then s
else
let stx := s.stxStack.back
s.popSyntax.pushSyntax (f stx)
@[noinline] def withResultOfInfo (p : ParserInfo) : ParserInfo := {
collectTokens := p.collectTokens,
collectKinds := p.collectKinds
}
@[inline] def withResultOf (p : Parser) (f : Syntax → Syntax) : Parser := {
info := withResultOfInfo p.info,
fn := withResultOfFn p.fn f
}
@[inline] def many1Unbox (p : Parser) : Parser :=
withResultOf (many1NoAntiquot p) fun stx => if stx.getNumArgs == 1 then stx.getArg 0 else stx
partial def satisfyFn (p : Char → Bool) (errorMsg : String := "unexpected character") : ParserFn := fun c s =>
let i := s.pos
if c.input.atEnd i then s.mkEOIError
else if p (c.input.get i) then s.next c.input i
else s.mkUnexpectedError errorMsg
partial def takeUntilFn (p : Char → Bool) : ParserFn := fun c s =>
let i := s.pos
if c.input.atEnd i then s
else if p (c.input.get i) then s
else takeUntilFn p c (s.next c.input i)
def takeWhileFn (p : Char → Bool) : ParserFn :=
takeUntilFn (fun c => !p c)
@[inline] def takeWhile1Fn (p : Char → Bool) (errorMsg : String) : ParserFn :=
andthenFn (satisfyFn p errorMsg) (takeWhileFn p)
partial def finishCommentBlock (nesting : Nat) : ParserFn := fun c s =>
let input := c.input
let i := s.pos
if input.atEnd i then eoi s
else
let curr := input.get i
let i := input.next i
if curr == '-' then
if input.atEnd i then eoi s
else
let curr := input.get i
if curr == '/' then -- "-/" end of comment
if nesting == 1 then s.next input i
else finishCommentBlock (nesting-1) c (s.next input i)
else
finishCommentBlock nesting c (s.next input i)
else if curr == '/' then
if input.atEnd i then eoi s
else
let curr := input.get i
if curr == '-' then finishCommentBlock (nesting+1) c (s.next input i)
else finishCommentBlock nesting c (s.setPos i)
else finishCommentBlock nesting c (s.setPos i)
where
eoi s := s.mkUnexpectedError "unterminated comment"
/-- Consume whitespace and comments -/
partial def whitespace : ParserFn := fun c s =>
let input := c.input
let i := s.pos
if input.atEnd i then s
else
let curr := input.get i
if curr == '\t' then
s.mkUnexpectedError "tabs are not allowed; please configure your editor to expand them"
else if curr.isWhitespace then whitespace c (s.next input i)
else if curr == '-' then
let i := input.next i
let curr := input.get i
if curr == '-' then andthenFn (takeUntilFn (fun c => c = '\n')) whitespace c (s.next input i)
else s
else if curr == '/' then
let i := input.next i
let curr := input.get i
if curr == '-' then
let i := input.next i
let curr := input.get i
if curr == '-' || curr == '!' then s -- "/--" and "/-!" doc comment are actual tokens
else andthenFn (finishCommentBlock 1) whitespace c (s.next input i)
else s
else s
def mkEmptySubstringAt (s : String) (p : String.Pos) : Substring :=
{ str := s, startPos := p, stopPos := p }
private def rawAux (startPos : String.Pos) (trailingWs : Bool) : ParserFn := fun c s =>
let input := c.input
let stopPos := s.pos
let leading := mkEmptySubstringAt input startPos
let val := input.extract startPos stopPos
if trailingWs then
let s := whitespace c s
let stopPos' := s.pos
let trailing := { str := input, startPos := stopPos, stopPos := stopPos' : Substring }
let atom := mkAtom (SourceInfo.original leading startPos trailing (startPos + val)) val
s.pushSyntax atom
else
let trailing := mkEmptySubstringAt input stopPos
let atom := mkAtom (SourceInfo.original leading startPos trailing (startPos + val)) val
s.pushSyntax atom
/-- Match an arbitrary Parser and return the consumed String in a `Syntax.atom`. -/
@[inline] def rawFn (p : ParserFn) (trailingWs := false) : ParserFn := fun c s =>
let startPos := s.pos
let s := p c s
if s.hasError then s else rawAux startPos trailingWs c s
@[inline] def chFn (c : Char) (trailingWs := false) : ParserFn :=
rawFn (satisfyFn (fun d => c == d) ("'" ++ toString c ++ "'")) trailingWs
def rawCh (c : Char) (trailingWs := false) : Parser :=
{ fn := chFn c trailingWs }
def hexDigitFn : ParserFn := fun c s =>
let input := c.input
let i := s.pos
if input.atEnd i then s.mkEOIError
else
let curr := input.get i
let i := input.next i
if curr.isDigit || ('a' <= curr && curr <= 'f') || ('A' <= curr && curr <= 'F') then s.setPos i
else s.mkUnexpectedError "invalid hexadecimal numeral"
def quotedCharCoreFn (isQuotable : Char → Bool) : ParserFn := fun c s =>
let input := c.input
let i := s.pos
if input.atEnd i then s.mkEOIError
else
let curr := input.get i
if isQuotable curr then
s.next input i
else if curr == 'x' then
andthenFn hexDigitFn hexDigitFn c (s.next input i)
else if curr == 'u' then
andthenFn hexDigitFn (andthenFn hexDigitFn (andthenFn hexDigitFn hexDigitFn)) c (s.next input i)
else
s.mkUnexpectedError "invalid escape sequence"
def isQuotableCharDefault (c : Char) : Bool :=
c == '\\' || c == '\"' || c == '\'' || c == 'r' || c == 'n' || c == 't'
def quotedCharFn : ParserFn :=
quotedCharCoreFn isQuotableCharDefault
/-- Push `(Syntax.node tk <new-atom>)` into syntax stack -/
def mkNodeToken (n : SyntaxNodeKind) (startPos : String.Pos) : ParserFn := fun c s =>
let input := c.input
let stopPos := s.pos
let leading := mkEmptySubstringAt input startPos
let val := input.extract startPos stopPos
let s := whitespace c s
let wsStopPos := s.pos
let trailing := { str := input, startPos := stopPos, stopPos := wsStopPos : Substring }
let info := SourceInfo.original leading startPos trailing stopPos
s.pushSyntax (Syntax.mkLit n val info)
def charLitFnAux (startPos : String.Pos) : ParserFn := fun c s =>
let input := c.input
let i := s.pos
if input.atEnd i then s.mkEOIError
else
let curr := input.get i
let s := s.setPos (input.next i)
let s := if curr == '\\' then quotedCharFn c s else s
if s.hasError then s
else
let i := s.pos
let curr := input.get i
let s := s.setPos (input.next i)
if curr == '\'' then mkNodeToken charLitKind startPos c s
else s.mkUnexpectedError "missing end of character literal"
partial def strLitFnAux (startPos : String.Pos) : ParserFn := fun c s =>
let input := c.input
let i := s.pos
if input.atEnd i then s.mkUnexpectedErrorAt "unterminated string literal" startPos
else
let curr := input.get i
let s := s.setPos (input.next i)
if curr == '\"' then
mkNodeToken strLitKind startPos c s
else if curr == '\\' then andthenFn quotedCharFn (strLitFnAux startPos) c s
else strLitFnAux startPos c s
def decimalNumberFn (startPos : String.Pos) (c : ParserContext) : ParserState → ParserState := fun s =>
let s := takeWhileFn (fun c => c.isDigit) c s
let input := c.input
let i := s.pos
let curr := input.get i
if curr == '.' || curr == 'e' || curr == 'E' then
let s := parseOptDot s
let s := parseOptExp s
mkNodeToken scientificLitKind startPos c s
else
mkNodeToken numLitKind startPos c s
where
parseOptDot s :=
let input := c.input
let i := s.pos
let curr := input.get i
if curr == '.' then
let i := input.next i
let curr := input.get i
if curr.isDigit then
takeWhileFn (fun c => c.isDigit) c (s.setPos i)
else
s.setPos i
else
s
parseOptExp s :=
let input := c.input
let i := s.pos
let curr := input.get i
if curr == 'e' || curr == 'E' then
let i := input.next i
let i := if input.get i == '-' then input.next i else i
let curr := input.get i
if curr.isDigit then
takeWhileFn (fun c => c.isDigit) c (s.setPos i)
else
s.setPos i
else
s
def binNumberFn (startPos : String.Pos) : ParserFn := fun c s =>
let s := takeWhile1Fn (fun c => c == '0' || c == '1') "binary number" c s
mkNodeToken numLitKind startPos c s
def octalNumberFn (startPos : String.Pos) : ParserFn := fun c s =>
let s := takeWhile1Fn (fun c => '0' ≤ c && c ≤ '7') "octal number" c s
mkNodeToken numLitKind startPos c s
def hexNumberFn (startPos : String.Pos) : ParserFn := fun c s =>
let s := takeWhile1Fn (fun c => ('0' ≤ c && c ≤ '9') || ('a' ≤ c && c ≤ 'f') || ('A' ≤ c && c ≤ 'F')) "hexadecimal number" c s
mkNodeToken numLitKind startPos c s
def numberFnAux : ParserFn := fun c s =>
let input := c.input
let startPos := s.pos
if input.atEnd startPos then s.mkEOIError
else
let curr := input.get startPos
if curr == '0' then
let i := input.next startPos
let curr := input.get i
if curr == 'b' || curr == 'B' then
binNumberFn startPos c (s.next input i)
else if curr == 'o' || curr == 'O' then
octalNumberFn startPos c (s.next input i)
else if curr == 'x' || curr == 'X' then
hexNumberFn startPos c (s.next input i)
else
decimalNumberFn startPos c (s.setPos i)
else if curr.isDigit then
decimalNumberFn startPos c (s.next input startPos)
else
s.mkError "numeral"
def isIdCont : String → ParserState → Bool := fun input s =>
let i := s.pos
let curr := input.get i
if curr == '.' then
let i := input.next i
if input.atEnd i then
false
else
let curr := input.get i
isIdFirst curr || isIdBeginEscape curr
else
false
private def isToken (idStartPos idStopPos : String.Pos) (tk : Option Token) : Bool :=
match tk with
| none => false
| some tk =>
-- if a token is both a symbol and a valid identifier (i.e. a keyword),
-- we want it to be recognized as a symbol
tk.endPos ≥ idStopPos - idStartPos
def mkTokenAndFixPos (startPos : String.Pos) (tk : Option Token) : ParserFn := fun c s =>
match tk with
| none => s.mkErrorAt "token" startPos
| some tk =>
if c.forbiddenTk? == some tk then
s.mkErrorAt "forbidden token" startPos
else
let input := c.input
let leading := mkEmptySubstringAt input startPos
let stopPos := startPos + tk
let s := s.setPos stopPos
let s := whitespace c s
let wsStopPos := s.pos
let trailing := { str := input, startPos := stopPos, stopPos := wsStopPos : Substring }
let atom := mkAtom (SourceInfo.original leading startPos trailing stopPos) tk
s.pushSyntax atom
def mkIdResult (startPos : String.Pos) (tk : Option Token) (val : Name) : ParserFn := fun c s =>
let stopPos := s.pos
if isToken startPos stopPos tk then
mkTokenAndFixPos startPos tk c s
else
let input := c.input
let rawVal := { str := input, startPos := startPos, stopPos := stopPos : Substring }
let s := whitespace c s
let trailingStopPos := s.pos
let leading := mkEmptySubstringAt input startPos
let trailing := { str := input, startPos := stopPos, stopPos := trailingStopPos : Substring }
let info := SourceInfo.original leading startPos trailing stopPos
let atom := mkIdent info rawVal val
s.pushSyntax atom
partial def identFnAux (startPos : String.Pos) (tk : Option Token) (r : Name) : ParserFn :=
let rec parse (r : Name) (c s) := Id.run do
let input := c.input
let i := s.pos
if input.atEnd i then
return s.mkEOIError
let curr := input.get i
if isIdBeginEscape curr then
let startPart := input.next i
let s := takeUntilFn isIdEndEscape c (s.setPos startPart)
if input.atEnd s.pos then
return s.mkUnexpectedErrorAt "unterminated identifier escape" startPart
let stopPart := s.pos
let s := s.next c.input s.pos
let r := Name.mkStr r (input.extract startPart stopPart)
if isIdCont input s then
let s := s.next input s.pos
parse r c s
else
mkIdResult startPos tk r c s
else if isIdFirst curr then
let startPart := i
let s := takeWhileFn isIdRest c (s.next input i)
let stopPart := s.pos
let r := Name.mkStr r (input.extract startPart stopPart)
if isIdCont input s then
let s := s.next input s.pos
parse r c s
else
mkIdResult startPos tk r c s
else
mkTokenAndFixPos startPos tk c s
parse r
private def isIdFirstOrBeginEscape (c : Char) : Bool :=
isIdFirst c || isIdBeginEscape c
private def nameLitAux (startPos : String.Pos) : ParserFn := fun c s =>
let input := c.input
let s := identFnAux startPos none Name.anonymous c (s.next input startPos)
if s.hasError then
s
else
let stx := s.stxStack.back
match stx with
| Syntax.ident info rawStr _ _ =>
let s := s.popSyntax
s.pushSyntax (Syntax.mkNameLit rawStr.toString info)
| _ => s.mkError "invalid Name literal"
private def tokenFnAux : ParserFn := fun c s =>
let input := c.input
let i := s.pos
let curr := input.get i
if curr == '\"' then
strLitFnAux i c (s.next input i)
else if curr == '\'' then
charLitFnAux i c (s.next input i)
else if curr.isDigit then
numberFnAux c s
else if curr == '`' && isIdFirstOrBeginEscape (getNext input i) then
nameLitAux i c s
else
let (_, tk) := c.tokens.matchPrefix input i
identFnAux i tk Name.anonymous c s
private def updateCache (startPos : String.Pos) (s : ParserState) : ParserState :=
-- do not cache token parsing errors, which are rare and usually fatal and thus not worth an extra field in `TokenCache`
match s with
| ⟨stack, lhsPrec, pos, _, none⟩ =>
if stack.size == 0 then s
else
let tk := stack.back
⟨stack, lhsPrec, pos, { tokenCache := { startPos := startPos, stopPos := pos, token := tk } }, none⟩
| other => other
def tokenFn (expected : List String := []) : ParserFn := fun c s =>
let input := c.input
let i := s.pos
if input.atEnd i then s.mkEOIError expected
else
let tkc := s.cache.tokenCache
if tkc.startPos == i then
let s := s.pushSyntax tkc.token
s.setPos tkc.stopPos
else
let s := tokenFnAux c s
updateCache i s
def peekTokenAux (c : ParserContext) (s : ParserState) : ParserState × Except ParserState Syntax :=
let iniSz := s.stackSize
let iniPos := s.pos
let s := tokenFn [] c s
if let some _ := s.errorMsg then (s.restore iniSz iniPos, Except.error s)
else
let stx := s.stxStack.back
(s.restore iniSz iniPos, Except.ok stx)
def peekToken (c : ParserContext) (s : ParserState) : ParserState × Except ParserState Syntax :=
let tkc := s.cache.tokenCache
if tkc.startPos == s.pos then
(s, Except.ok tkc.token)
else
peekTokenAux c s
/-- Treat keywords as identifiers. -/
def rawIdentFn : ParserFn := fun c s =>
let input := c.input
let i := s.pos
if input.atEnd i then s.mkEOIError
else identFnAux i none Name.anonymous c s
@[inline] def satisfySymbolFn (p : String → Bool) (expected : List String) : ParserFn := fun c s =>
let initStackSz := s.stackSize
let startPos := s.pos
let s := tokenFn expected c s
if s.hasError then
s
else
match s.stxStack.back with
| Syntax.atom _ sym => if p sym then s else s.mkErrorsAt expected startPos initStackSz
| _ => s.mkErrorsAt expected startPos initStackSz
def symbolFnAux (sym : String) (errorMsg : String) : ParserFn :=
satisfySymbolFn (fun s => s == sym) [errorMsg]
def symbolInfo (sym : String) : ParserInfo := {
collectTokens := fun tks => sym :: tks,
firstTokens := FirstTokens.tokens [ sym ]
}
@[inline] def symbolFn (sym : String) : ParserFn :=
symbolFnAux sym ("'" ++ sym ++ "'")
@[inline] def symbolNoAntiquot (sym : String) : Parser :=
let sym := sym.trim
{ info := symbolInfo sym,
fn := symbolFn sym }
def checkTailNoWs (prev : Syntax) : Bool :=
match prev.getTailInfo with
| SourceInfo.original _ _ trailing _ => trailing.stopPos == trailing.startPos
| _ => false
/-- Check if the following token is the symbol _or_ identifier `sym`. Useful for
parsing local tokens that have not been added to the token table (but may have
been so by some unrelated code).
For example, the universe `max` Function is parsed using this combinator so that
it can still be used as an identifier outside of universe (but registering it
as a token in a Term Syntax would not break the universe Parser). -/
def nonReservedSymbolFnAux (sym : String) (errorMsg : String) : ParserFn := fun c s =>
let initStackSz := s.stackSize
let startPos := s.pos
let s := tokenFn [errorMsg] c s
if s.hasError then s
else
match s.stxStack.back with
| Syntax.atom _ sym' =>
if sym == sym' then s else s.mkErrorAt errorMsg startPos initStackSz
| Syntax.ident info rawVal _ _ =>
if sym == rawVal.toString then
let s := s.popSyntax
s.pushSyntax (Syntax.atom info sym)
else
s.mkErrorAt errorMsg startPos initStackSz
| _ => s.mkErrorAt errorMsg startPos initStackSz
@[inline] def nonReservedSymbolFn (sym : String) : ParserFn :=
nonReservedSymbolFnAux sym ("'" ++ sym ++ "'")
def nonReservedSymbolInfo (sym : String) (includeIdent : Bool) : ParserInfo := {
firstTokens :=
if includeIdent then
FirstTokens.tokens [ sym, "ident" ]
else
FirstTokens.tokens [ sym ]
}
@[inline] def nonReservedSymbolNoAntiquot (sym : String) (includeIdent := false) : Parser :=
let sym := sym.trim
{ info := nonReservedSymbolInfo sym includeIdent,
fn := nonReservedSymbolFn sym }
partial def strAux (sym : String) (errorMsg : String) (j : String.Pos) :ParserFn :=
let rec parse (j c s) :=
if sym.atEnd j then s
else
let i := s.pos
let input := c.input
if input.atEnd i || sym.get j != input.get i then s.mkError errorMsg
else parse (sym.next j) c (s.next input i)
parse j
def checkTailWs (prev : Syntax) : Bool :=
match prev.getTailInfo with
| SourceInfo.original _ _ trailing _ => trailing.stopPos > trailing.startPos
| _ => false
def checkWsBeforeFn (errorMsg : String) : ParserFn := fun _ s =>
let prev := s.stxStack.back
if checkTailWs prev then s else s.mkError errorMsg
def checkWsBefore (errorMsg : String := "space before") : Parser := {
info := epsilonInfo,
fn := checkWsBeforeFn errorMsg
}
def checkTailLinebreak (prev : Syntax) : Bool :=
match prev.getTailInfo with
| SourceInfo.original _ _ trailing _ => trailing.contains '\n'
| _ => false
def checkLinebreakBeforeFn (errorMsg : String) : ParserFn := fun _ s =>
let prev := s.stxStack.back
if checkTailLinebreak prev then s else s.mkError errorMsg
def checkLinebreakBefore (errorMsg : String := "line break") : Parser := {
info := epsilonInfo
fn := checkLinebreakBeforeFn errorMsg
}
private def pickNonNone (stack : Array Syntax) : Syntax :=
match stack.findRev? fun stx => !stx.isNone with
| none => Syntax.missing
| some stx => stx
def checkNoWsBeforeFn (errorMsg : String) : ParserFn := fun _ s =>
let prev := pickNonNone s.stxStack
if checkTailNoWs prev then s else s.mkError errorMsg
def checkNoWsBefore (errorMsg : String := "no space before") : Parser := {
info := epsilonInfo,
fn := checkNoWsBeforeFn errorMsg
}
def unicodeSymbolFnAux (sym asciiSym : String) (expected : List String) : ParserFn :=
satisfySymbolFn (fun s => s == sym || s == asciiSym) expected
def unicodeSymbolInfo (sym asciiSym : String) : ParserInfo := {
collectTokens := fun tks => sym :: asciiSym :: tks,
firstTokens := FirstTokens.tokens [ sym, asciiSym ]
}
@[inline] def unicodeSymbolFn (sym asciiSym : String) : ParserFn :=
unicodeSymbolFnAux sym asciiSym ["'" ++ sym ++ "', '" ++ asciiSym ++ "'"]
@[inline] def unicodeSymbolNoAntiquot (sym asciiSym : String) : Parser :=
let sym := sym.trim
let asciiSym := asciiSym.trim
{ info := unicodeSymbolInfo sym asciiSym,
fn := unicodeSymbolFn sym asciiSym }
def mkAtomicInfo (k : String) : ParserInfo :=
{ firstTokens := FirstTokens.tokens [ k ] }
def numLitFn : ParserFn :=
fun c s =>
let initStackSz := s.stackSize
let iniPos := s.pos
let s := tokenFn ["numeral"] c s
if !s.hasError && !(s.stxStack.back.isOfKind numLitKind) then s.mkErrorAt "numeral" iniPos initStackSz else s
@[inline] def numLitNoAntiquot : Parser := {
fn := numLitFn,
info := mkAtomicInfo "num"
}
def scientificLitFn : ParserFn :=
fun c s =>
let initStackSz := s.stackSize
let iniPos := s.pos
let s := tokenFn ["scientific number"] c s
if !s.hasError && !(s.stxStack.back.isOfKind scientificLitKind) then s.mkErrorAt "scientific number" iniPos initStackSz else s
@[inline] def scientificLitNoAntiquot : Parser := {
fn := scientificLitFn,
info := mkAtomicInfo "scientific"
}
def strLitFn : ParserFn := fun c s =>
let initStackSz := s.stackSize
let iniPos := s.pos
let s := tokenFn ["string literal"] c s
if !s.hasError && !(s.stxStack.back.isOfKind strLitKind) then s.mkErrorAt "string literal" iniPos initStackSz else s
@[inline] def strLitNoAntiquot : Parser := {
fn := strLitFn,
info := mkAtomicInfo "str"
}
def charLitFn : ParserFn := fun c s =>
let initStackSz := s.stackSize
let iniPos := s.pos
let s := tokenFn ["char literal"] c s
if !s.hasError && !(s.stxStack.back.isOfKind charLitKind) then s.mkErrorAt "character literal" iniPos initStackSz else s
@[inline] def charLitNoAntiquot : Parser := {
fn := charLitFn,
info := mkAtomicInfo "char"
}
def nameLitFn : ParserFn := fun c s =>
let initStackSz := s.stackSize
let iniPos := s.pos
let s := tokenFn ["Name literal"] c s
if !s.hasError && !(s.stxStack.back.isOfKind nameLitKind) then s.mkErrorAt "Name literal" iniPos initStackSz else s
@[inline] def nameLitNoAntiquot : Parser := {
fn := nameLitFn,
info := mkAtomicInfo "name"
}
def identFn : ParserFn := fun c s =>
let initStackSz := s.stackSize
let iniPos := s.pos
let s := tokenFn ["identifier"] c s
if !s.hasError && !(s.stxStack.back.isIdent) then s.mkErrorAt "identifier" iniPos initStackSz else s
@[inline] def identNoAntiquot : Parser := {
fn := identFn,
info := mkAtomicInfo "ident"
}
@[inline] def rawIdentNoAntiquot : Parser := {
fn := rawIdentFn
}
def identEqFn (id : Name) : ParserFn := fun c s =>
let initStackSz := s.stackSize
let iniPos := s.pos
let s := tokenFn ["identifier"] c s
if s.hasError then
s
else match s.stxStack.back with
| Syntax.ident _ _ val _ => if val != id then s.mkErrorAt ("expected identifier '" ++ toString id ++ "'") iniPos initStackSz else s
| _ => s.mkErrorAt "identifier" iniPos initStackSz
@[inline] def identEq (id : Name) : Parser := {
fn := identEqFn id,
info := mkAtomicInfo "ident"
}
namespace ParserState
def keepTop (s : Array Syntax) (startStackSize : Nat) : Array Syntax :=
let node := s.back
s.shrink startStackSize |>.push node
def keepNewError (s : ParserState) (oldStackSize : Nat) : ParserState :=
match s with
| ⟨stack, lhsPrec, pos, cache, err⟩ => ⟨keepTop stack oldStackSize, lhsPrec, pos, cache, err⟩
def keepPrevError (s : ParserState) (oldStackSize : Nat) (oldStopPos : String.Pos) (oldError : Option Error) : ParserState :=
match s with
| ⟨stack, lhsPrec, _, cache, _⟩ => ⟨stack.shrink oldStackSize, lhsPrec, oldStopPos, cache, oldError⟩
def mergeErrors (s : ParserState) (oldStackSize : Nat) (oldError : Error) : ParserState :=
match s with
| ⟨stack, lhsPrec, pos, cache, some err⟩ =>
if oldError == err then s
else ⟨stack.shrink oldStackSize, lhsPrec, pos, cache, some (oldError.merge err)⟩
| other => other
def keepLatest (s : ParserState) (startStackSize : Nat) : ParserState :=
match s with
| ⟨stack, lhsPrec, pos, cache, _⟩ => ⟨keepTop stack startStackSize, lhsPrec, pos, cache, none⟩
def replaceLongest (s : ParserState) (startStackSize : Nat) : ParserState :=
s.keepLatest startStackSize
end ParserState
def invalidLongestMatchParser (s : ParserState) : ParserState :=
s.mkError "longestMatch parsers must generate exactly one Syntax node"
/--
Auxiliary function used to execute parsers provided to `longestMatchFn`.
Push `left?` into the stack if it is not `none`, and execute `p`.
Remark: `p` must produce exactly one syntax node.
Remark: the `left?` is not none when we are processing trailing parsers. -/
def runLongestMatchParser (left? : Option Syntax) (startLhsPrec : Nat) (p : ParserFn) : ParserFn := fun c s => Id.run do
/-
We assume any registered parser `p` has one of two forms:
* a direct call to `leadingParser` or `trailingParser`
* a direct call to a (leading) token parser
In the first case, we can extract the precedence of the parser by having `leadingParser/trailingParser`
set `ParserState.lhsPrec` to it in the very end so that no nested parser can interfere.
In the second case, the precedence is effectively `max` (there is a `checkPrec` merely for the convenience
of the pretty printer) and there are no nested `leadingParser/trailingParser` calls, so the value of `lhsPrec`
will not be changed by the parser (nor will it be read by any leading parser). Thus we initialize the field
to `maxPrec` in the leading case. -/
let mut s := { s with lhsPrec := if left?.isSome then startLhsPrec else maxPrec }
let startSize := s.stackSize
if let some left := left? then
s := s.pushSyntax left
s := p c s
-- stack contains `[..., result ]`
if s.stackSize == startSize + 1 then
s -- success or error with the expected number of nodes
else if s.hasError then
-- error with an unexpected number of nodes.
s.shrinkStack startSize |>.pushSyntax Syntax.missing
else
-- parser succeded with incorrect number of nodes
invalidLongestMatchParser s
def longestMatchStep (left? : Option Syntax) (startSize startLhsPrec : Nat) (startPos : String.Pos) (prevPrio : Nat) (prio : Nat) (p : ParserFn)
: ParserContext → ParserState → ParserState × Nat := fun c s =>
let prevErrorMsg := s.errorMsg
let prevStopPos := s.pos
let prevSize := s.stackSize
let prevLhsPrec := s.lhsPrec
let s := s.restore prevSize startPos
let s := runLongestMatchParser left? startLhsPrec p c s
match prevErrorMsg, s.errorMsg with
| none, none => -- both succeeded
if s.pos > prevStopPos || (s.pos == prevStopPos && prio > prevPrio) then (s.replaceLongest startSize, prio)
else if s.pos < prevStopPos || (s.pos == prevStopPos && prio < prevPrio) then ({ s.restore prevSize prevStopPos with lhsPrec := prevLhsPrec }, prevPrio) -- keep prev
-- it is not clear what the precedence of a choice node should be, so we conservatively take the minimum
else ({s with lhsPrec := s.lhsPrec.min prevLhsPrec }, prio)
| none, some _ => -- prev succeeded, current failed
({ s.restore prevSize prevStopPos with lhsPrec := prevLhsPrec }, prevPrio)
| some oldError, some _ => -- both failed
if s.pos > prevStopPos || (s.pos == prevStopPos && prio > prevPrio) then (s.keepNewError startSize, prio)
else if s.pos < prevStopPos || (s.pos == prevStopPos && prio < prevPrio) then (s.keepPrevError prevSize prevStopPos prevErrorMsg, prevPrio)
else (s.mergeErrors prevSize oldError, prio)
| some _, none => -- prev failed, current succeeded
let successNode := s.stxStack.back
let s := s.shrinkStack startSize -- restore stack to initial size to make sure (failure) nodes are removed from the stack
(s.pushSyntax successNode, prio) -- put successNode back on the stack
def longestMatchMkResult (startSize : Nat) (s : ParserState) : ParserState :=
if s.stackSize > startSize + 1 then s.mkNode choiceKind startSize else s
def longestMatchFnAux (left? : Option Syntax) (startSize startLhsPrec : Nat) (startPos : String.Pos) (prevPrio : Nat) (ps : List (Parser × Nat)) : ParserFn :=
let rec parse (prevPrio : Nat) (ps : List (Parser × Nat)) :=
match ps with
| [] => fun _ s => longestMatchMkResult startSize s
| p::ps => fun c s =>
let (s, prevPrio) := longestMatchStep left? startSize startLhsPrec startPos prevPrio p.2 p.1.fn c s
parse prevPrio ps c s
parse prevPrio ps
def longestMatchFn (left? : Option Syntax) : List (Parser × Nat) → ParserFn
| [] => fun _ s => s.mkError "longestMatch: empty list"
| [p] => fun c s => runLongestMatchParser left? s.lhsPrec p.1.fn c s
| p::ps => fun c s =>
let startSize := s.stackSize
let startLhsPrec := s.lhsPrec
let startPos := s.pos
let s := runLongestMatchParser left? s.lhsPrec p.1.fn c s
longestMatchFnAux left? startSize startLhsPrec startPos p.2 ps c s
def anyOfFn : List Parser → ParserFn
| [], _, s => s.mkError "anyOf: empty list"
| [p], c, s => p.fn c s
| p::ps, c, s => orelseFn p.fn (anyOfFn ps) c s
@[inline] def checkColGeFn (errorMsg : String) : ParserFn := fun c s =>
match c.savedPos? with
| none => s
| some savedPos =>
let savedPos := c.fileMap.toPosition savedPos
let pos := c.fileMap.toPosition s.pos
if pos.column ≥ savedPos.column then s
else s.mkError errorMsg
@[inline] def checkColGe (errorMsg : String := "checkColGe") : Parser :=
{ fn := checkColGeFn errorMsg }
@[inline] def checkColGtFn (errorMsg : String) : ParserFn := fun c s =>
match c.savedPos? with
| none => s
| some savedPos =>
let savedPos := c.fileMap.toPosition savedPos
let pos := c.fileMap.toPosition s.pos
if pos.column > savedPos.column then s
else s.mkError errorMsg
@[inline] def checkColGt (errorMsg : String := "checkColGt") : Parser :=
{ fn := checkColGtFn errorMsg }
@[inline] def checkLineEqFn (errorMsg : String) : ParserFn := fun c s =>
match c.savedPos? with
| none => s
| some savedPos =>
let savedPos := c.fileMap.toPosition savedPos
let pos := c.fileMap.toPosition s.pos
if pos.line == savedPos.line then s
else s.mkError errorMsg
@[inline] def checkLineEq (errorMsg : String := "checkLineEq") : Parser :=
{ fn := checkLineEqFn errorMsg }
@[inline] def withPosition (p : Parser) : Parser := {
info := p.info
fn := fun c s =>
p.fn { c with savedPos? := s.pos } s
}
@[inline] def withPositionAfterLinebreak (p : Parser) : Parser := {
info := p.info
fn := fun c s =>
let prev := s.stxStack.back
let c := if checkTailLinebreak prev then { c with savedPos? := s.pos } else c
p.fn c s
}
@[inline] def withoutPosition (p : Parser) : Parser := {
info := p.info
fn := fun c s => p.fn { c with savedPos? := none } s
}
@[inline] def withForbidden (tk : Token) (p : Parser) : Parser := {
info := p.info
fn := fun c s => p.fn { c with forbiddenTk? := tk } s
}
@[inline] def withoutForbidden (p : Parser) : Parser := {
info := p.info
fn := fun c s => p.fn { c with forbiddenTk? := none } s
}
def eoiFn : ParserFn := fun c s =>
let i := s.pos
if c.input.atEnd i then s
else s.mkError "expected end of file"
@[inline] def eoi : Parser :=
{ fn := eoiFn }
open Std (RBMap RBMap.empty)
/-- A multimap indexed by tokens. Used for indexing parsers by their leading token. -/
def TokenMap (α : Type) := RBMap Name (List α) Name.quickCmp
namespace TokenMap
def insert (map : TokenMap α) (k : Name) (v : α) : TokenMap α :=
match map.find? k with
| none => Std.RBMap.insert map k [v]
| some vs => Std.RBMap.insert map k (v::vs)
instance : Inhabited (TokenMap α) := ⟨RBMap.empty⟩
instance : EmptyCollection (TokenMap α) := ⟨RBMap.empty⟩
instance : ForIn m (TokenMap α) (Name × List α) := inferInstanceAs (ForIn _ (RBMap ..) _)
end TokenMap
structure PrattParsingTables where
leadingTable : TokenMap (Parser × Nat) := {}
leadingParsers : List (Parser × Nat) := [] -- for supporting parsers we cannot obtain first token
trailingTable : TokenMap (Parser × Nat) := {}
trailingParsers : List (Parser × Nat) := [] -- for supporting parsers such as function application
instance : Inhabited PrattParsingTables := ⟨{}⟩
/--
The type `LeadingIdentBehavior` specifies how the parsing table
lookup function behaves for identifiers. The function `prattParser`
uses two tables `leadingTable` and `trailingTable`. They map tokens
to parsers.
We use `LeadingIdentBehavior.symbol` and `LeadingIdentBehavior.both`
and `nonReservedSymbol` parser to implement the `tactic` parsers.
The idea is to avoid creating a reserved symbol for each
builtin tactic (e.g., `apply`, `assumption`, etc.). That is, users
may still use these symbols as identifiers (e.g., naming a
function).
-/
inductive LeadingIdentBehavior where
| /-- `LeadingIdentBehavior.default`: if the leading token
is an identifier, then `prattParser` just executes the parsers
associated with the auxiliary token "ident". -/
default
| /-- `LeadingIdentBehavior.symbol`: if the leading token is
an identifier `<foo>`, and there are parsers `P` associated with
the toek `<foo>`, then it executes `P`. Otherwise, it executes
only the parsers associated with the auxiliary token "ident". -/
symbol
| /-- `LeadingIdentBehavior.both`: if the leading token
an identifier `<foo>`, the it executes the parsers associated
with token `<foo>` and parsers associated with the auxiliary
token "ident". -/
both
deriving Inhabited, BEq, Repr
/--
Each parser category is implemented using a Pratt's parser.
The system comes equipped with the following categories: `level`, `term`, `tactic`, and `command`.
Users and plugins may define extra categories.
The method
```
categoryParser `term prec
```
executes the Pratt's parser for category `term` with precedence `prec`.
That is, only parsers with precedence at least `prec` are considered.
The method `termParser prec` is equivalent to the method above.
-/
structure ParserCategory where
/-- The name of a declaration which will be used as the target of
go-to-definition queries and from which doc strings will be extracted.
This is a dummy declaration of type `Lean.Parser.Category`
created by `declare_syntax_cat`, but for builtin categories the declaration
is made manually and passed to `registerBuiltinParserAttribute`. -/
declName : Name
/-- The list of syntax nodes that can parse into this category.
This can be used to list all syntaxes in the category. -/
kinds : SyntaxNodeKindSet := {}
/-- The parsing tables, which consist of a dynamic set of parser
functions based on the syntaxes that have been declared so far. -/
tables : PrattParsingTables := {}
/-- The `LeadingIdentBehavior`, which specifies how the parsing table
lookup function behaves for the first identifier to be parsed.
This is used by the `tactic` parser to avoid creating a reserved
symbol for each builtin tactic (e.g., `apply`, `assumption`, etc.). -/
behavior : LeadingIdentBehavior
deriving Inhabited
abbrev ParserCategories := Std.PersistentHashMap Name ParserCategory
def indexed {α : Type} (map : TokenMap α) (c : ParserContext) (s : ParserState) (behavior : LeadingIdentBehavior) : ParserState × List α :=
let (s, stx) := peekToken c s
let find (n : Name) : ParserState × List α :=
match map.find? n with
| some as => (s, as)
| _ => (s, [])
match stx with
| Except.ok (Syntax.atom _ sym) => find (Name.mkSimple sym)
| Except.ok (Syntax.ident _ _ val _) =>
match behavior with
| LeadingIdentBehavior.default => find identKind
| LeadingIdentBehavior.symbol =>
match map.find? val with
| some as => (s, as)
| none => find identKind
| LeadingIdentBehavior.both =>
match map.find? val with
| some as =>
if val == identKind then
(s, as) -- avoid running the same parsers twice
else
match map.find? identKind with
| some as' => (s, as ++ as')
| _ => (s, as)
| none => find identKind
| Except.ok (Syntax.node _ k _) => find k
| Except.ok _ => (s, [])
| Except.error s' => (s', [])
abbrev CategoryParserFn := Name → ParserFn
builtin_initialize categoryParserFnRef : IO.Ref CategoryParserFn ← IO.mkRef fun (_ : Name) => whitespace
builtin_initialize categoryParserFnExtension : EnvExtension CategoryParserFn ← registerEnvExtension $ categoryParserFnRef.get
def categoryParserFn (catName : Name) : ParserFn := fun ctx s =>
categoryParserFnExtension.getState ctx.env catName ctx s
def categoryParser (catName : Name) (prec : Nat) : Parser := {
fn := fun c s => categoryParserFn catName { c with prec := prec } s
}
-- Define `termParser` here because we need it for antiquotations
@[inline] def termParser (prec : Nat := 0) : Parser :=
categoryParser `term prec
-- ==================
/-! # Antiquotations -/
-- ==================
/-- Fail if previous token is immediately followed by ':'. -/
def checkNoImmediateColon : Parser := {
fn := fun c s =>
let prev := s.stxStack.back
if checkTailNoWs prev then
let input := c.input
let i := s.pos
if input.atEnd i then s
else
let curr := input.get i
if curr == ':' then
s.mkUnexpectedError "unexpected ':'"
else s
else s
}
def setExpectedFn (expected : List String) (p : ParserFn) : ParserFn := fun c s =>
match p c s with
| s'@{ errorMsg := some msg, .. } => { s' with errorMsg := some { msg with expected } }
| s' => s'
def setExpected (expected : List String) (p : Parser) : Parser :=
{ fn := setExpectedFn expected p.fn, info := p.info }
def pushNone : Parser :=
{ fn := fun _ s => s.pushSyntax mkNullNode }
-- We support three kinds of antiquotations: `$id`, `$_`, and `$(t)`, where `id` is a term identifier and `t` is a term.
def antiquotNestedExpr : Parser := node `antiquotNestedExpr (symbolNoAntiquot "(" >> decQuotDepth termParser >> symbolNoAntiquot ")")
def antiquotExpr : Parser := identNoAntiquot <|> symbolNoAntiquot "_" <|> antiquotNestedExpr
def tokenAntiquotFn : ParserFn := fun c s => Id.run do
if s.hasError then
return s
let iniSz := s.stackSize
let iniPos := s.pos
let s := (checkNoWsBefore >> symbolNoAntiquot "%" >> symbolNoAntiquot "$" >> checkNoWsBefore >> antiquotExpr).fn c s
if s.hasError then
return s.restore iniSz iniPos
s.mkNode (`token_antiquot) (iniSz - 1)
@[inline] def tokenWithAntiquot (p : Parser) : Parser where
fn c s :=
let s := p.fn c s
-- fast check that is false in most cases
if c.input.get s.pos == '%' then
tokenAntiquotFn c s
else
s
info := p.info
@[inline] def symbol (sym : String) : Parser :=
tokenWithAntiquot (symbolNoAntiquot sym)
instance : Coe String Parser := ⟨fun s => symbol s ⟩
@[inline] def nonReservedSymbol (sym : String) (includeIdent := false) : Parser :=
tokenWithAntiquot (nonReservedSymbolNoAntiquot sym includeIdent)
@[inline] def unicodeSymbol (sym asciiSym : String) : Parser :=
tokenWithAntiquot (unicodeSymbolNoAntiquot sym asciiSym)
/--
Define parser for `$e` (if anonymous == true) and `$e:name`.
`kind` is embedded in the antiquotation's kind, and checked at syntax `match` unless `isPseudoKind` is false.
Antiquotations can be escaped as in `$$e`, which produces the syntax tree for `$e`. -/
def mkAntiquot (name : String) (kind : SyntaxNodeKind) (anonymous := true) (isPseudoKind := false) : Parser :=
let kind := kind ++ (if isPseudoKind then `pseudo else Name.anonymous) ++ `antiquot
let nameP := node `antiquotName $ checkNoWsBefore ("no space before ':" ++ name ++ "'") >> symbol ":" >> nonReservedSymbol name
-- if parsing the kind fails and `anonymous` is true, check that we're not ignoring a different
-- antiquotation kind via `noImmediateColon`
let nameP := if anonymous then nameP <|> checkNoImmediateColon >> pushNone else nameP
-- antiquotations are not part of the "standard" syntax, so hide "expected '$'" on error
leadingNode kind maxPrec $ atomic $
setExpected [] "$" >>
manyNoAntiquot (checkNoWsBefore "" >> "$") >>
checkNoWsBefore "no space before spliced term" >> antiquotExpr >>
nameP
@[inline] def withAntiquotFn (antiquotP p : ParserFn) (isCatAntiquot := false) : ParserFn := fun c s =>
-- fast check that is false in most cases
if c.input.get s.pos == '$' then
-- Do not allow antiquotation choice nodes here as `antiquotP` is the strictly more general
-- antiquotation than any in `p`.
-- If it is a category antiquotation, do not backtrack into the category at all as that would
-- run *all* parsers of the category, and trailing parsers will later be applied anyway.
orelseFnCore (antiquotBehavior := if isCatAntiquot then .acceptLhs else .takeLongest) antiquotP p c s
else
p c s
/-- Optimized version of `mkAntiquot ... <|> p`. -/
@[inline] def withAntiquot (antiquotP p : Parser) : Parser := {
fn := withAntiquotFn antiquotP.fn p.fn,
info := orelseInfo antiquotP.info p.info
}
def withoutInfo (p : Parser) : Parser :=
{ fn := p.fn }
/-- Parse `$[p]suffix`, e.g. `$[p],*`. -/
def mkAntiquotSplice (kind : SyntaxNodeKind) (p suffix : Parser) : Parser :=
let kind := kind ++ `antiquot_scope
leadingNode kind maxPrec $ atomic $
setExpected [] "$" >>
manyNoAntiquot (checkNoWsBefore "" >> "$") >>
checkNoWsBefore "no space before spliced term" >> symbol "[" >> node nullKind p >> symbol "]" >>
suffix
private def withAntiquotSuffixSpliceFn (kind : SyntaxNodeKind) (suffix : ParserFn) : ParserFn := fun c s => Id.run do
let iniSz := s.stackSize
let iniPos := s.pos
let s := suffix c s
if s.hasError then
return s.restore iniSz iniPos
s.mkNode (kind ++ `antiquot_suffix_splice) (s.stxStack.size - 2)
/-- Parse `suffix` after an antiquotation, e.g. `$x,*`, and put both into a new node. -/
@[inline] def withAntiquotSuffixSplice (kind : SyntaxNodeKind) (p suffix : Parser) : Parser where
info := andthenInfo p.info suffix.info
fn c s :=
let s := p.fn c s
-- fast check that is false in most cases
if !s.hasError && s.stxStack.back.isAntiquots then
withAntiquotSuffixSpliceFn kind suffix.fn c s
else
s
def withAntiquotSpliceAndSuffix (kind : SyntaxNodeKind) (p suffix : Parser) :=
-- prevent `p`'s info from being collected twice
withAntiquot (mkAntiquotSplice kind (withoutInfo p) suffix) (withAntiquotSuffixSplice kind p suffix)
def nodeWithAntiquot (name : String) (kind : SyntaxNodeKind) (p : Parser) (anonymous := false) : Parser :=
withAntiquot (mkAntiquot name kind anonymous) $ node kind p
-- =========================
/-! # End of Antiquotations -/
-- =========================
def sepByElemParser (p : Parser) (sep : String) : Parser :=
withAntiquotSpliceAndSuffix `sepBy p (symbol (sep.trim ++ "*"))
def sepBy (p : Parser) (sep : String) (psep : Parser := symbol sep) (allowTrailingSep : Bool := false) : Parser :=
sepByNoAntiquot (sepByElemParser p sep) psep allowTrailingSep
def sepBy1 (p : Parser) (sep : String) (psep : Parser := symbol sep) (allowTrailingSep : Bool := false) : Parser :=
sepBy1NoAntiquot (sepByElemParser p sep) psep allowTrailingSep
def categoryParserOfStackFn (offset : Nat) : ParserFn := fun ctx s =>
let stack := s.stxStack
if stack.size < offset + 1 then
s.mkUnexpectedError ("failed to determine parser category using syntax stack, stack is too small")
else
match stack.get! (stack.size - offset - 1) with
| Syntax.ident _ _ catName _ => categoryParserFn catName ctx s
| _ => s.mkUnexpectedError ("failed to determine parser category using syntax stack, the specified element on the stack is not an identifier")
def categoryParserOfStack (offset : Nat) (prec : Nat := 0) : Parser :=
{ fn := fun c s => categoryParserOfStackFn offset { c with prec := prec } s }
private def mkResult (s : ParserState) (iniSz : Nat) : ParserState :=
if s.stackSize == iniSz + 1 then s
else s.mkNode nullKind iniSz -- throw error instead?
def leadingParserAux (kind : Name) (tables : PrattParsingTables) (behavior : LeadingIdentBehavior) : ParserFn := fun c s => Id.run do
let iniSz := s.stackSize
let (s, ps) := indexed tables.leadingTable c s behavior
if s.hasError then
return s
let ps := tables.leadingParsers ++ ps
if ps.isEmpty then
return s.mkError (toString kind)
let s := longestMatchFn none ps c s
mkResult s iniSz
@[inline] def leadingParser (kind : Name) (tables : PrattParsingTables) (behavior : LeadingIdentBehavior) (antiquotParser : ParserFn) : ParserFn :=
withAntiquotFn (isCatAntiquot := true) antiquotParser (leadingParserAux kind tables behavior)
def trailingLoopStep (tables : PrattParsingTables) (left : Syntax) (ps : List (Parser × Nat)) : ParserFn := fun c s =>
longestMatchFn left (ps ++ tables.trailingParsers) c s
partial def trailingLoop (tables : PrattParsingTables) (c : ParserContext) (s : ParserState) : ParserState := Id.run do
let iniSz := s.stackSize
let iniPos := s.pos
let (s, ps) := indexed tables.trailingTable c s LeadingIdentBehavior.default
if s.hasError then
-- Discard token parse errors and break the trailing loop instead.
-- The error will be flagged when the next leading position is parsed, unless the token
-- is in fact valid there (e.g. EOI at command level, no-longer forbidden token)
return s.restore iniSz iniPos
if ps.isEmpty && tables.trailingParsers.isEmpty then
return s -- no available trailing parser
let left := s.stxStack.back
let s := s.popSyntax
let s := trailingLoopStep tables left ps c s
if s.hasError then
-- Discard non-consuming parse errors and break the trailing loop instead, restoring `left`.
-- This is necessary for fallback parsers like `app` that pretend to be always applicable.
return if s.pos == iniPos then s.restore (iniSz - 1) iniPos |>.pushSyntax left else s
trailingLoop tables c s
/--
Implements a variant of Pratt's algorithm. In Pratt's algorithms tokens have a right and left binding power.
In our implementation, parsers have precedence instead. This method selects a parser (or more, via
`longestMatchFn`) from `leadingTable` based on the current token. Note that the unindexed `leadingParsers` parsers
are also tried. We have the unidexed `leadingParsers` because some parsers do not have a "first token". Example:
```
syntax term:51 "≤" ident "<" term "|" term : index
```
Example, in principle, the set of first tokens for this parser is any token that can start a term, but this set
is always changing. Thus, this parsing rule is stored as an unindexed leading parser at `leadingParsers`.
After processing the leading parser, we chain with parsers from `trailingTable`/`trailingParsers` that have precedence
at least `c.prec` where `c` is the `ParsingContext`. Recall that `c.prec` is set by `categoryParser`.
Note that in the original Pratt's algorith, precedences are only checked before calling trailing parsers. In our
implementation, leading *and* trailing parsers check the precendece. We claim our algorithm is more flexible,
modular and easier to understand.
`antiquotParser` should be a `mkAntiquot` parser (or always fail) and is tried before all other parsers.
It should not be added to the regular leading parsers because it would heavily
overlap with antiquotation parsers nested inside them. -/
@[inline] def prattParser (kind : Name) (tables : PrattParsingTables) (behavior : LeadingIdentBehavior) (antiquotParser : ParserFn) : ParserFn := fun c s =>
let s := leadingParser kind tables behavior antiquotParser c s
if s.hasError then
s
else
trailingLoop tables c s
def fieldIdxFn : ParserFn := fun c s =>
let initStackSz := s.stackSize
let iniPos := s.pos
let curr := c.input.get iniPos
if curr.isDigit && curr != '0' then
let s := takeWhileFn (fun c => c.isDigit) c s
mkNodeToken fieldIdxKind iniPos c s
else
s.mkErrorAt "field index" iniPos initStackSz
@[inline] def fieldIdx : Parser :=
withAntiquot (mkAntiquot "fieldIdx" `fieldIdx) {
fn := fieldIdxFn,
info := mkAtomicInfo "fieldIdx"
}
@[inline] def skip : Parser := {
fn := fun _ s => s,
info := epsilonInfo
}
end Parser
namespace Syntax
section
variable {β : Type} {m : Type → Type} [Monad m]
@[inline] def foldArgsM (s : Syntax) (f : Syntax → β → m β) (b : β) : m β :=
s.getArgs.foldlM (flip f) b
@[inline] def foldArgs (s : Syntax) (f : Syntax → β → β) (b : β) : β :=
Id.run (s.foldArgsM f b)
@[inline] def forArgsM (s : Syntax) (f : Syntax → m Unit) : m Unit :=
s.foldArgsM (fun s _ => f s) ()
end
end Syntax
end Lean
|
87bd19b345906ec615ba7929ed562e0882a5788d | 9d2e3d5a2e2342a283affd97eead310c3b528a24 | /src/hints/thursday/afternoon/category_theory/exercise3/hint8.lean | 9d408c281fdfe18940f9f5de3d14772613521656 | [] | 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 | 532 | lean | import for_mathlib.category_theory -- This imports some simp lemmas that I realised belong in mathlib while writing this exercise.
open category_theory
variables {C : Type*} [category C]
variables {D : Type*} [category D]
lemma equiv_preserves_mono {X Y : C} (f : X ⟶ Y) [mono f] (e : C ≌ D) :
mono (e.functor.map f) :=
begin
tidy,
replace w := congr_arg (λ k, e.inverse.map k) w,
simp at w,
rw [←category.assoc, ←category.assoc, cancel_mono f] at w,
-- Should be easy from here? See if `simp` can help.
end
|
98d8e9b27ff657de83897495aa6c800413f7cc95 | 27a31d06bcfc7c5d379fd04a08a9f5ed3f5302d4 | /stage0/src/Init/SimpLemmas.lean | 8e4183f33f3c37562ef12d8eacd452e75e64d868 | [
"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 | joehendrix/lean4 | 0d1486945f7ca9fe225070374338f4f7e74bab03 | 1221bdd3c7d5395baa451ce8fdd2c2f8a00cbc8f | refs/heads/master | 1,640,573,727,861 | 1,639,662,710,000 | 1,639,665,515,000 | 198,893,504 | 0 | 0 | Apache-2.0 | 1,564,084,645,000 | 1,564,084,644,000 | null | UTF-8 | Lean | false | false | 7,097 | lean | /-
Copyright (c) 2021 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
notation, basic datatypes and type classes
-/
prelude
import Init.Core
@[simp] theorem eq_self (a : α) : (a = a) = True :=
propext <| Iff.intro (fun _ => trivial) (fun _ => rfl)
theorem of_eq_true (h : p = True) : p :=
h ▸ trivial
theorem eq_true (h : p) : p = True :=
propext <| Iff.intro (fun _ => trivial) (fun _ => h)
theorem eq_false (h : ¬ p) : p = False :=
propext <| Iff.intro (fun h' => absurd h' h) (fun h' => False.elim h')
theorem eq_false' (h : p → False) : p = False :=
propext <| Iff.intro (fun h' => absurd h' h) (fun h' => False.elim h')
theorem eq_true_of_decide {p : Prop} {s : Decidable p} (h : decide p = true) : p = True :=
propext <| Iff.intro (fun h => trivial) (fun _ => of_decide_eq_true h)
theorem eq_false_of_decide {p : Prop} {s : Decidable p} (h : decide p = false) : p = False :=
propext <| Iff.intro (fun h' => absurd h' (of_decide_eq_false h)) (fun h => False.elim h)
theorem implies_congr {p₁ p₂ : Sort u} {q₁ q₂ : Sort v} (h₁ : p₁ = p₂) (h₂ : q₁ = q₂) : (p₁ → q₁) = (p₂ → q₂) :=
h₁ ▸ h₂ ▸ rfl
theorem implies_congr_ctx {p₁ p₂ q₁ q₂ : Prop} (h₁ : p₁ = p₂) (h₂ : p₂ → q₁ = q₂) : (p₁ → q₁) = (p₂ → q₂) :=
propext <| Iff.intro
(fun h hp₂ =>
have : p₁ := h₁ ▸ hp₂
have : q₁ := h this
h₂ hp₂ ▸ this)
(fun h hp₁ =>
have hp₂ : p₂ := h₁ ▸ hp₁
have : q₂ := h hp₂
h₂ hp₂ ▸ this)
theorem forall_congr {α : Sort u} {p q : α → Prop} (h : ∀ a, (p a = q a)) : (∀ a, p a) = (∀ a, q a) :=
have : p = q := funext h
this ▸ rfl
theorem let_congr {α : Sort u} {β : Sort v} {a a' : α} {b b' : α → β} (h₁ : a = a') (h₂ : ∀ x, b x = b' x) :
(let x := a; b x) = (let x := a'; b' x) := by
subst h₁
have : b = b' := funext h₂
subst this
rfl
theorem let_val_congr {α : Sort u} {β : Sort v} {a a' : α} (b : α → β) (h : a = a') :
(let x := a; b x) = (let x := a'; b x) := by
subst h
rfl
theorem let_body_congr {α : Sort u} {β : α → Sort v} {b b' : (a : α) → β a} (a : α) (h : ∀ x, b x = b' x) :
(let x := a; b x) = (let x := a; b' x) := by
have : b = b' := funext h
subst this
rfl
@[congr]
theorem ite_congr {x y u v : α} {s : Decidable b} [Decidable c] (h₁ : b = c) (h₂ : c → x = u) (h₃ : ¬ c → y = v) : ite b x y = ite c u v := by
cases Decidable.em c with
| inl h => rw [if_pos h]; subst b; rw[if_pos h]; exact h₂ h
| inr h => rw [if_neg h]; subst b; rw[if_neg h]; exact h₃ h
theorem Eq.mpr_prop {p q : Prop} (h₁ : p = q) (h₂ : q) : p :=
h₁ ▸ h₂
theorem Eq.mpr_not {p q : Prop} (h₁ : p = q) (h₂ : ¬q) : ¬p :=
h₁ ▸ h₂
@[congr]
theorem dite_congr {s : Decidable b} [Decidable c]
{x : b → α} {u : c → α} {y : ¬b → α} {v : ¬c → α}
(h₁ : b = c)
(h₂ : (h : c) → x (Eq.mpr_prop h₁ h) = u h)
(h₃ : (h : ¬c) → y (Eq.mpr_not h₁ h) = v h)
: dite b x y = dite c u v := by
cases Decidable.em c with
| inl h => rw [dif_pos h]; subst b; rw [dif_pos h]; exact h₂ h
| inr h => rw [dif_neg h]; subst b; rw [dif_neg h]; exact h₃ h
@[simp] theorem ne_eq (a b : α) : (a ≠ b) = Not (a = b) := rfl
@[simp] theorem ite_true (a b : α) : (if True then a else b) = a := rfl
@[simp] theorem ite_false (a b : α) : (if False then a else b) = b := rfl
@[simp] theorem dite_true {α : Sort u} {t : True → α} {e : ¬ True → α} : (dite True t e) = t True.intro := rfl
@[simp] theorem dite_false {α : Sort u} {t : False → α} {e : ¬ False → α} : (dite False t e) = e not_false := rfl
@[simp] theorem and_self (p : Prop) : (p ∧ p) = p := propext <| Iff.intro (fun h => h.1) (fun h => ⟨h, h⟩)
@[simp] theorem and_true (p : Prop) : (p ∧ True) = p := propext <| Iff.intro (fun h => h.1) (fun h => ⟨h, trivial⟩)
@[simp] theorem true_and (p : Prop) : (True ∧ p) = p := propext <| Iff.intro (fun h => h.2) (fun h => ⟨trivial, h⟩)
@[simp] theorem and_false (p : Prop) : (p ∧ False) = False := propext <| Iff.intro (fun h => h.2) (fun h => False.elim h)
@[simp] theorem false_and (p : Prop) : (False ∧ p) = False := propext <| Iff.intro (fun h => h.1) (fun h => False.elim h)
@[simp] theorem or_self (p : Prop) : (p ∨ p) = p := propext <| Iff.intro (fun | Or.inl h => h | Or.inr h => h) (fun h => Or.inl h)
@[simp] theorem or_true (p : Prop) : (p ∨ True) = True := propext <| Iff.intro (fun h => trivial) (fun h => Or.inr trivial)
@[simp] theorem true_or (p : Prop) : (True ∨ p) = True := propext <| Iff.intro (fun h => trivial) (fun h => Or.inl trivial)
@[simp] theorem or_false (p : Prop) : (p ∨ False) = p := propext <| Iff.intro (fun | Or.inl h => h | Or.inr h => False.elim h) (fun h => Or.inl h)
@[simp] theorem false_or (p : Prop) : (False ∨ p) = p := propext <| Iff.intro (fun | Or.inr h => h | Or.inl h => False.elim h) (fun h => Or.inr h)
@[simp] theorem iff_self (p : Prop) : (p ↔ p) = True := propext <| Iff.intro (fun h => trivial) (fun _ => Iff.intro id id)
@[simp] theorem iff_true (p : Prop) : (p ↔ True) = p := propext <| Iff.intro (fun h => h.mpr trivial) (fun h => Iff.intro (fun _ => trivial) (fun _ => h))
@[simp] theorem true_iff (p : Prop) : (True ↔ p) = p := propext <| Iff.intro (fun h => h.mp trivial) (fun h => Iff.intro (fun _ => h) (fun _ => trivial))
@[simp] theorem iff_false (p : Prop) : (p ↔ False) = ¬p := propext <| Iff.intro (fun h hp => h.mp hp) (fun h => Iff.intro h False.elim)
@[simp] theorem false_iff (p : Prop) : (False ↔ p) = ¬p := propext <| Iff.intro (fun h hp => h.mpr hp) (fun h => Iff.intro False.elim h)
@[simp] theorem false_implies (p : Prop) : (False → p) = True := propext <| Iff.intro (fun _ => trivial) (by intros; trivial)
@[simp] theorem implies_true (p : Prop) : (p → True) = True := propext <| Iff.intro (fun _ => trivial) (by intros; trivial)
@[simp] theorem true_implies (p : Prop) : (True → p) = p := propext <| Iff.intro (fun h => h trivial) (by intros; trivial)
@[simp] theorem Bool.or_false (b : Bool) : (b || false) = b := by cases b <;> rfl
@[simp] theorem Bool.or_true (b : Bool) : (b || true) = true := by cases b <;> rfl
@[simp] theorem Bool.false_or (b : Bool) : (false || b) = b := by cases b <;> rfl
@[simp] theorem Bool.true_or (b : Bool) : (true || b) = true := by cases b <;> rfl
@[simp] theorem Bool.or_self (b : Bool) : (b || b) = b := by cases b <;> rfl
@[simp] theorem Bool.and_false (b : Bool) : (b && false) = false := by cases b <;> rfl
@[simp] theorem Bool.and_true (b : Bool) : (b && true) = b := by cases b <;> rfl
@[simp] theorem Bool.false_and (b : Bool) : (false && b) = false := by cases b <;> rfl
@[simp] theorem Bool.true_and (b : Bool) : (true && b) = b := by cases b <;> rfl
@[simp] theorem Bool.and_self (b : Bool) : (b && b) = b := by cases b <;> rfl
|
ba480f97838c552a6c51c9a424a212314c0310d9 | 1717bcbca047a0d25d687e7e9cd482fba00d058f | /src/data/complex/exponential.lean | 9f4afaa34f38d15892afd4ca121506c1d945c78a | [
"Apache-2.0"
] | permissive | swapnilkapoor22/mathlib | 51ad5804e6a0635ed5c7611cee73e089ab271060 | 3e7efd4ecd5d379932a89212eebd362beb01309e | refs/heads/master | 1,676,467,741,465 | 1,610,301,556,000 | 1,610,301,556,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 60,165 | 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
-/
import algebra.geom_sum
import data.nat.choose.sum
import data.complex.basic
/-!
# Exponential, trigonometric and hyperbolic trigonometric functions
This file contains the definitions of the real and complex exponential, sine, cosine, tangent,
hyperbolic sine, hyperbolic cosine, and hyperbolic tangent functions.
-/
local notation `abs'` := _root_.abs
open is_absolute_value
open_locale classical big_operators nat
section
open real is_absolute_value finset
lemma forall_ge_le_of_forall_le_succ {α : Type*} [preorder α] (f : ℕ → α) {m : ℕ}
(h : ∀ n ≥ m, f n.succ ≤ f n) : ∀ {l}, ∀ k ≥ m, k ≤ l → f l ≤ f k :=
begin
assume l k hkm hkl,
generalize hp : l - k = p,
have : l = k + p := add_comm p k ▸ (nat.sub_eq_iff_eq_add hkl).1 hp,
subst this,
clear hkl hp,
induction p with p ih,
{ simp },
{ exact le_trans (h _ (le_trans hkm (nat.le_add_right _ _))) ih }
end
section
variables {α : Type*} {β : Type*} [ring β]
[linear_ordered_field α] [archimedean α] {abv : β → α} [is_absolute_value abv]
lemma is_cau_of_decreasing_bounded (f : ℕ → α) {a : α} {m : ℕ} (ham : ∀ n ≥ m, abs (f n) ≤ a)
(hnm : ∀ n ≥ m, f n.succ ≤ f n) : is_cau_seq abs f :=
λ ε ε0,
let ⟨k, hk⟩ := archimedean.arch a ε0 in
have h : ∃ l, ∀ n ≥ m, a - l •ℕ ε < f n :=
⟨k + k + 1, λ n hnm, lt_of_lt_of_le
(show a - (k + (k + 1)) •ℕ ε < -abs (f n),
from lt_neg.1 $ lt_of_le_of_lt (ham n hnm) (begin
rw [neg_sub, lt_sub_iff_add_lt, add_nsmul],
exact add_lt_add_of_le_of_lt hk (lt_of_le_of_lt hk
(lt_add_of_pos_left _ ε0)),
end))
(neg_le.2 $ (abs_neg (f n)) ▸ le_abs_self _)⟩,
let l := nat.find h in
have hl : ∀ (n : ℕ), n ≥ m → f n > a - l •ℕ ε := nat.find_spec h,
have hl0 : l ≠ 0 := λ hl0, not_lt_of_ge (ham m (le_refl _))
(lt_of_lt_of_le (by have := hl m (le_refl m); simpa [hl0] using this) (le_abs_self (f m))),
begin
cases not_forall.1
(nat.find_min h (nat.pred_lt hl0)) with i hi,
rw [not_imp, not_lt] at hi,
existsi i,
assume j hj,
have hfij : f j ≤ f i := forall_ge_le_of_forall_le_succ f hnm _ hi.1 hj,
rw [abs_of_nonpos (sub_nonpos.2 hfij), neg_sub, sub_lt_iff_lt_add'],
exact calc f i ≤ a - (nat.pred l) •ℕ ε : hi.2
... = a - l •ℕ ε + ε :
by conv {to_rhs, rw [← nat.succ_pred_eq_of_pos (nat.pos_of_ne_zero hl0), succ_nsmul',
sub_add, add_sub_cancel] }
... < f j + ε : add_lt_add_right (hl j (le_trans hi.1 hj)) _
end
lemma is_cau_of_mono_bounded (f : ℕ → α) {a : α} {m : ℕ} (ham : ∀ n ≥ m, abs (f n) ≤ a)
(hnm : ∀ n ≥ m, f n ≤ f n.succ) : is_cau_seq abs f :=
begin
refine @eq.rec_on (ℕ → α) _ (is_cau_seq abs) _ _
(-⟨_, @is_cau_of_decreasing_bounded _ _ _ (λ n, -f n) a m (by simpa) (by simpa)⟩ :
cau_seq α abs).2,
ext,
exact neg_neg _
end
end
section no_archimedean
variables {α : Type*} {β : Type*} [ring β]
[linear_ordered_field α] {abv : β → α} [is_absolute_value abv]
lemma is_cau_series_of_abv_le_cau {f : ℕ → β} {g : ℕ → α} (n : ℕ) :
(∀ m, n ≤ m → abv (f m) ≤ g m) →
is_cau_seq abs (λ n, ∑ i in range n, g i) →
is_cau_seq abv (λ n, ∑ i in range n, f i) :=
begin
assume hm hg ε ε0,
cases hg (ε / 2) (div_pos ε0 (by norm_num)) with i hi,
existsi max n i,
assume j ji,
have hi₁ := hi j (le_trans (le_max_right n i) ji),
have hi₂ := hi (max n i) (le_max_right n i),
have sub_le := abs_sub_le (∑ k in range j, g k) (∑ k in range i, g k)
(∑ k in range (max n i), g k),
have := add_lt_add hi₁ hi₂,
rw [abs_sub (∑ k in range (max n i), g k), add_halves ε] at this,
refine lt_of_le_of_lt (le_trans (le_trans _ (le_abs_self _)) sub_le) this,
generalize hk : j - max n i = k,
clear this hi₂ hi₁ hi ε0 ε hg sub_le,
rw nat.sub_eq_iff_eq_add ji at hk,
rw hk,
clear hk ji j,
induction k with k' hi,
{ simp [abv_zero abv] },
{ dsimp at *,
simp only [nat.succ_add, sum_range_succ, sub_eq_add_neg, add_assoc],
refine le_trans (abv_add _ _ _) _,
simp only [sub_eq_add_neg] at hi,
exact add_le_add (hm _ (le_add_of_nonneg_of_le (nat.zero_le _) (le_max_left _ _))) hi },
end
lemma is_cau_series_of_abv_cau {f : ℕ → β} : is_cau_seq abs (λ m, ∑ n in range m, abv (f n)) →
is_cau_seq abv (λ m, ∑ n in range m, f n) :=
is_cau_series_of_abv_le_cau 0 (λ n h, le_refl _)
end no_archimedean
section
variables {α : Type*} {β : Type*} [ring β]
[linear_ordered_field α] [archimedean α] {abv : β → α} [is_absolute_value abv]
lemma is_cau_geo_series {β : Type*} [field β] {abv : β → α} [is_absolute_value abv]
(x : β) (hx1 : abv x < 1) : is_cau_seq abv (λ n, ∑ m in range n, x ^ m) :=
have hx1' : abv x ≠ 1 := λ h, by simpa [h, lt_irrefl] using hx1,
is_cau_series_of_abv_cau
begin
simp only [abv_pow abv] {eta := ff},
have : (λ (m : ℕ), ∑ n in range m, (abv x) ^ n) =
λ m, geom_series (abv x) m := rfl,
simp only [this, geom_sum hx1'] {eta := ff},
conv in (_ / _) { rw [← neg_div_neg_eq, neg_sub, neg_sub] },
refine @is_cau_of_mono_bounded _ _ _ _ ((1 : α) / (1 - abv x)) 0 _ _,
{ assume n hn,
rw abs_of_nonneg,
refine div_le_div_of_le (le_of_lt $ sub_pos.2 hx1)
(sub_le_self _ (abv_pow abv x n ▸ abv_nonneg _ _)),
refine div_nonneg (sub_nonneg.2 _) (sub_nonneg.2 $ le_of_lt hx1),
clear hn,
induction n with n ih,
{ simp },
{ rw [pow_succ, ← one_mul (1 : α)],
refine mul_le_mul (le_of_lt hx1) ih (abv_pow abv x n ▸ abv_nonneg _ _) (by norm_num) } },
{ assume n hn,
refine div_le_div_of_le (le_of_lt $ sub_pos.2 hx1) (sub_le_sub_left _ _),
rw [← one_mul (_ ^ n), pow_succ],
exact mul_le_mul_of_nonneg_right (le_of_lt hx1) (pow_nonneg (abv_nonneg _ _) _) }
end
lemma is_cau_geo_series_const (a : α) {x : α} (hx1 : abs x < 1) :
is_cau_seq abs (λ m, ∑ n in range m, a * x ^ n) :=
have is_cau_seq abs (λ m, a * ∑ n in range m, x ^ n) :=
(cau_seq.const abs a * ⟨_, is_cau_geo_series x hx1⟩).2,
by simpa only [mul_sum]
lemma series_ratio_test {f : ℕ → β} (n : ℕ) (r : α)
(hr0 : 0 ≤ r) (hr1 : r < 1) (h : ∀ m, n ≤ m → abv (f m.succ) ≤ r * abv (f m)) :
is_cau_seq abv (λ m, ∑ n in range m, f n) :=
have har1 : abs r < 1, by rwa abs_of_nonneg hr0,
begin
refine is_cau_series_of_abv_le_cau n.succ _ (is_cau_geo_series_const (abv (f n.succ) * r⁻¹ ^ n.succ) har1),
assume m hmn,
cases classical.em (r = 0) with r_zero r_ne_zero,
{ have m_pos := lt_of_lt_of_le (nat.succ_pos n) hmn,
have := h m.pred (nat.le_of_succ_le_succ (by rwa [nat.succ_pred_eq_of_pos m_pos])),
simpa [r_zero, nat.succ_pred_eq_of_pos m_pos, pow_succ] },
generalize hk : m - n.succ = k,
have r_pos : 0 < r := lt_of_le_of_ne hr0 (ne.symm r_ne_zero),
replace hk : m = k + n.succ := (nat.sub_eq_iff_eq_add hmn).1 hk,
induction k with k ih generalizing m n,
{ rw [hk, zero_add, mul_right_comm, inv_pow' _ _, ← div_eq_mul_inv, mul_div_cancel],
exact (ne_of_lt (pow_pos r_pos _)).symm },
{ have kn : k + n.succ ≥ n.succ, by rw ← zero_add n.succ; exact add_le_add (zero_le _) (by simp),
rw [hk, nat.succ_add, pow_succ' r, ← mul_assoc],
exact le_trans (by rw mul_comm; exact h _ (nat.le_of_succ_le kn))
(mul_le_mul_of_nonneg_right (ih (k + n.succ) n h kn rfl) hr0) }
end
lemma sum_range_diag_flip {α : Type*} [add_comm_monoid α] (n : ℕ) (f : ℕ → ℕ → α) :
∑ m in range n, ∑ k in range (m + 1), f k (m - k) =
∑ m in range n, ∑ k in range (n - m), f m k :=
by rw [sum_sigma', sum_sigma']; exact sum_bij
(λ a _, ⟨a.2, a.1 - a.2⟩)
(λ a ha, have h₁ : a.1 < n := mem_range.1 (mem_sigma.1 ha).1,
have h₂ : a.2 < nat.succ a.1 := mem_range.1 (mem_sigma.1 ha).2,
mem_sigma.2 ⟨mem_range.2 (lt_of_lt_of_le h₂ h₁),
mem_range.2 ((nat.sub_lt_sub_right_iff (nat.le_of_lt_succ h₂)).2 h₁)⟩)
(λ _ _, rfl)
(λ ⟨a₁, a₂⟩ ⟨b₁, b₂⟩ ha hb h,
have ha : a₁ < n ∧ a₂ ≤ a₁ :=
⟨mem_range.1 (mem_sigma.1 ha).1, nat.le_of_lt_succ (mem_range.1 (mem_sigma.1 ha).2)⟩,
have hb : b₁ < n ∧ b₂ ≤ b₁ :=
⟨mem_range.1 (mem_sigma.1 hb).1, nat.le_of_lt_succ (mem_range.1 (mem_sigma.1 hb).2)⟩,
have h : a₂ = b₂ ∧ _ := sigma.mk.inj h,
have h' : a₁ = b₁ - b₂ + a₂ := (nat.sub_eq_iff_eq_add ha.2).1 (eq_of_heq h.2),
sigma.mk.inj_iff.2
⟨nat.sub_add_cancel hb.2 ▸ h'.symm ▸ h.1 ▸ rfl,
(heq_of_eq h.1)⟩)
(λ ⟨a₁, a₂⟩ ha,
have ha : a₁ < n ∧ a₂ < n - a₁ :=
⟨mem_range.1 (mem_sigma.1 ha).1, (mem_range.1 (mem_sigma.1 ha).2)⟩,
⟨⟨a₂ + a₁, a₁⟩, ⟨mem_sigma.2 ⟨mem_range.2 (nat.lt_sub_right_iff_add_lt.1 ha.2),
mem_range.2 (nat.lt_succ_of_le (nat.le_add_left _ _))⟩,
sigma.mk.inj_iff.2 ⟨rfl, heq_of_eq (nat.add_sub_cancel _ _).symm⟩⟩⟩)
lemma sum_range_sub_sum_range {α : Type*} [add_comm_group α] {f : ℕ → α}
{n m : ℕ} (hnm : n ≤ m) : ∑ k in range m, f k - ∑ k in range n, f k =
∑ k in (range m).filter (λ k, n ≤ k), f k :=
begin
rw [← sum_sdiff (@filter_subset _ (λ k, n ≤ k) _ (range m)),
sub_eq_iff_eq_add, ← eq_sub_iff_add_eq, add_sub_cancel'],
refine finset.sum_congr
(finset.ext $ λ a, ⟨λ h, by simp at *; finish,
λ h, have ham : a < m := lt_of_lt_of_le (mem_range.1 h) hnm,
by simp * at *⟩)
(λ _ _, rfl),
end
end
section no_archimedean
variables {α : Type*} {β : Type*} [ring β]
[linear_ordered_field α] {abv : β → α} [is_absolute_value abv]
lemma abv_sum_le_sum_abv {γ : Type*} (f : γ → β) (s : finset γ) :
abv (∑ k in s, f k) ≤ ∑ k in s, abv (f k) :=
by haveI := classical.dec_eq γ; exact
finset.induction_on s (by simp [abv_zero abv])
(λ a s has ih, by rw [sum_insert has, sum_insert has];
exact le_trans (abv_add abv _ _) (add_le_add_left ih _))
lemma cauchy_product {a b : ℕ → β}
(ha : is_cau_seq abs (λ m, ∑ n in range m, abv (a n)))
(hb : is_cau_seq abv (λ m, ∑ n in range m, b n)) (ε : α) (ε0 : 0 < ε) :
∃ i : ℕ, ∀ j ≥ i, abv ((∑ k in range j, a k) * (∑ k in range j, b k) -
∑ n in range j, ∑ m in range (n + 1), a m * b (n - m)) < ε :=
let ⟨Q, hQ⟩ := cau_seq.bounded ⟨_, hb⟩ in
let ⟨P, hP⟩ := cau_seq.bounded ⟨_, ha⟩ in
have hP0 : 0 < P, from lt_of_le_of_lt (abs_nonneg _) (hP 0),
have hPε0 : 0 < ε / (2 * P),
from div_pos ε0 (mul_pos (show (2 : α) > 0, from by norm_num) hP0),
let ⟨N, hN⟩ := cau_seq.cauchy₂ ⟨_, hb⟩ hPε0 in
have hQε0 : 0 < ε / (4 * Q),
from div_pos ε0 (mul_pos (show (0 : α) < 4, by norm_num)
(lt_of_le_of_lt (abv_nonneg _ _) (hQ 0))),
let ⟨M, hM⟩ := cau_seq.cauchy₂ ⟨_, ha⟩ hQε0 in
⟨2 * (max N M + 1), λ K hK,
have h₁ : ∑ m in range K, ∑ k in range (m + 1), a k * b (m - k) =
∑ m in range K, ∑ n in range (K - m), a m * b n,
by simpa using sum_range_diag_flip K (λ m n, a m * b n),
have h₂ : (λ i, ∑ k in range (K - i), a i * b k) = (λ i, a i * ∑ k in range (K - i), b k),
by simp [finset.mul_sum],
have h₃ : ∑ i in range K, a i * ∑ k in range (K - i), b k =
∑ i in range K, a i * (∑ k in range (K - i), b k - ∑ k in range K, b k)
+ ∑ i in range K, a i * ∑ k in range K, b k,
by rw ← sum_add_distrib; simp [(mul_add _ _ _).symm],
have two_mul_two : (4 : α) = 2 * 2, by norm_num,
have hQ0 : Q ≠ 0, from λ h, by simpa [h, lt_irrefl] using hQε0,
have h2Q0 : 2 * Q ≠ 0, from mul_ne_zero two_ne_zero hQ0,
have hε : ε / (2 * P) * P + ε / (4 * Q) * (2 * Q) = ε,
by rw [← div_div_eq_div_mul, div_mul_cancel _ (ne.symm (ne_of_lt hP0)),
two_mul_two, mul_assoc, ← div_div_eq_div_mul, div_mul_cancel _ h2Q0, add_halves],
have hNMK : max N M + 1 < K,
from lt_of_lt_of_le (by rw two_mul; exact lt_add_of_pos_left _ (nat.succ_pos _)) hK,
have hKN : N < K,
from calc N ≤ max N M : le_max_left _ _
... < max N M + 1 : nat.lt_succ_self _
... < K : hNMK,
have hsumlesum : ∑ i in range (max N M + 1), abv (a i) *
abv (∑ k in range (K - i), b k - ∑ k in range K, b k) ≤
∑ i in range (max N M + 1), abv (a i) * (ε / (2 * P)),
from sum_le_sum (λ m hmJ, mul_le_mul_of_nonneg_left
(le_of_lt (hN (K - m) K
(nat.le_sub_left_of_add_le (le_trans
(by rw two_mul; exact add_le_add (le_of_lt (mem_range.1 hmJ))
(le_trans (le_max_left _ _) (le_of_lt (lt_add_one _)))) hK))
(le_of_lt hKN))) (abv_nonneg abv _)),
have hsumltP : ∑ n in range (max N M + 1), abv (a n) < P :=
calc ∑ n in range (max N M + 1), abv (a n)
= abs (∑ n in range (max N M + 1), abv (a n)) :
eq.symm (abs_of_nonneg (sum_nonneg (λ x h, abv_nonneg abv (a x))))
... < P : hP (max N M + 1),
begin
rw [h₁, h₂, h₃, sum_mul, ← sub_sub, sub_right_comm, sub_self, zero_sub, abv_neg abv],
refine lt_of_le_of_lt (abv_sum_le_sum_abv _ _) _,
suffices : ∑ i in range (max N M + 1),
abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k) +
(∑ i in range K, abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k) -
∑ i in range (max N M + 1), abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k)) <
ε / (2 * P) * P + ε / (4 * Q) * (2 * Q),
{ rw hε at this, simpa [abv_mul abv] },
refine add_lt_add (lt_of_le_of_lt hsumlesum
(by rw [← sum_mul, mul_comm]; exact (mul_lt_mul_left hPε0).mpr hsumltP)) _,
rw sum_range_sub_sum_range (le_of_lt hNMK),
exact calc ∑ i in (range K).filter (λ k, max N M + 1 ≤ k),
abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k)
≤ ∑ i in (range K).filter (λ k, max N M + 1 ≤ k), abv (a i) * (2 * Q) :
sum_le_sum (λ n hn, begin
refine mul_le_mul_of_nonneg_left _ (abv_nonneg _ _),
rw sub_eq_add_neg,
refine le_trans (abv_add _ _ _) _,
rw [two_mul, abv_neg abv],
exact add_le_add (le_of_lt (hQ _)) (le_of_lt (hQ _)),
end)
... < ε / (4 * Q) * (2 * Q) :
by rw [← sum_mul, ← sum_range_sub_sum_range (le_of_lt hNMK)];
refine (mul_lt_mul_right $ by rw two_mul;
exact add_pos (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0))
(lt_of_le_of_lt (abv_nonneg _ _) (hQ 0))).2
(lt_of_le_of_lt (le_abs_self _)
(hM _ _ (le_trans (nat.le_succ_of_le (le_max_right _ _)) (le_of_lt hNMK))
(nat.le_succ_of_le (le_max_right _ _))))
end⟩
end no_archimedean
end
open finset
open cau_seq
namespace complex
lemma is_cau_abs_exp (z : ℂ) : is_cau_seq _root_.abs
(λ n, ∑ m in range n, abs (z ^ m / m!)) :=
let ⟨n, hn⟩ := exists_nat_gt (abs z) in
have hn0 : (0 : ℝ) < n, from lt_of_le_of_lt (abs_nonneg _) hn,
series_ratio_test n (complex.abs z / n) (div_nonneg (complex.abs_nonneg _) (le_of_lt hn0))
(by rwa [div_lt_iff hn0, one_mul])
(λ m hm,
by rw [abs_abs, abs_abs, nat.factorial_succ, pow_succ,
mul_comm m.succ, nat.cast_mul, ← div_div_eq_div_mul, mul_div_assoc,
mul_div_right_comm, abs_mul, abs_div, abs_cast_nat];
exact mul_le_mul_of_nonneg_right
(div_le_div_of_le_left (abs_nonneg _) hn0
(nat.cast_le.2 (le_trans hm (nat.le_succ _)))) (abs_nonneg _))
noncomputable theory
lemma is_cau_exp (z : ℂ) :
is_cau_seq abs (λ n, ∑ m in range n, z ^ m / m!) :=
is_cau_series_of_abv_cau (is_cau_abs_exp z)
/-- The Cauchy sequence consisting of partial sums of the Taylor series of
the complex exponential function -/
@[pp_nodot] def exp' (z : ℂ) :
cau_seq ℂ complex.abs :=
⟨λ n, ∑ m in range n, z ^ m / m!, is_cau_exp z⟩
/-- The complex exponential function, defined via its Taylor series -/
@[pp_nodot] def exp (z : ℂ) : ℂ := lim (exp' z)
/-- The complex sine function, defined via `exp` -/
@[pp_nodot] def sin (z : ℂ) : ℂ := ((exp (-z * I) - exp (z * I)) * I) / 2
/-- The complex cosine function, defined via `exp` -/
@[pp_nodot] def cos (z : ℂ) : ℂ := (exp (z * I) + exp (-z * I)) / 2
/-- The complex tangent function, defined as `sin z / cos z` -/
@[pp_nodot] def tan (z : ℂ) : ℂ := sin z / cos z
/-- The complex hyperbolic sine function, defined via `exp` -/
@[pp_nodot] def sinh (z : ℂ) : ℂ := (exp z - exp (-z)) / 2
/-- The complex hyperbolic cosine function, defined via `exp` -/
@[pp_nodot] def cosh (z : ℂ) : ℂ := (exp z + exp (-z)) / 2
/-- The complex hyperbolic tangent function, defined as `sinh z / cosh z` -/
@[pp_nodot] def tanh (z : ℂ) : ℂ := sinh z / cosh z
end complex
namespace real
open complex
/-- The real exponential function, defined as the real part of the complex exponential -/
@[pp_nodot] def exp (x : ℝ) : ℝ := (exp x).re
/-- The real sine function, defined as the real part of the complex sine -/
@[pp_nodot] def sin (x : ℝ) : ℝ := (sin x).re
/-- The real cosine function, defined as the real part of the complex cosine -/
@[pp_nodot] def cos (x : ℝ) : ℝ := (cos x).re
/-- The real tangent function, defined as the real part of the complex tangent -/
@[pp_nodot] def tan (x : ℝ) : ℝ := (tan x).re
/-- The real hypebolic sine function, defined as the real part of the complex hyperbolic sine -/
@[pp_nodot] def sinh (x : ℝ) : ℝ := (sinh x).re
/-- The real hypebolic cosine function, defined as the real part of the complex hyperbolic cosine -/
@[pp_nodot] def cosh (x : ℝ) : ℝ := (cosh x).re
/-- The real hypebolic tangent function, defined as the real part of
the complex hyperbolic tangent -/
@[pp_nodot] def tanh (x : ℝ) : ℝ := (tanh x).re
end real
namespace complex
variables (x y : ℂ)
@[simp] lemma exp_zero : exp 0 = 1 :=
lim_eq_of_equiv_const $
λ ε ε0, ⟨1, λ j hj, begin
convert ε0,
cases j,
{ exact absurd hj (not_le_of_gt zero_lt_one) },
{ dsimp [exp'],
induction j with j ih,
{ dsimp [exp']; simp },
{ rw ← ih dec_trivial,
simp only [sum_range_succ, pow_succ],
simp } }
end⟩
lemma exp_add : exp (x + y) = exp x * exp y :=
show lim (⟨_, is_cau_exp (x + y)⟩ : cau_seq ℂ abs) =
lim (show cau_seq ℂ abs, from ⟨_, is_cau_exp x⟩)
* lim (show cau_seq ℂ abs, from ⟨_, is_cau_exp y⟩),
from
have hj : ∀ j : ℕ, ∑ m in range j, (x + y) ^ m / m! =
∑ i in range j, ∑ k in range (i + 1), x ^ k / k! * (y ^ (i - k) / (i - k)!),
from assume j,
finset.sum_congr rfl (λ m hm, begin
rw [add_pow, div_eq_mul_inv, sum_mul],
refine finset.sum_congr rfl (λ i hi, _),
have h₁ : (m.choose i : ℂ) ≠ 0 := nat.cast_ne_zero.2
(pos_iff_ne_zero.1 (nat.choose_pos (nat.le_of_lt_succ (mem_range.1 hi)))),
have h₂ := nat.choose_mul_factorial_mul_factorial (nat.le_of_lt_succ $ finset.mem_range.1 hi),
rw [← h₂, nat.cast_mul, nat.cast_mul, mul_inv', mul_inv'],
simp only [mul_left_comm (m.choose i : ℂ), mul_assoc, mul_left_comm (m.choose i : ℂ)⁻¹,
mul_comm (m.choose i : ℂ)],
rw inv_mul_cancel h₁,
simp [div_eq_mul_inv, mul_comm, mul_assoc, mul_left_comm]
end),
by rw lim_mul_lim;
exact eq.symm (lim_eq_lim_of_equiv (by dsimp; simp only [hj];
exact cauchy_product (is_cau_abs_exp x) (is_cau_exp y)))
attribute [irreducible] complex.exp
lemma exp_list_sum (l : list ℂ) : exp l.sum = (l.map exp).prod :=
@monoid_hom.map_list_prod (multiplicative ℂ) ℂ _ _ ⟨exp, exp_zero, exp_add⟩ l
lemma exp_multiset_sum (s : multiset ℂ) : exp s.sum = (s.map exp).prod :=
@monoid_hom.map_multiset_prod (multiplicative ℂ) ℂ _ _ ⟨exp, exp_zero, exp_add⟩ s
lemma exp_sum {α : Type*} (s : finset α) (f : α → ℂ) : exp (∑ x in s, f x) = ∏ x in s, exp (f x) :=
@monoid_hom.map_prod α (multiplicative ℂ) ℂ _ _ ⟨exp, exp_zero, exp_add⟩ f s
lemma exp_nat_mul (x : ℂ) : ∀ n : ℕ, exp(n*x) = (exp x)^n
| 0 := by rw [nat.cast_zero, zero_mul, exp_zero, pow_zero]
| (nat.succ n) := by rw [pow_succ', nat.cast_add_one, add_mul, exp_add, ←exp_nat_mul, one_mul]
lemma exp_ne_zero : exp x ≠ 0 :=
λ h, zero_ne_one $ by rw [← exp_zero, ← add_neg_self x, exp_add, h]; simp
lemma exp_neg : exp (-x) = (exp x)⁻¹ :=
by rw [← mul_right_inj' (exp_ne_zero x), ← exp_add];
simp [mul_inv_cancel (exp_ne_zero x)]
lemma exp_sub : exp (x - y) = exp x / exp y :=
by simp [sub_eq_add_neg, exp_add, exp_neg, div_eq_mul_inv]
@[simp] lemma exp_conj : exp (conj x) = conj (exp x) :=
begin
dsimp [exp],
rw [← lim_conj],
refine congr_arg lim (cau_seq.ext (λ _, _)),
dsimp [exp', function.comp, cau_seq_conj],
rw conj.map_sum,
refine sum_congr rfl (λ n hn, _),
rw [conj.map_div, conj.map_pow, ← of_real_nat_cast, conj_of_real]
end
@[simp] lemma of_real_exp_of_real_re (x : ℝ) : ((exp x).re : ℂ) = exp x :=
eq_conj_iff_re.1 $ by rw [← exp_conj, conj_of_real]
@[simp, norm_cast] lemma of_real_exp (x : ℝ) : (real.exp x : ℂ) = exp x :=
of_real_exp_of_real_re _
@[simp] lemma exp_of_real_im (x : ℝ) : (exp x).im = 0 :=
by rw [← of_real_exp_of_real_re, of_real_im]
lemma exp_of_real_re (x : ℝ) : (exp x).re = real.exp x := rfl
lemma two_sinh : 2 * sinh x = exp x - exp (-x) :=
mul_div_cancel' _ two_ne_zero'
lemma two_cosh : 2 * cosh x = exp x + exp (-x) :=
mul_div_cancel' _ two_ne_zero'
@[simp] lemma sinh_zero : sinh 0 = 0 := by simp [sinh]
@[simp] lemma sinh_neg : sinh (-x) = -sinh x :=
by simp [sinh, exp_neg, (neg_div _ _).symm, add_mul]
private lemma sinh_add_aux {a b c d : ℂ} :
(a - b) * (c + d) + (a + b) * (c - d) = 2 * (a * c - b * d) := by ring
lemma sinh_add : sinh (x + y) = sinh x * cosh y + cosh x * sinh y :=
begin
rw [← mul_right_inj' (@two_ne_zero' ℂ _ _ _), two_sinh,
exp_add, neg_add, exp_add, eq_comm,
mul_add, ← mul_assoc, two_sinh, mul_left_comm, two_sinh,
← mul_right_inj' (@two_ne_zero' ℂ _ _ _), mul_add,
mul_left_comm, two_cosh, ← mul_assoc, two_cosh],
exact sinh_add_aux
end
@[simp] lemma cosh_zero : cosh 0 = 1 := by simp [cosh]
@[simp] lemma cosh_neg : cosh (-x) = cosh x :=
by simp [add_comm, cosh, exp_neg]
private lemma cosh_add_aux {a b c d : ℂ} :
(a + b) * (c + d) + (a - b) * (c - d) = 2 * (a * c + b * d) := by ring
lemma cosh_add : cosh (x + y) = cosh x * cosh y + sinh x * sinh y :=
begin
rw [← mul_right_inj' (@two_ne_zero' ℂ _ _ _), two_cosh,
exp_add, neg_add, exp_add, eq_comm,
mul_add, ← mul_assoc, two_cosh, ← mul_assoc, two_sinh,
← mul_right_inj' (@two_ne_zero' ℂ _ _ _), mul_add,
mul_left_comm, two_cosh, mul_left_comm, two_sinh],
exact cosh_add_aux
end
lemma sinh_sub : sinh (x - y) = sinh x * cosh y - cosh x * sinh y :=
by simp [sub_eq_add_neg, sinh_add, sinh_neg, cosh_neg]
lemma cosh_sub : cosh (x - y) = cosh x * cosh y - sinh x * sinh y :=
by simp [sub_eq_add_neg, cosh_add, sinh_neg, cosh_neg]
lemma sinh_conj : sinh (conj x) = conj (sinh x) :=
by rw [sinh, ← conj.map_neg, exp_conj, exp_conj, ← conj.map_sub, sinh, conj.map_div, conj_bit0, conj.map_one]
@[simp] lemma of_real_sinh_of_real_re (x : ℝ) : ((sinh x).re : ℂ) = sinh x :=
eq_conj_iff_re.1 $ by rw [← sinh_conj, conj_of_real]
@[simp, norm_cast] lemma of_real_sinh (x : ℝ) : (real.sinh x : ℂ) = sinh x :=
of_real_sinh_of_real_re _
@[simp] lemma sinh_of_real_im (x : ℝ) : (sinh x).im = 0 :=
by rw [← of_real_sinh_of_real_re, of_real_im]
lemma sinh_of_real_re (x : ℝ) : (sinh x).re = real.sinh x := rfl
lemma cosh_conj : cosh (conj x) = conj (cosh x) :=
begin
rw [cosh, ← conj.map_neg, exp_conj, exp_conj, ← conj.map_add, cosh, conj.map_div,
conj_bit0, conj.map_one]
end
@[simp] lemma of_real_cosh_of_real_re (x : ℝ) : ((cosh x).re : ℂ) = cosh x :=
eq_conj_iff_re.1 $ by rw [← cosh_conj, conj_of_real]
@[simp, norm_cast] lemma of_real_cosh (x : ℝ) : (real.cosh x : ℂ) = cosh x :=
of_real_cosh_of_real_re _
@[simp] lemma cosh_of_real_im (x : ℝ) : (cosh x).im = 0 :=
by rw [← of_real_cosh_of_real_re, of_real_im]
lemma cosh_of_real_re (x : ℝ) : (cosh x).re = real.cosh x := rfl
lemma tanh_eq_sinh_div_cosh : tanh x = sinh x / cosh x := rfl
@[simp] lemma tanh_zero : tanh 0 = 0 := by simp [tanh]
@[simp] lemma tanh_neg : tanh (-x) = -tanh x := by simp [tanh, neg_div]
lemma tanh_conj : tanh (conj x) = conj (tanh x) :=
by rw [tanh, sinh_conj, cosh_conj, ← conj.map_div, tanh]
@[simp] lemma of_real_tanh_of_real_re (x : ℝ) : ((tanh x).re : ℂ) = tanh x :=
eq_conj_iff_re.1 $ by rw [← tanh_conj, conj_of_real]
@[simp, norm_cast] lemma of_real_tanh (x : ℝ) : (real.tanh x : ℂ) = tanh x :=
of_real_tanh_of_real_re _
@[simp] lemma tanh_of_real_im (x : ℝ) : (tanh x).im = 0 :=
by rw [← of_real_tanh_of_real_re, of_real_im]
lemma tanh_of_real_re (x : ℝ) : (tanh x).re = real.tanh x := rfl
lemma cosh_add_sinh : cosh x + sinh x = exp x :=
by rw [← mul_right_inj' (@two_ne_zero' ℂ _ _ _), mul_add,
two_cosh, two_sinh, add_add_sub_cancel, two_mul]
lemma sinh_add_cosh : sinh x + cosh x = exp x :=
by rw [add_comm, cosh_add_sinh]
lemma cosh_sub_sinh : cosh x - sinh x = exp (-x) :=
by rw [← mul_right_inj' (@two_ne_zero' ℂ _ _ _), mul_sub,
two_cosh, two_sinh, add_sub_sub_cancel, two_mul]
lemma cosh_sq_sub_sinh_sq : cosh x ^ 2 - sinh x ^ 2 = 1 :=
by rw [sq_sub_sq, cosh_add_sinh, cosh_sub_sinh, ← exp_add, add_neg_self, exp_zero]
lemma cosh_square : cosh x ^ 2 = sinh x ^ 2 + 1 :=
begin
rw ← cosh_sq_sub_sinh_sq x,
ring
end
lemma sinh_square : sinh x ^ 2 = cosh x ^ 2 - 1 :=
begin
rw ← cosh_sq_sub_sinh_sq x,
ring
end
lemma cosh_two_mul : cosh (2 * x) = cosh x ^ 2 + sinh x ^ 2 :=
by rw [two_mul, cosh_add, pow_two, pow_two]
lemma sinh_two_mul : sinh (2 * x) = 2 * sinh x * cosh x :=
begin
rw [two_mul, sinh_add],
ring
end
lemma cosh_three_mul : cosh (3 * x) = 4 * cosh x ^ 3 - 3 * cosh x :=
begin
have h1 : x + 2 * x = 3 * x, by ring,
rw [← h1, cosh_add x (2 * x)],
simp only [cosh_two_mul, sinh_two_mul],
have h2 : sinh x * (2 * sinh x * cosh x) = 2 * cosh x * sinh x ^ 2, by ring,
rw [h2, sinh_square],
ring
end
lemma sinh_three_mul : sinh (3 * x) = 4 * sinh x ^ 3 + 3 * sinh x :=
begin
have h1 : x + 2 * x = 3 * x, by ring,
rw [← h1, sinh_add x (2 * x)],
simp only [cosh_two_mul, sinh_two_mul],
have h2 : cosh x * (2 * sinh x * cosh x) = 2 * sinh x * cosh x ^ 2, by ring,
rw [h2, cosh_square],
ring,
end
@[simp] lemma sin_zero : sin 0 = 0 := by simp [sin]
@[simp] lemma sin_neg : sin (-x) = -sin x :=
by simp [sin, sub_eq_add_neg, exp_neg, (neg_div _ _).symm, add_mul]
lemma two_sin : 2 * sin x = (exp (-x * I) - exp (x * I)) * I :=
mul_div_cancel' _ two_ne_zero'
lemma two_cos : 2 * cos x = exp (x * I) + exp (-x * I) :=
mul_div_cancel' _ two_ne_zero'
lemma sinh_mul_I : sinh (x * I) = sin x * I :=
by rw [← mul_right_inj' (@two_ne_zero' ℂ _ _ _), two_sinh,
← mul_assoc, two_sin, mul_assoc, I_mul_I, mul_neg_one,
neg_sub, neg_mul_eq_neg_mul]
lemma cosh_mul_I : cosh (x * I) = cos x :=
by rw [← mul_right_inj' (@two_ne_zero' ℂ _ _ _), two_cosh,
two_cos, neg_mul_eq_neg_mul]
lemma sin_add : sin (x + y) = sin x * cos y + cos x * sin y :=
by rw [← mul_left_inj' I_ne_zero, ← sinh_mul_I,
add_mul, add_mul, mul_right_comm, ← sinh_mul_I,
mul_assoc, ← sinh_mul_I, ← cosh_mul_I, ← cosh_mul_I, sinh_add]
@[simp] lemma cos_zero : cos 0 = 1 := by simp [cos]
@[simp] lemma cos_neg : cos (-x) = cos x :=
by simp [cos, sub_eq_add_neg, exp_neg, add_comm]
private lemma cos_add_aux {a b c d : ℂ} :
(a + b) * (c + d) - (b - a) * (d - c) * (-1) =
2 * (a * c + b * d) := by ring
lemma cos_add : cos (x + y) = cos x * cos y - sin x * sin y :=
by rw [← cosh_mul_I, add_mul, cosh_add, cosh_mul_I, cosh_mul_I,
sinh_mul_I, sinh_mul_I, mul_mul_mul_comm, I_mul_I,
mul_neg_one, sub_eq_add_neg]
lemma sin_sub : sin (x - y) = sin x * cos y - cos x * sin y :=
by simp [sub_eq_add_neg, sin_add, sin_neg, cos_neg]
lemma cos_sub : cos (x - y) = cos x * cos y + sin x * sin y :=
by simp [sub_eq_add_neg, cos_add, sin_neg, cos_neg]
theorem sin_sub_sin : sin x - sin y = 2 * sin((x - y)/2) * cos((x + y)/2) :=
begin
have s1 := sin_add ((x + y) / 2) ((x - y) / 2),
have s2 := sin_sub ((x + y) / 2) ((x - y) / 2),
rw [div_add_div_same, add_sub, add_right_comm, add_sub_cancel, half_add_self] at s1,
rw [div_sub_div_same, ←sub_add, add_sub_cancel', half_add_self] at s2,
rw [s1, s2],
ring
end
theorem cos_sub_cos : cos x - cos y = -2 * sin((x + y)/2) * sin((x - y)/2) :=
begin
have s1 := cos_add ((x + y) / 2) ((x - y) / 2),
have s2 := cos_sub ((x + y) / 2) ((x - y) / 2),
rw [div_add_div_same, add_sub, add_right_comm, add_sub_cancel, half_add_self] at s1,
rw [div_sub_div_same, ←sub_add, add_sub_cancel', half_add_self] at s2,
rw [s1, s2],
ring,
end
lemma cos_add_cos : cos x + cos y = 2 * cos ((x + y) / 2) * cos ((x - y) / 2) :=
begin
have h2 : (2:ℂ) ≠ 0 := by norm_num,
calc cos x + cos y = cos ((x + y) / 2 + (x - y) / 2) + cos ((x + y) / 2 - (x - y) / 2) : _
... = (cos ((x + y) / 2) * cos ((x - y) / 2) - sin ((x + y) / 2) * sin ((x - y) / 2))
+ (cos ((x + y) / 2) * cos ((x - y) / 2) + sin ((x + y) / 2) * sin ((x - y) / 2)) : _
... = 2 * cos ((x + y) / 2) * cos ((x - y) / 2) : _,
{ congr; field_simp [h2]; ring },
{ rw [cos_add, cos_sub] },
ring,
end
lemma sin_conj : sin (conj x) = conj (sin x) :=
by rw [← mul_left_inj' I_ne_zero, ← sinh_mul_I,
← conj_neg_I, ← conj.map_mul, ← conj.map_mul, sinh_conj,
mul_neg_eq_neg_mul_symm, sinh_neg, sinh_mul_I, mul_neg_eq_neg_mul_symm]
@[simp] lemma of_real_sin_of_real_re (x : ℝ) : ((sin x).re : ℂ) = sin x :=
eq_conj_iff_re.1 $ by rw [← sin_conj, conj_of_real]
@[simp, norm_cast] lemma of_real_sin (x : ℝ) : (real.sin x : ℂ) = sin x :=
of_real_sin_of_real_re _
@[simp] lemma sin_of_real_im (x : ℝ) : (sin x).im = 0 :=
by rw [← of_real_sin_of_real_re, of_real_im]
lemma sin_of_real_re (x : ℝ) : (sin x).re = real.sin x := rfl
lemma cos_conj : cos (conj x) = conj (cos x) :=
by rw [← cosh_mul_I, ← conj_neg_I, ← conj.map_mul, ← cosh_mul_I,
cosh_conj, mul_neg_eq_neg_mul_symm, cosh_neg]
@[simp] lemma of_real_cos_of_real_re (x : ℝ) : ((cos x).re : ℂ) = cos x :=
eq_conj_iff_re.1 $ by rw [← cos_conj, conj_of_real]
@[simp, norm_cast] lemma of_real_cos (x : ℝ) : (real.cos x : ℂ) = cos x :=
of_real_cos_of_real_re _
@[simp] lemma cos_of_real_im (x : ℝ) : (cos x).im = 0 :=
by rw [← of_real_cos_of_real_re, of_real_im]
lemma cos_of_real_re (x : ℝ) : (cos x).re = real.cos x := rfl
@[simp] lemma tan_zero : tan 0 = 0 := by simp [tan]
lemma tan_eq_sin_div_cos : tan x = sin x / cos x := rfl
lemma tan_mul_cos {x : ℂ} (hx : cos x ≠ 0) : tan x * cos x = sin x :=
by rw [tan_eq_sin_div_cos, div_mul_cancel _ hx]
@[simp] lemma tan_neg : tan (-x) = -tan x := by simp [tan, neg_div]
lemma tan_conj : tan (conj x) = conj (tan x) :=
by rw [tan, sin_conj, cos_conj, ← conj.map_div, tan]
@[simp] lemma of_real_tan_of_real_re (x : ℝ) : ((tan x).re : ℂ) = tan x :=
eq_conj_iff_re.1 $ by rw [← tan_conj, conj_of_real]
@[simp, norm_cast] lemma of_real_tan (x : ℝ) : (real.tan x : ℂ) = tan x :=
of_real_tan_of_real_re _
@[simp] lemma tan_of_real_im (x : ℝ) : (tan x).im = 0 :=
by rw [← of_real_tan_of_real_re, of_real_im]
lemma tan_of_real_re (x : ℝ) : (tan x).re = real.tan x := rfl
lemma cos_add_sin_I : cos x + sin x * I = exp (x * I) :=
by rw [← cosh_add_sinh, sinh_mul_I, cosh_mul_I]
lemma cos_sub_sin_I : cos x - sin x * I = exp (-x * I) :=
by rw [← neg_mul_eq_neg_mul, ← cosh_sub_sinh, sinh_mul_I, cosh_mul_I]
@[simp] lemma sin_sq_add_cos_sq : sin x ^ 2 + cos x ^ 2 = 1 :=
eq.trans
(by rw [cosh_mul_I, sinh_mul_I, mul_pow, I_sq, mul_neg_one, sub_neg_eq_add, add_comm])
(cosh_sq_sub_sinh_sq (x * I))
@[simp] lemma cos_sq_add_sin_sq : cos x ^ 2 + sin x ^ 2 = 1 :=
by rw [add_comm, sin_sq_add_cos_sq]
lemma cos_two_mul' : cos (2 * x) = cos x ^ 2 - sin x ^ 2 :=
by rw [two_mul, cos_add, ← pow_two, ← pow_two]
lemma cos_two_mul : cos (2 * x) = 2 * cos x ^ 2 - 1 :=
by rw [cos_two_mul', eq_sub_iff_add_eq.2 (sin_sq_add_cos_sq x),
← sub_add, sub_add_eq_add_sub, two_mul]
lemma sin_two_mul : sin (2 * x) = 2 * sin x * cos x :=
by rw [two_mul, sin_add, two_mul, add_mul, mul_comm]
lemma cos_square : cos x ^ 2 = 1 / 2 + cos (2 * x) / 2 :=
by simp [cos_two_mul, div_add_div_same, mul_div_cancel_left, two_ne_zero', -one_div]
lemma cos_square' : cos x ^ 2 = 1 - sin x ^ 2 :=
by rw [←sin_sq_add_cos_sq x, add_sub_cancel']
lemma sin_square : sin x ^ 2 = 1 - cos x ^ 2 :=
by rw [←sin_sq_add_cos_sq x, add_sub_cancel]
lemma inv_one_add_tan_sq {x : ℂ} (hx : cos x ≠ 0) : (1 + tan x ^ 2)⁻¹ = cos x ^ 2 :=
have cos x ^ 2 ≠ 0, from pow_ne_zero 2 hx,
by { rw [tan_eq_sin_div_cos, div_pow], field_simp [this] }
lemma tan_sq_div_one_add_tan_sq {x : ℂ} (hx : cos x ≠ 0) :
tan x ^ 2 / (1 + tan x ^ 2) = sin x ^ 2 :=
by simp only [← tan_mul_cos hx, mul_pow, ← inv_one_add_tan_sq hx, div_eq_mul_inv, one_mul]
lemma cos_three_mul : cos (3 * x) = 4 * cos x ^ 3 - 3 * cos x :=
begin
have h1 : x + 2 * x = 3 * x, by ring,
rw [← h1, cos_add x (2 * x)],
simp only [cos_two_mul, sin_two_mul, mul_add, mul_sub, mul_one, pow_two],
have h2 : 4 * cos x ^ 3 = 2 * cos x * cos x * cos x + 2 * cos x * cos x ^ 2, by ring,
rw [h2, cos_square'],
ring
end
lemma sin_three_mul : sin (3 * x) = 3 * sin x - 4 * sin x ^ 3 :=
begin
have h1 : x + 2 * x = 3 * x, by ring,
rw [← h1, sin_add x (2 * x)],
simp only [cos_two_mul, sin_two_mul, cos_square'],
have h2 : cos x * (2 * sin x * cos x) = 2 * sin x * cos x ^ 2, by ring,
rw [h2, cos_square'],
ring
end
lemma exp_mul_I : exp (x * I) = cos x + sin x * I :=
(cos_add_sin_I _).symm
lemma exp_add_mul_I : exp (x + y * I) = exp x * (cos y + sin y * I) :=
by rw [exp_add, exp_mul_I]
lemma exp_eq_exp_re_mul_sin_add_cos : exp x = exp x.re * (cos x.im + sin x.im * I) :=
by rw [← exp_add_mul_I, re_add_im]
/-- De Moivre's formula -/
theorem cos_add_sin_mul_I_pow (n : ℕ) (z : ℂ) : (cos z + sin z * I) ^ n = cos (↑n * z) + sin (↑n * z) * I :=
begin
rw [← exp_mul_I, ← exp_mul_I],
induction n with n ih,
{ rw [pow_zero, nat.cast_zero, zero_mul, zero_mul, exp_zero] },
{ rw [pow_succ', ih, nat.cast_succ, add_mul, add_mul, one_mul, exp_add] }
end
end complex
namespace real
open complex
variables (x y : ℝ)
@[simp] lemma exp_zero : exp 0 = 1 :=
by simp [real.exp]
lemma exp_add : exp (x + y) = exp x * exp y :=
by simp [exp_add, exp]
lemma exp_list_sum (l : list ℝ) : exp l.sum = (l.map exp).prod :=
@monoid_hom.map_list_prod (multiplicative ℝ) ℝ _ _ ⟨exp, exp_zero, exp_add⟩ l
lemma exp_multiset_sum (s : multiset ℝ) : exp s.sum = (s.map exp).prod :=
@monoid_hom.map_multiset_prod (multiplicative ℝ) ℝ _ _ ⟨exp, exp_zero, exp_add⟩ s
lemma exp_sum {α : Type*} (s : finset α) (f : α → ℝ) : exp (∑ x in s, f x) = ∏ x in s, exp (f x) :=
@monoid_hom.map_prod α (multiplicative ℝ) ℝ _ _ ⟨exp, exp_zero, exp_add⟩ f s
lemma exp_nat_mul (x : ℝ) : ∀ n : ℕ, exp(n*x) = (exp x)^n
| 0 := by rw [nat.cast_zero, zero_mul, exp_zero, pow_zero]
| (nat.succ n) := by rw [pow_succ', nat.cast_add_one, add_mul, exp_add, ←exp_nat_mul, one_mul]
lemma exp_ne_zero : exp x ≠ 0 :=
λ h, exp_ne_zero x $ by rw [exp, ← of_real_inj] at h; simp * at *
lemma exp_neg : exp (-x) = (exp x)⁻¹ :=
by rw [← of_real_inj, exp, of_real_exp_of_real_re, of_real_neg, exp_neg,
of_real_inv, of_real_exp]
lemma exp_sub : exp (x - y) = exp x / exp y :=
by simp [sub_eq_add_neg, exp_add, exp_neg, div_eq_mul_inv]
@[simp] lemma sin_zero : sin 0 = 0 := by simp [sin]
@[simp] lemma sin_neg : sin (-x) = -sin x :=
by simp [sin, exp_neg, (neg_div _ _).symm, add_mul]
lemma sin_add : sin (x + y) = sin x * cos y + cos x * sin y :=
by rw [← of_real_inj]; simp [sin, sin_add]
@[simp] lemma cos_zero : cos 0 = 1 := by simp [cos]
@[simp] lemma cos_neg : cos (-x) = cos x :=
by simp [cos, exp_neg]
lemma cos_add : cos (x + y) = cos x * cos y - sin x * sin y :=
by rw ← of_real_inj; simp [cos, cos_add]
lemma sin_sub : sin (x - y) = sin x * cos y - cos x * sin y :=
by simp [sub_eq_add_neg, sin_add, sin_neg, cos_neg]
lemma cos_sub : cos (x - y) = cos x * cos y + sin x * sin y :=
by simp [sub_eq_add_neg, cos_add, sin_neg, cos_neg]
lemma sin_sub_sin : sin x - sin y = 2 * sin((x - y)/2) * cos((x + y)/2) :=
begin
rw ← of_real_inj,
simp only [sin, cos, of_real_sin_of_real_re, of_real_sub, of_real_add, of_real_div, of_real_mul,
of_real_one, of_real_bit0],
convert sin_sub_sin _ _;
norm_cast
end
theorem cos_sub_cos : cos x - cos y = -2 * sin((x + y)/2) * sin((x - y)/2) :=
begin
rw ← of_real_inj,
simp only [cos, neg_mul_eq_neg_mul_symm, of_real_sin, of_real_sub, of_real_add,
of_real_cos_of_real_re, of_real_div, of_real_mul, of_real_one, of_real_neg, of_real_bit0],
convert cos_sub_cos _ _,
ring,
end
lemma cos_add_cos : cos x + cos y = 2 * cos ((x + y) / 2) * cos ((x - y) / 2) :=
begin
rw ← of_real_inj,
simp only [cos, of_real_sub, of_real_add, of_real_cos_of_real_re, of_real_div, of_real_mul,
of_real_one, of_real_bit0],
convert cos_add_cos _ _;
norm_cast,
end
lemma tan_eq_sin_div_cos : tan x = sin x / cos x :=
if h : complex.cos x = 0 then by simp [sin, cos, tan, *, complex.tan, div_eq_mul_inv] at *
else
by rw [sin, cos, tan, complex.tan, ← of_real_inj, div_eq_mul_inv, mul_re];
simp [norm_sq, (div_div_eq_div_mul _ _ _).symm, div_self h]; refl
lemma tan_mul_cos {x : ℝ} (hx : cos x ≠ 0) : tan x * cos x = sin x :=
by rw [tan_eq_sin_div_cos, div_mul_cancel _ hx]
@[simp] lemma tan_zero : tan 0 = 0 := by simp [tan]
@[simp] lemma tan_neg : tan (-x) = -tan x := by simp [tan, neg_div]
@[simp] lemma sin_sq_add_cos_sq : sin x ^ 2 + cos x ^ 2 = 1 :=
of_real_inj.1 $ by simp
@[simp] lemma cos_sq_add_sin_sq : cos x ^ 2 + sin x ^ 2 = 1 :=
by rw [add_comm, sin_sq_add_cos_sq]
lemma sin_sq_le_one : sin x ^ 2 ≤ 1 :=
by rw ← sin_sq_add_cos_sq x; exact le_add_of_nonneg_right (pow_two_nonneg _)
lemma cos_sq_le_one : cos x ^ 2 ≤ 1 :=
by rw ← sin_sq_add_cos_sq x; exact le_add_of_nonneg_left (pow_two_nonneg _)
lemma abs_sin_le_one : abs' (sin x) ≤ 1 :=
abs_le_one_iff_mul_self_le_one.2 $ by simp only [← pow_two, sin_sq_le_one]
lemma abs_cos_le_one : abs' (cos x) ≤ 1 :=
abs_le_one_iff_mul_self_le_one.2 $ by simp only [← pow_two, cos_sq_le_one]
lemma sin_le_one : sin x ≤ 1 :=
(abs_le.1 (abs_sin_le_one _)).2
lemma cos_le_one : cos x ≤ 1 :=
(abs_le.1 (abs_cos_le_one _)).2
lemma neg_one_le_sin : -1 ≤ sin x :=
(abs_le.1 (abs_sin_le_one _)).1
lemma neg_one_le_cos : -1 ≤ cos x :=
(abs_le.1 (abs_cos_le_one _)).1
lemma cos_two_mul : cos (2 * x) = 2 * cos x ^ 2 - 1 :=
by rw ← of_real_inj; simp [cos_two_mul]
lemma cos_two_mul' : cos (2 * x) = cos x ^ 2 - sin x ^ 2 :=
by rw ← of_real_inj; simp [cos_two_mul']
lemma sin_two_mul : sin (2 * x) = 2 * sin x * cos x :=
by rw ← of_real_inj; simp [sin_two_mul]
lemma cos_square : cos x ^ 2 = 1 / 2 + cos (2 * x) / 2 :=
of_real_inj.1 $ by simpa using cos_square x
lemma cos_square' : cos x ^ 2 = 1 - sin x ^ 2 :=
by rw [←sin_sq_add_cos_sq x, add_sub_cancel']
lemma sin_square : sin x ^ 2 = 1 - cos x ^ 2 :=
eq_sub_iff_add_eq.2 $ sin_sq_add_cos_sq _
lemma inv_one_add_tan_sq {x : ℝ} (hx : cos x ≠ 0) : (1 + tan x ^ 2)⁻¹ = cos x ^ 2 :=
have complex.cos x ≠ 0, from mt (congr_arg re) hx,
of_real_inj.1 $ by simpa using complex.inv_one_add_tan_sq this
lemma tan_sq_div_one_add_tan_sq {x : ℝ} (hx : cos x ≠ 0) :
tan x ^ 2 / (1 + tan x ^ 2) = sin x ^ 2 :=
by simp only [← tan_mul_cos hx, mul_pow, ← inv_one_add_tan_sq hx, div_eq_mul_inv, one_mul]
lemma inv_sqrt_one_add_tan_sq {x : ℝ} (hx : 0 < cos x) :
(sqrt (1 + tan x ^ 2))⁻¹ = cos x :=
by rw [← sqrt_sqr hx.le, ← sqrt_inv, inv_one_add_tan_sq hx.ne']
lemma tan_div_sqrt_one_add_tan_sq {x : ℝ} (hx : 0 < cos x) :
tan x / sqrt (1 + tan x ^ 2) = sin x :=
by rw [← tan_mul_cos hx.ne', ← inv_sqrt_one_add_tan_sq hx, div_eq_mul_inv]
lemma cos_three_mul : cos (3 * x) = 4 * cos x ^ 3 - 3 * cos x :=
by rw ← of_real_inj; simp [cos_three_mul]
lemma sin_three_mul : sin (3 * x) = 3 * sin x - 4 * sin x ^ 3 :=
by rw ← of_real_inj; simp [sin_three_mul]
/-- The definition of `sinh` in terms of `exp`. -/
lemma sinh_eq (x : ℝ) : sinh x = (exp x - exp (-x)) / 2 :=
eq_div_of_mul_eq two_ne_zero $ by rw [sinh, exp, exp, complex.of_real_neg, complex.sinh, mul_two,
← complex.add_re, ← mul_two, div_mul_cancel _ (two_ne_zero' : (2 : ℂ) ≠ 0), complex.sub_re]
@[simp] lemma sinh_zero : sinh 0 = 0 := by simp [sinh]
@[simp] lemma sinh_neg : sinh (-x) = -sinh x :=
by simp [sinh, exp_neg, (neg_div _ _).symm, add_mul]
lemma sinh_add : sinh (x + y) = sinh x * cosh y + cosh x * sinh y :=
by rw ← of_real_inj; simp [sinh_add]
/-- The definition of `cosh` in terms of `exp`. -/
lemma cosh_eq (x : ℝ) : cosh x = (exp x + exp (-x)) / 2 :=
eq_div_of_mul_eq two_ne_zero $ by rw [cosh, exp, exp, complex.of_real_neg, complex.cosh, mul_two,
← complex.add_re, ← mul_two, div_mul_cancel _ (two_ne_zero' : (2 : ℂ) ≠ 0), complex.add_re]
@[simp] lemma cosh_zero : cosh 0 = 1 := by simp [cosh]
@[simp] lemma cosh_neg : cosh (-x) = cosh x :=
by simp [cosh, exp_neg]
lemma cosh_add : cosh (x + y) = cosh x * cosh y + sinh x * sinh y :=
by rw ← of_real_inj; simp [cosh, cosh_add]
lemma sinh_sub : sinh (x - y) = sinh x * cosh y - cosh x * sinh y :=
by simp [sub_eq_add_neg, sinh_add, sinh_neg, cosh_neg]
lemma cosh_sub : cosh (x - y) = cosh x * cosh y - sinh x * sinh y :=
by simp [sub_eq_add_neg, cosh_add, sinh_neg, cosh_neg]
lemma tanh_eq_sinh_div_cosh : tanh x = sinh x / cosh x :=
of_real_inj.1 $ by simp [tanh_eq_sinh_div_cosh]
@[simp] lemma tanh_zero : tanh 0 = 0 := by simp [tanh]
@[simp] lemma tanh_neg : tanh (-x) = -tanh x := by simp [tanh, neg_div]
lemma cosh_add_sinh : cosh x + sinh x = exp x :=
by rw ← of_real_inj; simp [cosh_add_sinh]
lemma sinh_add_cosh : sinh x + cosh x = exp x :=
by rw ← of_real_inj; simp [sinh_add_cosh]
lemma cosh_sq_sub_sinh_sq (x : ℝ) : cosh x ^ 2 - sinh x ^ 2 = 1 :=
by rw ← of_real_inj; simp [cosh_sq_sub_sinh_sq]
lemma cosh_square : cosh x ^ 2 = sinh x ^ 2 + 1 :=
by rw ← of_real_inj; simp [cosh_square]
lemma sinh_square : sinh x ^ 2 = cosh x ^ 2 - 1 :=
by rw ← of_real_inj; simp [sinh_square]
lemma cosh_two_mul : cosh (2 * x) = cosh x ^ 2 + sinh x ^ 2 :=
by rw ← of_real_inj; simp [cosh_two_mul]
lemma sinh_two_mul : sinh (2 * x) = 2 * sinh x * cosh x :=
by rw ← of_real_inj; simp [sinh_two_mul]
lemma cosh_three_mul : cosh (3 * x) = 4 * cosh x ^ 3 - 3 * cosh x :=
by rw ← of_real_inj; simp [cosh_three_mul]
lemma sinh_three_mul : sinh (3 * x) = 4 * sinh x ^ 3 + 3 * sinh x :=
by rw ← of_real_inj; simp [sinh_three_mul]
open is_absolute_value
/- TODO make this private and prove ∀ x -/
lemma add_one_le_exp_of_nonneg {x : ℝ} (hx : 0 ≤ x) : x + 1 ≤ exp x :=
calc x + 1 ≤ lim (⟨(λ n : ℕ, ((exp' x) n).re), is_cau_seq_re (exp' x)⟩ : cau_seq ℝ abs') :
le_lim (cau_seq.le_of_exists ⟨2,
λ j hj, show x + (1 : ℝ) ≤ (∑ m in range j, (x ^ m / m! : ℂ)).re,
from have h₁ : (((λ m : ℕ, (x ^ m / m! : ℂ)) ∘ nat.succ) 0).re = x, by simp,
have h₂ : ((x : ℂ) ^ 0 / 0!).re = 1, by simp,
begin
rw [← nat.sub_add_cancel hj, sum_range_succ', sum_range_succ',
add_re, add_re, h₁, h₂, add_assoc,
← @sum_hom _ _ _ _ _ _ _ complex.re
(is_add_group_hom.to_is_add_monoid_hom _)],
refine le_add_of_nonneg_of_le (sum_nonneg (λ m hm, _)) (le_refl _),
rw [← of_real_pow, ← of_real_nat_cast, ← of_real_div, of_real_re],
exact div_nonneg (pow_nonneg hx _) (nat.cast_nonneg _),
end⟩)
... = exp x : by rw [exp, complex.exp, ← cau_seq_re, lim_re]
lemma one_le_exp {x : ℝ} (hx : 0 ≤ x) : 1 ≤ exp x :=
by linarith [add_one_le_exp_of_nonneg hx]
lemma exp_pos (x : ℝ) : 0 < exp x :=
(le_total 0 x).elim (lt_of_lt_of_le zero_lt_one ∘ one_le_exp)
(λ h, by rw [← neg_neg x, real.exp_neg];
exact inv_pos.2 (lt_of_lt_of_le zero_lt_one (one_le_exp (neg_nonneg.2 h))))
@[simp] lemma abs_exp (x : ℝ) : abs' (exp x) = exp x :=
abs_of_pos (exp_pos _)
lemma exp_strict_mono : strict_mono exp :=
λ x y h, by rw [← sub_add_cancel y x, real.exp_add];
exact (lt_mul_iff_one_lt_left (exp_pos _)).2
(lt_of_lt_of_le (by linarith) (add_one_le_exp_of_nonneg (by linarith)))
@[mono] lemma exp_monotone : ∀ {x y : ℝ}, x ≤ y → exp x ≤ exp y := exp_strict_mono.monotone
@[simp] lemma exp_lt_exp {x y : ℝ} : exp x < exp y ↔ x < y := exp_strict_mono.lt_iff_lt
@[simp] lemma exp_le_exp {x y : ℝ} : exp x ≤ exp y ↔ x ≤ y := exp_strict_mono.le_iff_le
lemma exp_injective : function.injective exp := exp_strict_mono.injective
@[simp] lemma exp_eq_exp {x y : ℝ} : exp x = exp y ↔ x = y := exp_injective.eq_iff
@[simp] lemma exp_eq_one_iff : exp x = 1 ↔ x = 0 :=
by rw [← exp_zero, exp_injective.eq_iff]
@[simp] lemma one_lt_exp_iff {x : ℝ} : 1 < exp x ↔ 0 < x :=
by rw [← exp_zero, exp_lt_exp]
@[simp] lemma exp_lt_one_iff {x : ℝ} : exp x < 1 ↔ x < 0 :=
by rw [← exp_zero, exp_lt_exp]
@[simp] lemma exp_le_one_iff {x : ℝ} : exp x ≤ 1 ↔ x ≤ 0 :=
exp_zero ▸ exp_le_exp
@[simp] lemma one_le_exp_iff {x : ℝ} : 1 ≤ exp x ↔ 0 ≤ x :=
exp_zero ▸ exp_le_exp
/-- `real.cosh` is always positive -/
lemma cosh_pos (x : ℝ) : 0 < real.cosh x :=
(cosh_eq x).symm ▸ half_pos (add_pos (exp_pos x) (exp_pos (-x)))
end real
namespace complex
lemma sum_div_factorial_le {α : Type*} [linear_ordered_field α] (n j : ℕ) (hn : 0 < n) :
∑ m in filter (λ k, n ≤ k) (range j), (1 / m! : α) ≤ n.succ * (n! * n)⁻¹ :=
calc ∑ m in filter (λ k, n ≤ k) (range j), (1 / m! : α)
= ∑ m in range (j - n), 1 / (m + n)! :
sum_bij (λ m _, m - n)
(λ m hm, mem_range.2 $ (nat.sub_lt_sub_right_iff (by simp at hm; tauto)).2
(by simp at hm; tauto))
(λ m hm, by rw nat.sub_add_cancel; simp at *; tauto)
(λ a₁ a₂ ha₁ ha₂ h,
by rwa [nat.sub_eq_iff_eq_add, ← nat.sub_add_comm, eq_comm, nat.sub_eq_iff_eq_add, add_left_inj, eq_comm] at h;
simp at *; tauto)
(λ b hb, ⟨b + n, mem_filter.2 ⟨mem_range.2 $ nat.add_lt_of_lt_sub_right (mem_range.1 hb), nat.le_add_left _ _⟩,
by rw nat.add_sub_cancel⟩)
... ≤ ∑ m in range (j - n), (n! * n.succ ^ m)⁻¹ :
begin
refine sum_le_sum (assume m n, _),
rw [one_div, inv_le_inv],
{ rw [← nat.cast_pow, ← nat.cast_mul, nat.cast_le, add_comm],
exact nat.factorial_mul_pow_le_factorial },
{ exact nat.cast_pos.2 (nat.factorial_pos _) },
{ exact mul_pos (nat.cast_pos.2 (nat.factorial_pos _))
(pow_pos (nat.cast_pos.2 (nat.succ_pos _)) _) },
end
... = n!⁻¹ * ∑ m in range (j - n), n.succ⁻¹ ^ m :
by simp [mul_inv', mul_sum.symm, sum_mul.symm, -nat.factorial_succ, mul_comm, inv_pow']
... = (n.succ - n.succ * n.succ⁻¹ ^ (j - n)) / (n! * n) :
have h₁ : (n.succ : α) ≠ 1, from @nat.cast_one α _ _ ▸ mt nat.cast_inj.1
(mt nat.succ.inj (pos_iff_ne_zero.1 hn)),
have h₂ : (n.succ : α) ≠ 0, from nat.cast_ne_zero.2 (nat.succ_ne_zero _),
have h₃ : (n! * n : α) ≠ 0,
from mul_ne_zero (nat.cast_ne_zero.2 (pos_iff_ne_zero.1 (nat.factorial_pos _)))
(nat.cast_ne_zero.2 (pos_iff_ne_zero.1 hn)),
have h₄ : (n.succ - 1 : α) = n, by simp,
by rw [← geom_series_def, geom_sum_inv h₁ h₂, eq_div_iff_mul_eq h₃,
mul_comm _ (n! * n : α), ← mul_assoc (n!⁻¹ : α), ← mul_inv_rev', h₄,
← mul_assoc (n! * n : α), mul_comm (n : α) n!, mul_inv_cancel h₃];
simp [mul_add, add_mul, mul_assoc, mul_comm]
... ≤ n.succ / (n! * n) :
begin
refine iff.mpr (div_le_div_right (mul_pos _ _)) _,
exact nat.cast_pos.2 (nat.factorial_pos _),
exact nat.cast_pos.2 hn,
exact sub_le_self _
(mul_nonneg (nat.cast_nonneg _) (pow_nonneg (inv_nonneg.2 (nat.cast_nonneg _)) _))
end
lemma exp_bound {x : ℂ} (hx : abs x ≤ 1) {n : ℕ} (hn : 0 < n) :
abs (exp x - ∑ m in range n, x ^ m / m!) ≤ abs x ^ n * (n.succ * (n! * n)⁻¹) :=
begin
rw [← lim_const (∑ m in range n, _), exp, sub_eq_add_neg, ← lim_neg, lim_add, ← lim_abs],
refine lim_le (cau_seq.le_of_exists ⟨n, λ j hj, _⟩),
simp_rw ← sub_eq_add_neg,
show abs (∑ m in range j, x ^ m / m! - ∑ m in range n, x ^ m / m!)
≤ abs x ^ n * (n.succ * (n! * n)⁻¹),
rw sum_range_sub_sum_range hj,
exact calc abs (∑ m in (range j).filter (λ k, n ≤ k), (x ^ m / m! : ℂ))
= abs (∑ m in (range j).filter (λ k, n ≤ k), (x ^ n * (x ^ (m - n) / m!) : ℂ)) :
congr_arg abs (sum_congr rfl (λ m hm, by rw [← mul_div_assoc, ← pow_add, nat.add_sub_cancel']; simp at hm; tauto))
... ≤ ∑ m in filter (λ k, n ≤ k) (range j), abs (x ^ n * (_ / m!)) : abv_sum_le_sum_abv _ _
... ≤ ∑ m in filter (λ k, n ≤ k) (range j), abs x ^ n * (1 / m!) :
begin
refine sum_le_sum (λ m hm, _),
rw [abs_mul, abv_pow abs, abs_div, abs_cast_nat],
refine mul_le_mul_of_nonneg_left ((div_le_div_right _).2 _) _,
exact nat.cast_pos.2 (nat.factorial_pos _),
rw abv_pow abs,
exact (pow_le_one _ (abs_nonneg _) hx),
exact pow_nonneg (abs_nonneg _) _
end
... = abs x ^ n * (∑ m in (range j).filter (λ k, n ≤ k), (1 / m! : ℝ)) :
by simp [abs_mul, abv_pow abs, abs_div, mul_sum.symm]
... ≤ abs x ^ n * (n.succ * (n! * n)⁻¹) :
mul_le_mul_of_nonneg_left (sum_div_factorial_le _ _ hn) (pow_nonneg (abs_nonneg _) _)
end
lemma abs_exp_sub_one_le {x : ℂ} (hx : abs x ≤ 1) :
abs (exp x - 1) ≤ 2 * abs x :=
calc abs (exp x - 1) = abs (exp x - ∑ m in range 1, x ^ m / m!) :
by simp [sum_range_succ]
... ≤ abs x ^ 1 * ((nat.succ 1) * (1! * (1 : ℕ))⁻¹) :
exp_bound hx dec_trivial
... = 2 * abs x : by simp [two_mul, mul_two, mul_add, mul_comm]
lemma abs_exp_sub_one_sub_id_le {x : ℂ} (hx : abs x ≤ 1) :
abs (exp x - 1 - x) ≤ (abs x)^2 :=
calc abs (exp x - 1 - x) = abs (exp x - ∑ m in range 2, x ^ m / m!) :
by simp [sub_eq_add_neg, sum_range_succ, add_assoc]
... ≤ (abs x)^2 * (nat.succ 2 * (2! * (2 : ℕ))⁻¹) :
exp_bound hx dec_trivial
... ≤ (abs x)^2 * 1 :
mul_le_mul_of_nonneg_left (by norm_num) (pow_two_nonneg (abs x))
... = (abs x)^2 :
by rw [mul_one]
end complex
namespace real
open complex finset
lemma exp_bound {x : ℝ} (hx : abs' x ≤ 1) {n : ℕ} (hn : 0 < n) :
abs' (exp x - ∑ m in range n, x ^ m / m!) ≤ abs' x ^ n * (n.succ / (n! * n)) :=
begin
have hxc : complex.abs x ≤ 1, by exact_mod_cast hx,
convert exp_bound hxc hn; norm_cast
end
/-- A finite initial segment of the exponential series, followed by an arbitrary tail.
For fixed `n` this is just a linear map wrt `r`, and each map is a simple linear function
of the previous (see `exp_near_succ`), with `exp_near n x r ⟶ exp x` as `n ⟶ ∞`,
for any `r`. -/
def exp_near (n : ℕ) (x r : ℝ) : ℝ := ∑ m in range n, x ^ m / m! + x ^ n / n! * r
@[simp] theorem exp_near_zero (x r) : exp_near 0 x r = r := by simp [exp_near]
@[simp] theorem exp_near_succ (n x r) : exp_near (n + 1) x r = exp_near n x (1 + x / (n+1) * r) :=
by simp [exp_near, range_succ, mul_add, add_left_comm, add_assoc, pow_succ, div_eq_mul_inv,
mul_inv']; ac_refl
theorem exp_near_sub (n x r₁ r₂) : exp_near n x r₁ - exp_near n x r₂ = x ^ n / n! * (r₁ - r₂) :=
by simp [exp_near, mul_sub]
lemma exp_approx_end (n m : ℕ) (x : ℝ)
(e₁ : n + 1 = m) (h : abs' x ≤ 1) :
abs' (exp x - exp_near m x 0) ≤ abs' x ^ m / m! * ((m+1)/m) :=
by { simp [exp_near], convert exp_bound h _ using 1, field_simp [mul_comm], linarith }
lemma exp_approx_succ {n} {x a₁ b₁ : ℝ} (m : ℕ)
(e₁ : n + 1 = m) (a₂ b₂ : ℝ)
(e : abs' (1 + x / m * a₂ - a₁) ≤ b₁ - abs' x / m * b₂)
(h : abs' (exp x - exp_near m x a₂) ≤ abs' x ^ m / m! * b₂) :
abs' (exp x - exp_near n x a₁) ≤ abs' x ^ n / n! * b₁ :=
begin
refine (_root_.abs_sub_le _ _ _).trans ((add_le_add_right h _).trans _),
subst e₁, rw [exp_near_succ, exp_near_sub, _root_.abs_mul],
convert mul_le_mul_of_nonneg_left (le_sub_iff_add_le'.1 e) _,
{ simp [mul_add, pow_succ', div_eq_mul_inv, _root_.abs_mul, _root_.abs_inv, ← pow_abs, mul_inv'],
ac_refl },
{ simp [_root_.div_nonneg, _root_.abs_nonneg] }
end
lemma exp_approx_end' {n} {x a b : ℝ} (m : ℕ)
(e₁ : n + 1 = m) (rm : ℝ) (er : ↑m = rm) (h : abs' x ≤ 1)
(e : abs' (1 - a) ≤ b - abs' x / rm * ((rm+1)/rm)) :
abs' (exp x - exp_near n x a) ≤ abs' x ^ n / n! * b :=
by subst er; exact
exp_approx_succ _ e₁ _ _ (by simpa using e) (exp_approx_end _ _ _ e₁ h)
lemma exp_1_approx_succ_eq {n} {a₁ b₁ : ℝ} {m : ℕ}
(en : n + 1 = m) {rm : ℝ} (er : ↑m = rm)
(h : abs' (exp 1 - exp_near m 1 ((a₁ - 1) * rm)) ≤ abs' 1 ^ m / m! * (b₁ * rm)) :
abs' (exp 1 - exp_near n 1 a₁) ≤ abs' 1 ^ n / n! * b₁ :=
begin
subst er,
refine exp_approx_succ _ en _ _ _ h,
field_simp [show (m : ℝ) ≠ 0, by norm_cast; linarith],
end
lemma exp_approx_start (x a b : ℝ)
(h : abs' (exp x - exp_near 0 x a) ≤ abs' x ^ 0 / 0! * b) :
abs' (exp x - a) ≤ b :=
by simpa using h
lemma cos_bound {x : ℝ} (hx : abs' x ≤ 1) :
abs' (cos x - (1 - x ^ 2 / 2)) ≤ abs' x ^ 4 * (5 / 96) :=
calc abs' (cos x - (1 - x ^ 2 / 2)) = abs (complex.cos x - (1 - x ^ 2 / 2)) :
by rw ← abs_of_real; simp [of_real_bit0, of_real_one, of_real_inv]
... = abs ((complex.exp (x * I) + complex.exp (-x * I) - (2 - x ^ 2)) / 2) :
by simp [complex.cos, sub_div, add_div, neg_div, div_self (@two_ne_zero' ℂ _ _ _)]
... = abs (((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!) +
((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!))) / 2) :
congr_arg abs (congr_arg (λ x : ℂ, x / 2) begin
simp only [sum_range_succ],
simp [pow_succ],
apply complex.ext; simp [div_eq_mul_inv, norm_sq]; ring
end)
... ≤ abs ((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!) / 2) +
abs ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!) / 2) :
by rw add_div; exact abs_add _ _
... = (abs ((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!)) / 2 +
abs ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!)) / 2) :
by simp [complex.abs_div]
... ≤ ((complex.abs (x * I) ^ 4 * (nat.succ 4 * (4! * (4 : ℕ))⁻¹)) / 2 +
(complex.abs (-x * I) ^ 4 * (nat.succ 4 * (4! * (4 : ℕ))⁻¹)) / 2) :
add_le_add ((div_le_div_right (by norm_num)).2 (complex.exp_bound (by simpa) dec_trivial))
((div_le_div_right (by norm_num)).2 (complex.exp_bound (by simpa) dec_trivial))
... ≤ abs' x ^ 4 * (5 / 96) : by norm_num; simp [mul_assoc, mul_comm, mul_left_comm, mul_div_assoc]
lemma sin_bound {x : ℝ} (hx : abs' x ≤ 1) :
abs' (sin x - (x - x ^ 3 / 6)) ≤ abs' x ^ 4 * (5 / 96) :=
calc abs' (sin x - (x - x ^ 3 / 6)) = abs (complex.sin x - (x - x ^ 3 / 6)) :
by rw ← abs_of_real; simp [of_real_bit0, of_real_one, of_real_inv]
... = abs (((complex.exp (-x * I) - complex.exp (x * I)) * I - (2 * x - x ^ 3 / 3)) / 2) :
by simp [complex.sin, sub_div, add_div, neg_div, mul_div_cancel_left _ (@two_ne_zero' ℂ _ _ _),
div_div_eq_div_mul, show (3 : ℂ) * 2 = 6, by norm_num]
... = abs ((((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!) -
(complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!)) * I) / 2) :
congr_arg abs (congr_arg (λ x : ℂ, x / 2) begin
simp only [sum_range_succ],
simp [pow_succ],
apply complex.ext; simp [div_eq_mul_inv, norm_sq]; ring
end)
... ≤ abs ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!) * I / 2) +
abs (-((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!) * I) / 2) :
by rw [sub_mul, sub_eq_add_neg, add_div]; exact abs_add _ _
... = (abs ((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!)) / 2 +
abs ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!)) / 2) :
by simp [add_comm, complex.abs_div, complex.abs_mul]
... ≤ ((complex.abs (x * I) ^ 4 * (nat.succ 4 * (4! * (4 : ℕ))⁻¹)) / 2 +
(complex.abs (-x * I) ^ 4 * (nat.succ 4 * (4! * (4 : ℕ))⁻¹)) / 2) :
add_le_add ((div_le_div_right (by norm_num)).2 (complex.exp_bound (by simpa) dec_trivial))
((div_le_div_right (by norm_num)).2 (complex.exp_bound (by simpa) dec_trivial))
... ≤ abs' x ^ 4 * (5 / 96) : by norm_num; simp [mul_assoc, mul_comm, mul_left_comm, mul_div_assoc]
lemma cos_pos_of_le_one {x : ℝ} (hx : abs' x ≤ 1) : 0 < cos x :=
calc 0 < (1 - x ^ 2 / 2) - abs' x ^ 4 * (5 / 96) :
sub_pos.2 $ lt_sub_iff_add_lt.2
(calc abs' x ^ 4 * (5 / 96) + x ^ 2 / 2
≤ 1 * (5 / 96) + 1 / 2 :
add_le_add
(mul_le_mul_of_nonneg_right (pow_le_one _ (abs_nonneg _) hx) (by norm_num))
((div_le_div_right (by norm_num)).2 (by rw [pow_two, ← abs_mul_self, _root_.abs_mul];
exact mul_le_one hx (abs_nonneg _) hx))
... < 1 : by norm_num)
... ≤ cos x : sub_le.1 (abs_sub_le_iff.1 (cos_bound hx)).2
lemma sin_pos_of_pos_of_le_one {x : ℝ} (hx0 : 0 < x) (hx : x ≤ 1) : 0 < sin x :=
calc 0 < x - x ^ 3 / 6 - abs' x ^ 4 * (5 / 96) :
sub_pos.2 $ lt_sub_iff_add_lt.2
(calc abs' x ^ 4 * (5 / 96) + x ^ 3 / 6
≤ x * (5 / 96) + x / 6 :
add_le_add
(mul_le_mul_of_nonneg_right
(calc abs' x ^ 4 ≤ abs' x ^ 1 : pow_le_pow_of_le_one (abs_nonneg _)
(by rwa _root_.abs_of_nonneg (le_of_lt hx0))
dec_trivial
... = x : by simp [_root_.abs_of_nonneg (le_of_lt (hx0))]) (by norm_num))
((div_le_div_right (by norm_num)).2
(calc x ^ 3 ≤ x ^ 1 : pow_le_pow_of_le_one (le_of_lt hx0) hx dec_trivial
... = x : pow_one _))
... < x : by linarith)
... ≤ sin x : sub_le.1 (abs_sub_le_iff.1 (sin_bound
(by rwa [_root_.abs_of_nonneg (le_of_lt hx0)]))).2
lemma sin_pos_of_pos_of_le_two {x : ℝ} (hx0 : 0 < x) (hx : x ≤ 2) : 0 < sin x :=
have x / 2 ≤ 1, from (div_le_iff (by norm_num)).mpr (by simpa),
calc 0 < 2 * sin (x / 2) * cos (x / 2) :
mul_pos (mul_pos (by norm_num) (sin_pos_of_pos_of_le_one (half_pos hx0) this))
(cos_pos_of_le_one (by rwa [_root_.abs_of_nonneg (le_of_lt (half_pos hx0))]))
... = sin x : by rw [← sin_two_mul, two_mul, add_halves]
lemma cos_one_le : cos 1 ≤ 2 / 3 :=
calc cos 1 ≤ abs' (1 : ℝ) ^ 4 * (5 / 96) + (1 - 1 ^ 2 / 2) :
sub_le_iff_le_add.1 (abs_sub_le_iff.1 (cos_bound (by simp))).1
... ≤ 2 / 3 : by norm_num
lemma cos_one_pos : 0 < cos 1 := cos_pos_of_le_one (by simp)
lemma cos_two_neg : cos 2 < 0 :=
calc cos 2 = cos (2 * 1) : congr_arg cos (mul_one _).symm
... = _ : real.cos_two_mul 1
... ≤ 2 * (2 / 3) ^ 2 - 1 :
sub_le_sub_right (mul_le_mul_of_nonneg_left
(by rw [pow_two, pow_two]; exact
mul_self_le_mul_self (le_of_lt cos_one_pos)
cos_one_le)
(by norm_num)) _
... < 0 : by norm_num
end real
namespace complex
lemma abs_cos_add_sin_mul_I (x : ℝ) : abs (cos x + sin x * I) = 1 :=
have _ := real.sin_sq_add_cos_sq x,
by simp [add_comm, abs, norm_sq, pow_two, *, sin_of_real_re, cos_of_real_re, mul_re] at *
lemma abs_exp_eq_iff_re_eq {x y : ℂ} : abs (exp x) = abs (exp y) ↔ x.re = y.re :=
by rw [exp_eq_exp_re_mul_sin_add_cos, exp_eq_exp_re_mul_sin_add_cos y,
abs_mul, abs_mul, abs_cos_add_sin_mul_I, abs_cos_add_sin_mul_I,
← of_real_exp, ← of_real_exp, abs_of_nonneg (le_of_lt (real.exp_pos _)),
abs_of_nonneg (le_of_lt (real.exp_pos _)), mul_one, mul_one];
exact ⟨λ h, real.exp_injective h, congr_arg _⟩
@[simp] lemma abs_exp_of_real (x : ℝ) : abs (exp x) = real.exp x :=
by rw [← of_real_exp]; exact abs_of_nonneg (le_of_lt (real.exp_pos _))
end complex
|
cbdd0bd2ea94d1977466e9ee9eb0c0625b64066b | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/measure_theory/measure/measure_space.lean | 9089d791ce8e2ba1cf638cfad31361a42446474d | [
"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 | 189,953 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro
-/
import measure_theory.measure.null_measurable
import measure_theory.measurable_space
import topology.algebra.order.liminf_limsup
/-!
# Measure spaces
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
The definition of a measure and a measure space are in `measure_theory.measure_space_def`, with
only a few basic properties. This file provides many more properties of these objects.
This separation allows the measurability tactic to import only the file `measure_space_def`, and to
be available in `measure_space` (through `measurable_space`).
Given a measurable space `α`, a measure on `α` is a function that sends measurable sets to the
extended nonnegative reals that satisfies the following conditions:
1. `μ ∅ = 0`;
2. `μ` is countably additive. This means that the measure of a countable union of pairwise disjoint
sets is equal to the measure of the individual sets.
Every measure can be canonically extended to an outer measure, so that it assigns values to
all subsets, not just the measurable subsets. On the other hand, a measure that is countably
additive on measurable sets can be restricted to measurable sets to obtain a measure.
In this file a measure is defined to be an outer measure that is countably additive on
measurable sets, with the additional assumption that the outer measure is the canonical
extension of the restricted measure.
Measures on `α` form a complete lattice, and are closed under scalar multiplication with `ℝ≥0∞`.
We introduce the following typeclasses for measures:
* `is_probability_measure μ`: `μ univ = 1`;
* `is_finite_measure μ`: `μ univ < ∞`;
* `sigma_finite μ`: there exists a countable collection of sets that cover `univ`
where `μ` is finite;
* `is_locally_finite_measure μ` : `∀ x, ∃ s ∈ 𝓝 x, μ s < ∞`;
* `has_no_atoms μ` : `∀ x, μ {x} = 0`; possibly should be redefined as
`∀ s, 0 < μ s → ∃ t ⊆ s, 0 < μ t ∧ μ t < μ s`.
Given a measure, the null sets are the sets where `μ s = 0`, where `μ` denotes the corresponding
outer measure (so `s` might not be measurable). We can then define the completion of `μ` as the
measure on the least `σ`-algebra that also contains all null sets, by defining the measure to be `0`
on the null sets.
## Main statements
* `completion` is the completion of a measure to all null measurable sets.
* `measure.of_measurable` and `outer_measure.to_measure` are two important ways to define a measure.
## Implementation notes
Given `μ : measure α`, `μ s` is the value of the *outer measure* applied to `s`.
This conveniently allows us to apply the measure to sets without proving that they are measurable.
We get countable subadditivity for all sets, but only countable additivity for measurable sets.
You often don't want to define a measure via its constructor.
Two ways that are sometimes more convenient:
* `measure.of_measurable` is a way to define a measure by only giving its value on measurable sets
and proving the properties (1) and (2) mentioned above.
* `outer_measure.to_measure` is a way of obtaining a measure from an outer measure by showing that
all measurable sets in the measurable space are Carathéodory measurable.
To prove that two measures are equal, there are multiple options:
* `ext`: two measures are equal if they are equal on all measurable sets.
* `ext_of_generate_from_of_Union`: two measures are equal if they are equal on a π-system generating
the measurable sets, if the π-system contains a spanning increasing sequence of sets where the
measures take finite value (in particular the measures are σ-finite). This is a special case of
the more general `ext_of_generate_from_of_cover`
* `ext_of_generate_finite`: two finite measures are equal if they are equal on a π-system
generating the measurable sets. This is a special case of `ext_of_generate_from_of_Union` using
`C ∪ {univ}`, but is easier to work with.
A `measure_space` is a class that is a measurable space with a canonical measure.
The measure is denoted `volume`.
## References
* <https://en.wikipedia.org/wiki/Measure_(mathematics)>
* <https://en.wikipedia.org/wiki/Complete_measure>
* <https://en.wikipedia.org/wiki/Almost_everywhere>
## Tags
measure, almost everywhere, measure space, completion, null set, null measurable set
-/
noncomputable theory
open set filter (hiding map) function measurable_space topological_space (second_countable_topology)
open_locale classical topology big_operators filter ennreal nnreal interval measure_theory
variables {α β γ δ ι R R' : Type*}
namespace measure_theory
section
variables {m : measurable_space α} {μ μ₁ μ₂ : measure α} {s s₁ s₂ t : set α}
instance ae_is_measurably_generated : is_measurably_generated μ.ae :=
⟨λ s hs, let ⟨t, hst, htm, htμ⟩ := exists_measurable_superset_of_null hs in
⟨tᶜ, compl_mem_ae_iff.2 htμ, htm.compl, compl_subset_comm.1 hst⟩⟩
/-- See also `measure_theory.ae_restrict_uIoc_iff`. -/
lemma ae_uIoc_iff [linear_order α] {a b : α} {P : α → Prop} :
(∀ᵐ x ∂μ, x ∈ Ι a b → P x) ↔ (∀ᵐ x ∂μ, x ∈ Ioc a b → P x) ∧ (∀ᵐ x ∂μ, x ∈ Ioc b a → P x) :=
by simp only [uIoc_eq_union, mem_union, or_imp_distrib, eventually_and]
lemma measure_union (hd : disjoint s₁ s₂) (h : measurable_set s₂) :
μ (s₁ ∪ s₂) = μ s₁ + μ s₂ :=
measure_union₀ h.null_measurable_set hd.ae_disjoint
lemma measure_union' (hd : disjoint s₁ s₂) (h : measurable_set s₁) :
μ (s₁ ∪ s₂) = μ s₁ + μ s₂ :=
measure_union₀' h.null_measurable_set hd.ae_disjoint
lemma measure_inter_add_diff (s : set α) (ht : measurable_set t) :
μ (s ∩ t) + μ (s \ t) = μ s :=
measure_inter_add_diff₀ _ ht.null_measurable_set
lemma measure_diff_add_inter (s : set α) (ht : measurable_set t) :
μ (s \ t) + μ (s ∩ t) = μ s :=
(add_comm _ _).trans (measure_inter_add_diff s ht)
lemma measure_union_add_inter (s : set α) (ht : measurable_set t) :
μ (s ∪ t) + μ (s ∩ t) = μ s + μ t :=
by { rw [← measure_inter_add_diff (s ∪ t) ht, set.union_inter_cancel_right,
union_diff_right, ← measure_inter_add_diff s ht], ac_refl }
lemma measure_union_add_inter' (hs : measurable_set s) (t : set α) :
μ (s ∪ t) + μ (s ∩ t) = μ s + μ t :=
by rw [union_comm, inter_comm, measure_union_add_inter t hs, add_comm]
lemma measure_add_measure_compl (h : measurable_set s) :
μ s + μ sᶜ = μ univ :=
measure_add_measure_compl₀ h.null_measurable_set
lemma measure_bUnion₀ {s : set β} {f : β → set α} (hs : s.countable)
(hd : s.pairwise (ae_disjoint μ on f)) (h : ∀ b ∈ s, null_measurable_set (f b) μ) :
μ (⋃ b ∈ s, f b) = ∑' p : s, μ (f p) :=
begin
haveI := hs.to_encodable,
rw bUnion_eq_Union,
exact measure_Union₀ (hd.on_injective subtype.coe_injective $ λ x, x.2) (λ x, h x x.2)
end
lemma measure_bUnion {s : set β} {f : β → set α} (hs : s.countable)
(hd : s.pairwise_disjoint f) (h : ∀ b ∈ s, measurable_set (f b)) :
μ (⋃ b ∈ s, f b) = ∑' p : s, μ (f p) :=
measure_bUnion₀ hs hd.ae_disjoint (λ b hb, (h b hb).null_measurable_set)
lemma measure_sUnion₀ {S : set (set α)} (hs : S.countable)
(hd : S.pairwise (ae_disjoint μ)) (h : ∀ s ∈ S, null_measurable_set s μ) :
μ (⋃₀ S) = ∑' s : S, μ s :=
by rw [sUnion_eq_bUnion, measure_bUnion₀ hs hd h]
lemma measure_sUnion {S : set (set α)} (hs : S.countable)
(hd : S.pairwise disjoint) (h : ∀ s ∈ S, measurable_set s) :
μ (⋃₀ S) = ∑' s : S, μ s :=
by rw [sUnion_eq_bUnion, measure_bUnion hs hd h]
lemma measure_bUnion_finset₀ {s : finset ι} {f : ι → set α}
(hd : set.pairwise ↑s (ae_disjoint μ on f)) (hm : ∀ b ∈ s, null_measurable_set (f b) μ) :
μ (⋃ b ∈ s, f b) = ∑ p in s, μ (f p) :=
begin
rw [← finset.sum_attach, finset.attach_eq_univ, ← tsum_fintype],
exact measure_bUnion₀ s.countable_to_set hd hm
end
lemma measure_bUnion_finset {s : finset ι} {f : ι → set α} (hd : pairwise_disjoint ↑s f)
(hm : ∀ b ∈ s, measurable_set (f b)) :
μ (⋃ b ∈ s, f b) = ∑ p in s, μ (f p) :=
measure_bUnion_finset₀ hd.ae_disjoint (λ b hb, (hm b hb).null_measurable_set)
/-- The measure of a disjoint union (even uncountable) of measurable sets is at least the sum of
the measures of the sets. -/
lemma tsum_meas_le_meas_Union_of_disjoint {ι : Type*} [measurable_space α] (μ : measure α)
{As : ι → set α} (As_mble : ∀ (i : ι), measurable_set (As i))
(As_disj : pairwise (disjoint on As)) :
∑' i, μ (As i) ≤ μ (⋃ i, As i) :=
begin
rcases (show summable (λ i, μ (As i)), from ennreal.summable) with ⟨S, hS⟩,
rw [hS.tsum_eq],
refine tendsto_le_of_eventually_le hS tendsto_const_nhds (eventually_of_forall _),
intros s,
rw ← measure_bUnion_finset (λ i hi j hj hij, As_disj hij) (λ i _, As_mble i),
exact measure_mono (Union₂_subset_Union (λ (i : ι), i ∈ s) (λ (i : ι), As i)),
end
/-- If `s` is a countable set, then the measure of its preimage can be found as the sum of measures
of the fibers `f ⁻¹' {y}`. -/
lemma tsum_measure_preimage_singleton {s : set β} (hs : s.countable) {f : α → β}
(hf : ∀ y ∈ s, measurable_set (f ⁻¹' {y})) :
∑' b : s, μ (f ⁻¹' {↑b}) = μ (f ⁻¹' s) :=
by rw [← set.bUnion_preimage_singleton, measure_bUnion hs (pairwise_disjoint_fiber _ _) hf]
/-- If `s` is a `finset`, then the measure of its preimage can be found as the sum of measures
of the fibers `f ⁻¹' {y}`. -/
lemma sum_measure_preimage_singleton (s : finset β) {f : α → β}
(hf : ∀ y ∈ s, measurable_set (f ⁻¹' {y})) :
∑ b in s, μ (f ⁻¹' {b}) = μ (f ⁻¹' ↑s) :=
by simp only [← measure_bUnion_finset (pairwise_disjoint_fiber _ _) hf,
finset.set_bUnion_preimage_singleton]
lemma measure_diff_null' (h : μ (s₁ ∩ s₂) = 0) : μ (s₁ \ s₂) = μ s₁ :=
measure_congr $ diff_ae_eq_self.2 h
lemma measure_diff_null (h : μ s₂ = 0) : μ (s₁ \ s₂) = μ s₁ :=
measure_diff_null' $ measure_mono_null (inter_subset_right _ _) h
lemma measure_add_diff (hs : measurable_set s) (t : set α) : μ s + μ (t \ s) = μ (s ∪ t) :=
by rw [← measure_union' disjoint_sdiff_right hs, union_diff_self]
lemma measure_diff' (s : set α) (hm : measurable_set t) (h_fin : μ t ≠ ∞) :
μ (s \ t) = μ (s ∪ t) - μ t :=
eq.symm $ ennreal.sub_eq_of_add_eq h_fin $ by rw [add_comm, measure_add_diff hm, union_comm]
lemma measure_diff (h : s₂ ⊆ s₁) (h₂ : measurable_set s₂) (h_fin : μ s₂ ≠ ∞) :
μ (s₁ \ s₂) = μ s₁ - μ s₂ :=
by rw [measure_diff' _ h₂ h_fin, union_eq_self_of_subset_right h]
lemma le_measure_diff : μ s₁ - μ s₂ ≤ μ (s₁ \ s₂) :=
tsub_le_iff_left.2 $
calc μ s₁ ≤ μ (s₂ ∪ s₁) : measure_mono (subset_union_right _ _)
... = μ (s₂ ∪ s₁ \ s₂) : congr_arg μ union_diff_self.symm
... ≤ μ s₂ + μ (s₁ \ s₂) : measure_union_le _ _
lemma measure_diff_lt_of_lt_add (hs : measurable_set s) (hst : s ⊆ t)
(hs' : μ s ≠ ∞) {ε : ℝ≥0∞} (h : μ t < μ s + ε) : μ (t \ s) < ε :=
begin
rw [measure_diff hst hs hs'], rw add_comm at h,
exact ennreal.sub_lt_of_lt_add (measure_mono hst) h
end
lemma measure_diff_le_iff_le_add (hs : measurable_set s) (hst : s ⊆ t)
(hs' : μ s ≠ ∞) {ε : ℝ≥0∞} : μ (t \ s) ≤ ε ↔ μ t ≤ μ s + ε :=
by rwa [measure_diff hst hs hs', tsub_le_iff_left]
lemma measure_eq_measure_of_null_diff {s t : set α} (hst : s ⊆ t) (h_nulldiff : μ (t \ s) = 0) :
μ s = μ t :=
measure_congr (hst.eventually_le.antisymm $ ae_le_set.mpr h_nulldiff)
lemma measure_eq_measure_of_between_null_diff {s₁ s₂ s₃ : set α}
(h12 : s₁ ⊆ s₂) (h23 : s₂ ⊆ s₃) (h_nulldiff : μ (s₃ \ s₁) = 0) :
(μ s₁ = μ s₂) ∧ (μ s₂ = μ s₃) :=
begin
have le12 : μ s₁ ≤ μ s₂ := measure_mono h12,
have le23 : μ s₂ ≤ μ s₃ := measure_mono h23,
have key : μ s₃ ≤ μ s₁ := calc
μ s₃ = μ ((s₃ \ s₁) ∪ s₁) : by rw (diff_union_of_subset (h12.trans h23))
... ≤ μ (s₃ \ s₁) + μ s₁ : measure_union_le _ _
... = μ s₁ : by simp only [h_nulldiff, zero_add],
exact ⟨le12.antisymm (le23.trans key), le23.antisymm (key.trans le12)⟩,
end
lemma measure_eq_measure_smaller_of_between_null_diff {s₁ s₂ s₃ : set α}
(h12 : s₁ ⊆ s₂) (h23 : s₂ ⊆ s₃) (h_nulldiff : μ (s₃ \ s₁) = 0) : μ s₁ = μ s₂ :=
(measure_eq_measure_of_between_null_diff h12 h23 h_nulldiff).1
lemma measure_eq_measure_larger_of_between_null_diff {s₁ s₂ s₃ : set α}
(h12 : s₁ ⊆ s₂) (h23 : s₂ ⊆ s₃) (h_nulldiff : μ (s₃ \ s₁) = 0) : μ s₂ = μ s₃ :=
(measure_eq_measure_of_between_null_diff h12 h23 h_nulldiff).2
lemma measure_compl (h₁ : measurable_set s) (h_fin : μ s ≠ ∞) : μ (sᶜ) = μ univ - μ s :=
by { rw compl_eq_univ_diff, exact measure_diff (subset_univ s) h₁ h_fin }
@[simp] lemma union_ae_eq_left_iff_ae_subset : (s ∪ t : set α) =ᵐ[μ] s ↔ t ≤ᵐ[μ] s :=
begin
rw ae_le_set,
refine ⟨λ h, by simpa only [union_diff_left] using (ae_eq_set.mp h).1,
λ h, eventually_le_antisymm_iff.mpr
⟨by rwa [ae_le_set, union_diff_left], has_subset.subset.eventually_le $ subset_union_left s t⟩⟩,
end
@[simp] lemma union_ae_eq_right_iff_ae_subset : (s ∪ t : set α) =ᵐ[μ] t ↔ s ≤ᵐ[μ] t :=
by rw [union_comm, union_ae_eq_left_iff_ae_subset]
lemma ae_eq_of_ae_subset_of_measure_ge (h₁ : s ≤ᵐ[μ] t) (h₂ : μ t ≤ μ s) (hsm : measurable_set s)
(ht : μ t ≠ ∞) : s =ᵐ[μ] t :=
begin
refine eventually_le_antisymm_iff.mpr ⟨h₁, ae_le_set.mpr _⟩,
replace h₂ : μ t = μ s, from h₂.antisymm (measure_mono_ae h₁),
replace ht : μ s ≠ ∞, from h₂ ▸ ht,
rw [measure_diff' t hsm ht, measure_congr (union_ae_eq_left_iff_ae_subset.mpr h₁), h₂, tsub_self],
end
/-- If `s ⊆ t`, `μ t ≤ μ s`, `μ t ≠ ∞`, and `s` is measurable, then `s =ᵐ[μ] t`. -/
lemma ae_eq_of_subset_of_measure_ge (h₁ : s ⊆ t) (h₂ : μ t ≤ μ s) (hsm : measurable_set s)
(ht : μ t ≠ ∞) : s =ᵐ[μ] t :=
ae_eq_of_ae_subset_of_measure_ge (has_subset.subset.eventually_le h₁) h₂ hsm ht
lemma measure_Union_congr_of_subset [countable β] {s : β → set α} {t : β → set α}
(hsub : ∀ b, s b ⊆ t b) (h_le : ∀ b, μ (t b) ≤ μ (s b)) :
μ (⋃ b, s b) = μ (⋃ b, t b) :=
begin
rcases em (∃ b, μ (t b) = ∞) with ⟨b, hb⟩|htop,
{ calc μ (⋃ b, s b) = ∞ : top_unique (hb ▸ (h_le b).trans $ measure_mono $ subset_Union _ _)
... = μ (⋃ b, t b) : eq.symm $ top_unique $ hb ▸ measure_mono $ subset_Union _ _ },
push_neg at htop,
refine le_antisymm (measure_mono (Union_mono hsub)) _,
set M := to_measurable μ,
have H : ∀ b, (M (t b) ∩ M (⋃ b, s b) : set α) =ᵐ[μ] M (t b),
{ refine λ b, ae_eq_of_subset_of_measure_ge (inter_subset_left _ _) _ _ _,
{ calc μ (M (t b)) = μ (t b) : measure_to_measurable _
... ≤ μ (s b) : h_le b
... ≤ μ (M (t b) ∩ M (⋃ b, s b)) : measure_mono $
subset_inter ((hsub b).trans $ subset_to_measurable _ _)
((subset_Union _ _).trans $ subset_to_measurable _ _) },
{ exact (measurable_set_to_measurable _ _).inter (measurable_set_to_measurable _ _) },
{ rw measure_to_measurable, exact htop b } },
calc μ (⋃ b, t b) ≤ μ (⋃ b, M (t b)) :
measure_mono (Union_mono $ λ b, subset_to_measurable _ _)
... = μ (⋃ b, M (t b) ∩ M (⋃ b, s b)) :
measure_congr (eventually_eq.countable_Union H).symm
... ≤ μ (M (⋃ b, s b)) :
measure_mono (Union_subset $ λ b, inter_subset_right _ _)
... = μ (⋃ b, s b) : measure_to_measurable _
end
lemma measure_union_congr_of_subset {t₁ t₂ : set α} (hs : s₁ ⊆ s₂) (hsμ : μ s₂ ≤ μ s₁)
(ht : t₁ ⊆ t₂) (htμ : μ t₂ ≤ μ t₁) :
μ (s₁ ∪ t₁) = μ (s₂ ∪ t₂) :=
begin
rw [union_eq_Union, union_eq_Union],
exact measure_Union_congr_of_subset (bool.forall_bool.2 ⟨ht, hs⟩) (bool.forall_bool.2 ⟨htμ, hsμ⟩)
end
@[simp] lemma measure_Union_to_measurable [countable β] (s : β → set α) :
μ (⋃ b, to_measurable μ (s b)) = μ (⋃ b, s b) :=
eq.symm $ measure_Union_congr_of_subset (λ b, subset_to_measurable _ _)
(λ b, (measure_to_measurable _).le)
lemma measure_bUnion_to_measurable {I : set β} (hc : I.countable) (s : β → set α) :
μ (⋃ b ∈ I, to_measurable μ (s b)) = μ (⋃ b ∈ I, s b) :=
by { haveI := hc.to_encodable, simp only [bUnion_eq_Union, measure_Union_to_measurable] }
@[simp] lemma measure_to_measurable_union : μ (to_measurable μ s ∪ t) = μ (s ∪ t) :=
eq.symm $ measure_union_congr_of_subset (subset_to_measurable _ _) (measure_to_measurable _).le
subset.rfl le_rfl
@[simp] lemma measure_union_to_measurable : μ (s ∪ to_measurable μ t) = μ (s ∪ t) :=
eq.symm $ measure_union_congr_of_subset subset.rfl le_rfl (subset_to_measurable _ _)
(measure_to_measurable _).le
lemma sum_measure_le_measure_univ {s : finset ι} {t : ι → set α} (h : ∀ i ∈ s, measurable_set (t i))
(H : set.pairwise_disjoint ↑s t) :
∑ i in s, μ (t i) ≤ μ (univ : set α) :=
by { rw ← measure_bUnion_finset H h, exact measure_mono (subset_univ _) }
lemma tsum_measure_le_measure_univ {s : ι → set α} (hs : ∀ i, measurable_set (s i))
(H : pairwise (disjoint on s)) :
∑' i, μ (s i) ≤ μ (univ : set α) :=
begin
rw [ennreal.tsum_eq_supr_sum],
exact supr_le (λ s, sum_measure_le_measure_univ (λ i hi, hs i) (λ i hi j hj hij, H hij))
end
/-- Pigeonhole principle for measure spaces: if `∑' i, μ (s i) > μ univ`, then
one of the intersections `s i ∩ s j` is not empty. -/
lemma exists_nonempty_inter_of_measure_univ_lt_tsum_measure {m : measurable_space α} (μ : measure α)
{s : ι → set α} (hs : ∀ i, measurable_set (s i)) (H : μ (univ : set α) < ∑' i, μ (s i)) :
∃ i j (h : i ≠ j), (s i ∩ s j).nonempty :=
begin
contrapose! H,
apply tsum_measure_le_measure_univ hs,
intros i j hij,
rw [function.on_fun, disjoint_iff_inf_le],
exact λ x hx, H i j hij ⟨x, hx⟩
end
/-- Pigeonhole principle for measure spaces: if `s` is a `finset` and
`∑ i in s, μ (t i) > μ univ`, then one of the intersections `t i ∩ t j` is not empty. -/
lemma exists_nonempty_inter_of_measure_univ_lt_sum_measure {m : measurable_space α} (μ : measure α)
{s : finset ι} {t : ι → set α} (h : ∀ i ∈ s, measurable_set (t i))
(H : μ (univ : set α) < ∑ i in s, μ (t i)) :
∃ (i ∈ s) (j ∈ s) (h : i ≠ j), (t i ∩ t j).nonempty :=
begin
contrapose! H,
apply sum_measure_le_measure_univ h,
intros i hi j hj hij,
rw [function.on_fun, disjoint_iff_inf_le],
exact λ x hx, H i hi j hj hij ⟨x, hx⟩
end
/-- If two sets `s` and `t` are included in a set `u`, and `μ s + μ t > μ u`,
then `s` intersects `t`. Version assuming that `t` is measurable. -/
lemma nonempty_inter_of_measure_lt_add
{m : measurable_space α} (μ : measure α)
{s t u : set α} (ht : measurable_set t) (h's : s ⊆ u) (h't : t ⊆ u)
(h : μ u < μ s + μ t) :
(s ∩ t).nonempty :=
begin
rw ←set.not_disjoint_iff_nonempty_inter,
contrapose! h,
calc μ s + μ t = μ (s ∪ t) : (measure_union h ht).symm
... ≤ μ u : measure_mono (union_subset h's h't)
end
/-- If two sets `s` and `t` are included in a set `u`, and `μ s + μ t > μ u`,
then `s` intersects `t`. Version assuming that `s` is measurable. -/
lemma nonempty_inter_of_measure_lt_add'
{m : measurable_space α} (μ : measure α)
{s t u : set α} (hs : measurable_set s) (h's : s ⊆ u) (h't : t ⊆ u)
(h : μ u < μ s + μ t) :
(s ∩ t).nonempty :=
begin
rw add_comm at h,
rw inter_comm,
exact nonempty_inter_of_measure_lt_add μ hs h't h's h
end
/-- Continuity from below: the measure of the union of a directed sequence of (not necessarily
-measurable) sets is the supremum of the measures. -/
lemma measure_Union_eq_supr [countable ι] {s : ι → set α} (hd : directed (⊆) s) :
μ (⋃ i, s i) = ⨆ i, μ (s i) :=
begin
casesI nonempty_encodable ι,
-- WLOG, `ι = ℕ`
generalize ht : function.extend encodable.encode s ⊥ = t,
replace hd : directed (⊆) t := ht ▸ hd.extend_bot encodable.encode_injective,
suffices : μ (⋃ n, t n) = ⨆ n, μ (t n),
{ simp only [← ht, encodable.encode_injective.apply_extend μ, ← supr_eq_Union,
supr_extend_bot encodable.encode_injective, (∘), pi.bot_apply, bot_eq_empty,
measure_empty] at this,
exact this.trans (supr_extend_bot encodable.encode_injective _) },
unfreezingI { clear_dependent ι },
-- The `≥` inequality is trivial
refine le_antisymm _ (supr_le $ λ i, measure_mono $ subset_Union _ _),
-- Choose `T n ⊇ t n` of the same measure, put `Td n = disjointed T`
set T : ℕ → set α := λ n, to_measurable μ (t n),
set Td : ℕ → set α := disjointed T,
have hm : ∀ n, measurable_set (Td n),
from measurable_set.disjointed (λ n, measurable_set_to_measurable _ _),
calc μ (⋃ n, t n) ≤ μ (⋃ n, T n) : measure_mono (Union_mono $ λ i, subset_to_measurable _ _)
... = μ (⋃ n, Td n) : by rw [Union_disjointed]
... ≤ ∑' n, μ (Td n) : measure_Union_le _
... = ⨆ I : finset ℕ, ∑ n in I, μ (Td n) : ennreal.tsum_eq_supr_sum
... ≤ ⨆ n, μ (t n) : supr_le (λ I, _),
rcases hd.finset_le I with ⟨N, hN⟩,
calc ∑ n in I, μ (Td n) = μ (⋃ n ∈ I, Td n) :
(measure_bUnion_finset ((disjoint_disjointed T).set_pairwise I) (λ n _, hm n)).symm
... ≤ μ (⋃ n ∈ I, T n) : measure_mono (Union₂_mono $ λ n hn, disjointed_subset _ _)
... = μ (⋃ n ∈ I, t n) : measure_bUnion_to_measurable I.countable_to_set _
... ≤ μ (t N) : measure_mono (Union₂_subset hN)
... ≤ ⨆ n, μ (t n) : le_supr (μ ∘ t) N,
end
lemma measure_bUnion_eq_supr {s : ι → set α} {t : set ι} (ht : t.countable)
(hd : directed_on ((⊆) on s) t) :
μ (⋃ i ∈ t, s i) = ⨆ i ∈ t, μ (s i) :=
begin
haveI := ht.to_encodable,
rw [bUnion_eq_Union, measure_Union_eq_supr hd.directed_coe, ← supr_subtype'']
end
/-- Continuity from above: the measure of the intersection of a decreasing sequence of measurable
sets is the infimum of the measures. -/
lemma measure_Inter_eq_infi [countable ι] {s : ι → set α}
(h : ∀ i, measurable_set (s i)) (hd : directed (⊇) s) (hfin : ∃ i, μ (s i) ≠ ∞) :
μ (⋂ i, s i) = (⨅ i, μ (s i)) :=
begin
rcases hfin with ⟨k, hk⟩,
have : ∀ t ⊆ s k, μ t ≠ ∞, from λ t ht, ne_top_of_le_ne_top hk (measure_mono ht),
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) (measurable_set.Inter h) (this _ (Inter_subset _ k)),
diff_Inter, measure_Union_eq_supr],
{ congr' 1,
refine le_antisymm (supr_mono' $ λ i, _) (supr_mono $ λ i, _),
{ rcases hd i k with ⟨j, hji, hjk⟩,
use j,
rw [← measure_diff hjk (h _) (this _ hjk)],
exact measure_mono (diff_subset_diff_right hji) },
{ rw [tsub_le_iff_right, ← measure_union disjoint_sdiff_left (h i), set.union_comm],
exact measure_mono (diff_subset_iff.1 $ subset.refl _) } },
{ exact hd.mono_comp _ (λ _ _, diff_subset_diff_right) }
end
/-- Continuity from below: the measure of the union of an increasing sequence of measurable sets
is the limit of the measures. -/
lemma tendsto_measure_Union [semilattice_sup ι] [countable ι] {s : ι → set α} (hm : monotone s) :
tendsto (μ ∘ s) at_top (𝓝 (μ (⋃ n, s n))) :=
begin
rw measure_Union_eq_supr (directed_of_sup hm),
exact tendsto_at_top_supr (λ n m hnm, measure_mono $ hm hnm)
end
/-- Continuity from above: the measure of the intersection of a decreasing sequence of measurable
sets is the limit of the measures. -/
lemma tendsto_measure_Inter [countable ι] [semilattice_sup ι] {s : ι → set α}
(hs : ∀ n, measurable_set (s n)) (hm : antitone s) (hf : ∃ i, μ (s i) ≠ ∞) :
tendsto (μ ∘ s) at_top (𝓝 (μ (⋂ n, s n))) :=
begin
rw measure_Inter_eq_infi hs (directed_of_sup hm) hf,
exact tendsto_at_top_infi (λ n m hnm, measure_mono $ hm hnm),
end
/-- The measure of the intersection of a decreasing sequence of measurable
sets indexed by a linear order with first countable topology is the limit of the measures. -/
lemma tendsto_measure_bInter_gt {ι : Type*} [linear_order ι] [topological_space ι]
[order_topology ι] [densely_ordered ι] [topological_space.first_countable_topology ι]
{s : ι → set α} {a : ι}
(hs : ∀ r > a, measurable_set (s r)) (hm : ∀ i j, a < i → i ≤ j → s i ⊆ s j)
(hf : ∃ r > a, μ (s r) ≠ ∞) :
tendsto (μ ∘ s) (𝓝[Ioi a] a) (𝓝 (μ (⋂ r > a, s r))) :=
begin
refine tendsto_order.2 ⟨λ l hl, _, λ L hL, _⟩,
{ filter_upwards [self_mem_nhds_within] with r hr
using hl.trans_le (measure_mono (bInter_subset_of_mem hr)), },
obtain ⟨u, u_anti, u_pos, u_lim⟩ : ∃ (u : ℕ → ι), strict_anti u ∧ (∀ (n : ℕ), a < u n)
∧ tendsto u at_top (𝓝 a),
{ rcases hf with ⟨r, ar, hr⟩,
rcases exists_seq_strict_anti_tendsto' ar with ⟨w, w_anti, w_mem, w_lim⟩,
exact ⟨w, w_anti, λ n, (w_mem n).1, w_lim⟩ },
have A : tendsto (μ ∘ (s ∘ u)) at_top (𝓝(μ (⋂ n, s (u n)))),
{ refine tendsto_measure_Inter (λ n, hs _ (u_pos n)) _ _,
{ intros m n hmn,
exact hm _ _ (u_pos n) (u_anti.antitone hmn) },
{ rcases hf with ⟨r, rpos, hr⟩,
obtain ⟨n, hn⟩ : ∃ (n : ℕ), u n < r := ((tendsto_order.1 u_lim).2 r rpos).exists,
refine ⟨n, ne_of_lt (lt_of_le_of_lt _ hr.lt_top)⟩,
exact measure_mono (hm _ _ (u_pos n) hn.le) } },
have B : (⋂ n, s (u n)) = (⋂ r > a, s r),
{ apply subset.antisymm,
{ simp only [subset_Inter_iff, gt_iff_lt],
intros r rpos,
obtain ⟨n, hn⟩ : ∃ n, u n < r := ((tendsto_order.1 u_lim).2 _ rpos).exists,
exact subset.trans (Inter_subset _ n) (hm (u n) r (u_pos n) hn.le) },
{ simp only [subset_Inter_iff, gt_iff_lt],
intros n,
apply bInter_subset_of_mem,
exact u_pos n } },
rw B at A,
obtain ⟨n, hn⟩ : ∃ n, μ (s (u n)) < L := ((tendsto_order.1 A).2 _ hL).exists,
have : Ioc a (u n) ∈ 𝓝[>] a := Ioc_mem_nhds_within_Ioi ⟨le_rfl, u_pos n⟩,
filter_upwards [this] with r hr using lt_of_le_of_lt (measure_mono (hm _ _ hr.1 hr.2)) hn,
end
/-- One direction of the **Borel-Cantelli lemma**: if (sᵢ) is a sequence of sets such
that `∑ μ sᵢ` is finite, then the limit superior of the `sᵢ` is a null set. -/
lemma measure_limsup_eq_zero {s : ℕ → set α} (hs : ∑' i, μ (s i) ≠ ∞) : μ (limsup s at_top) = 0 :=
begin
-- First we replace the sequence `sₙ` with a sequence of measurable sets `tₙ ⊇ sₙ` of the same
-- measure.
set t : ℕ → set α := λ n, to_measurable μ (s n),
have ht : ∑' i, μ (t i) ≠ ∞, by simpa only [t, measure_to_measurable] using hs,
suffices : μ (limsup t at_top) = 0,
{ have A : s ≤ t := λ n, subset_to_measurable μ (s n),
-- TODO default args fail
exact measure_mono_null (limsup_le_limsup (eventually_of_forall (pi.le_def.mp A))
is_cobounded_le_of_bot is_bounded_le_of_top) this },
-- Next we unfold `limsup` for sets and replace equality with an inequality
simp only [limsup_eq_infi_supr_of_nat', set.infi_eq_Inter, set.supr_eq_Union,
← nonpos_iff_eq_zero],
-- Finally, we estimate `μ (⋃ i, t (i + n))` by `∑ i', μ (t (i + n))`
refine le_of_tendsto_of_tendsto'
(tendsto_measure_Inter (λ i, measurable_set.Union (λ b, measurable_set_to_measurable _ _)) _
⟨0, ne_top_of_le_ne_top ht (measure_Union_le t)⟩)
(ennreal.tendsto_sum_nat_add (μ ∘ t) ht) (λ n, measure_Union_le _),
intros n m hnm x,
simp only [set.mem_Union],
exact λ ⟨i, hi⟩, ⟨i + (m - n), by simpa only [add_assoc, tsub_add_cancel_of_le hnm] using hi⟩
end
lemma measure_liminf_eq_zero {s : ℕ → set α} (h : ∑' i, μ (s i) ≠ ⊤) : μ (liminf s at_top) = 0 :=
begin
rw ← le_zero_iff,
have : liminf s at_top ≤ limsup s at_top :=
liminf_le_limsup (by is_bounded_default) (by is_bounded_default),
exact (μ.mono this).trans (by simp [measure_limsup_eq_zero h]),
end
lemma limsup_ae_eq_of_forall_ae_eq (s : ℕ → set α) {t : set α} (h : ∀ n, s n =ᵐ[μ] t) :
-- Need `@` below because of diamond; see gh issue #16932
@limsup (set α) ℕ _ s at_top =ᵐ[μ] t :=
begin
simp_rw ae_eq_set at h ⊢,
split,
{ rw at_top.limsup_sdiff s t,
apply measure_limsup_eq_zero,
simp [h], },
{ rw at_top.sdiff_limsup s t,
apply measure_liminf_eq_zero,
simp [h], },
end
lemma liminf_ae_eq_of_forall_ae_eq (s : ℕ → set α) {t : set α} (h : ∀ n, s n =ᵐ[μ] t) :
-- Need `@` below because of diamond; see gh issue #16932
@liminf (set α) ℕ _ s at_top =ᵐ[μ] t :=
begin
simp_rw ae_eq_set at h ⊢,
split,
{ rw at_top.liminf_sdiff s t,
apply measure_liminf_eq_zero,
simp [h], },
{ rw at_top.sdiff_liminf s t,
apply measure_limsup_eq_zero,
simp [h], },
end
lemma measure_if {x : β} {t : set β} {s : set α} :
μ (if x ∈ t then s else ∅) = indicator t (λ _, μ s) x :=
by { split_ifs; simp [h] }
end
section outer_measure
variables [ms : measurable_space α] {s t : set α}
include ms
/-- Obtain a measure by giving an outer measure where all sets in the σ-algebra are
Carathéodory measurable. -/
def outer_measure.to_measure (m : outer_measure α) (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 (μ : measure α) : ms ≤ μ.to_outer_measure.caratheodory :=
λ s hs t, (measure_inter_add_diff _ hs).symm
@[simp] lemma to_measure_to_outer_measure (m : outer_measure α) (h : ms ≤ m.caratheodory) :
(m.to_measure h).to_outer_measure = m.trim := rfl
@[simp] lemma to_measure_apply (m : outer_measure α) (h : ms ≤ m.caratheodory)
{s : set α} (hs : measurable_set s) : m.to_measure h s = m s :=
m.trim_eq hs
lemma le_to_measure_apply (m : outer_measure α) (h : ms ≤ m.caratheodory) (s : set α) :
m s ≤ m.to_measure h s :=
m.le_trim s
lemma to_measure_apply₀ (m : outer_measure α) (h : ms ≤ m.caratheodory)
{s : set α} (hs : null_measurable_set s (m.to_measure h)) : m.to_measure h s = m s :=
begin
refine le_antisymm _ (le_to_measure_apply _ _ _),
rcases hs.exists_measurable_subset_ae_eq with ⟨t, hts, htm, heq⟩,
calc m.to_measure h s = m.to_measure h t : measure_congr heq.symm
... = m t : to_measure_apply m h htm
... ≤ m s : m.mono hts
end
@[simp] lemma to_outer_measure_to_measure {μ : measure α} :
μ.to_outer_measure.to_measure (le_to_outer_measure_caratheodory _) = μ :=
measure.ext $ λ s, μ.to_outer_measure.trim_eq
@[simp] lemma bounded_by_measure (μ : measure α) :
outer_measure.bounded_by μ = μ.to_outer_measure :=
μ.to_outer_measure.bounded_by_eq_self
end outer_measure
variables {m0 : measurable_space α} [measurable_space β] [measurable_space γ]
variables {μ μ₁ μ₂ μ₃ ν ν' ν₁ ν₂ : measure α} {s s' t : set α}
namespace measure
/-- If `u` is a superset of `t` with the same (finite) measure (both sets possibly non-measurable),
then for any measurable set `s` one also has `μ (t ∩ s) = μ (u ∩ s)`. -/
lemma measure_inter_eq_of_measure_eq {s t u : set α} (hs : measurable_set s)
(h : μ t = μ u) (htu : t ⊆ u) (ht_ne_top : μ t ≠ ∞) :
μ (t ∩ s) = μ (u ∩ s) :=
begin
rw h at ht_ne_top,
refine le_antisymm (measure_mono (inter_subset_inter_left _ htu)) _,
have A : μ (u ∩ s) + μ (u \ s) ≤ μ (t ∩ s) + μ (u \ s) := calc
μ (u ∩ s) + μ (u \ s) = μ u : measure_inter_add_diff _ hs
... = μ t : h.symm
... = μ (t ∩ s) + μ (t \ s) : (measure_inter_add_diff _ hs).symm
... ≤ μ (t ∩ s) + μ (u \ s) :
add_le_add le_rfl (measure_mono (diff_subset_diff htu subset.rfl)),
have B : μ (u \ s) ≠ ∞ := (lt_of_le_of_lt (measure_mono (diff_subset _ _)) ht_ne_top.lt_top).ne,
exact ennreal.le_of_add_le_add_right B A
end
/-- The measurable superset `to_measurable μ t` of `t` (which has the same measure as `t`)
satisfies, for any measurable set `s`, the equality `μ (to_measurable μ t ∩ s) = μ (u ∩ s)`.
Here, we require that the measure of `t` is finite. The conclusion holds without this assumption
when the measure is sigma_finite, see `measure_to_measurable_inter_of_sigma_finite`. -/
lemma measure_to_measurable_inter {s t : set α} (hs : measurable_set s) (ht : μ t ≠ ∞) :
μ (to_measurable μ t ∩ s) = μ (t ∩ s) :=
(measure_inter_eq_of_measure_eq hs (measure_to_measurable t).symm
(subset_to_measurable μ t) ht).symm
/-! ### The `ℝ≥0∞`-module of measures -/
instance [measurable_space α] : 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 {m : measurable_space α} :
(0 : measure α).to_outer_measure = 0 := rfl
@[simp, norm_cast] theorem coe_zero {m : measurable_space α} : ⇑(0 : measure α) = 0 := rfl
instance [is_empty α] {m : measurable_space α} : subsingleton (measure α) :=
⟨λ μ ν, by{ ext1 s hs, simp only [eq_empty_of_is_empty s, measure_empty] }⟩
lemma eq_zero_of_is_empty [is_empty α] {m : measurable_space α} (μ : measure α) : μ = 0 :=
subsingleton.elim μ 0
instance [measurable_space α] : inhabited (measure α) := ⟨0⟩
instance [measurable_space α] : 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 {m : measurable_space α} (μ₁ μ₂ : measure α) :
(μ₁ + μ₂).to_outer_measure = μ₁.to_outer_measure + μ₂.to_outer_measure := rfl
@[simp, norm_cast] theorem coe_add {m : measurable_space α} (μ₁ μ₂ : measure α) :
⇑(μ₁ + μ₂) = μ₁ + μ₂ := rfl
theorem add_apply {m : measurable_space α} (μ₁ μ₂ : measure α) (s : set α) :
(μ₁ + μ₂) s = μ₁ s + μ₂ s := rfl
section has_smul
variables [has_smul R ℝ≥0∞] [is_scalar_tower R ℝ≥0∞ ℝ≥0∞]
variables [has_smul R' ℝ≥0∞] [is_scalar_tower R' ℝ≥0∞ ℝ≥0∞]
instance [measurable_space α] : has_smul R (measure α) :=
⟨λ c μ,
{ to_outer_measure := c • μ.to_outer_measure,
m_Union := λ s hs hd, begin
rw ←smul_one_smul ℝ≥0∞ c (_ : outer_measure α),
dsimp,
simp_rw [measure_Union hd hs, ennreal.tsum_mul_left],
end,
trimmed := by rw [outer_measure.trim_smul, μ.trimmed] }⟩
@[simp] theorem smul_to_outer_measure {m : measurable_space α} (c : R) (μ : measure α) :
(c • μ).to_outer_measure = c • μ.to_outer_measure :=
rfl
@[simp, norm_cast] theorem coe_smul {m : measurable_space α} (c : R) (μ : measure α) :
⇑(c • μ) = c • μ :=
rfl
@[simp] theorem smul_apply {m : measurable_space α} (c : R) (μ : measure α) (s : set α) :
(c • μ) s = c • μ s :=
rfl
instance [smul_comm_class R R' ℝ≥0∞] [measurable_space α] :
smul_comm_class R R' (measure α) :=
⟨λ _ _ _, ext $ λ _ _, smul_comm _ _ _⟩
instance [has_smul R R'] [is_scalar_tower R R' ℝ≥0∞] [measurable_space α] :
is_scalar_tower R R' (measure α) :=
⟨λ _ _ _, ext $ λ _ _, smul_assoc _ _ _⟩
instance [has_smul Rᵐᵒᵖ ℝ≥0∞] [is_central_scalar R ℝ≥0∞] [measurable_space α] :
is_central_scalar R (measure α) :=
⟨λ _ _, ext $ λ _ _, op_smul_eq_smul _ _⟩
end has_smul
instance [monoid R] [mul_action R ℝ≥0∞] [is_scalar_tower R ℝ≥0∞ ℝ≥0∞] [measurable_space α] :
mul_action R (measure α) :=
injective.mul_action _ to_outer_measure_injective smul_to_outer_measure
instance add_comm_monoid [measurable_space α] : add_comm_monoid (measure α) :=
to_outer_measure_injective.add_comm_monoid to_outer_measure zero_to_outer_measure
add_to_outer_measure (λ _ _, smul_to_outer_measure _ _)
/-- Coercion to function as an additive monoid homomorphism. -/
def coe_add_hom {m : measurable_space α} : measure α →+ (set α → ℝ≥0∞) :=
⟨coe_fn, coe_zero, coe_add⟩
@[simp] lemma coe_finset_sum {m : measurable_space α} (I : finset ι) (μ : ι → measure α) :
⇑(∑ i in I, μ i) = ∑ i in I, μ i :=
(@coe_add_hom α m).map_sum _ _
theorem finset_sum_apply {m : measurable_space α} (I : finset ι) (μ : ι → measure α) (s : set α) :
(∑ i in I, μ i) s = ∑ i in I, μ i s :=
by rw [coe_finset_sum, finset.sum_apply]
instance [monoid R] [distrib_mul_action R ℝ≥0∞] [is_scalar_tower R ℝ≥0∞ ℝ≥0∞]
[measurable_space α] :
distrib_mul_action R (measure α) :=
injective.distrib_mul_action ⟨to_outer_measure, zero_to_outer_measure, add_to_outer_measure⟩
to_outer_measure_injective smul_to_outer_measure
instance [semiring R] [module R ℝ≥0∞] [is_scalar_tower R ℝ≥0∞ ℝ≥0∞] [measurable_space α] :
module R (measure α) :=
injective.module R ⟨to_outer_measure, zero_to_outer_measure, add_to_outer_measure⟩
to_outer_measure_injective smul_to_outer_measure
@[simp] theorem coe_nnreal_smul_apply {m : measurable_space α} (c : ℝ≥0) (μ : measure α)
(s : set α) :
(c • μ) s = c * μ s :=
rfl
lemma ae_smul_measure_iff {p : α → Prop} {c : ℝ≥0∞} (hc : c ≠ 0) :
(∀ᵐ x ∂(c • μ), p x) ↔ ∀ᵐ x ∂μ, p x :=
by simp [ae_iff, hc]
lemma measure_eq_left_of_subset_of_measure_add_eq {s t : set α}
(h : (μ + ν) t ≠ ∞) (h' : s ⊆ t) (h'' : (μ + ν) s = (μ + ν) t) :
μ s = μ t :=
begin
refine le_antisymm (measure_mono h') _,
have : μ t + ν t ≤ μ s + ν t := calc
μ t + ν t = μ s + ν s : h''.symm
... ≤ μ s + ν t : add_le_add le_rfl (measure_mono h'),
apply ennreal.le_of_add_le_add_right _ this,
simp only [not_or_distrib, ennreal.add_eq_top, pi.add_apply, ne.def, coe_add] at h,
exact h.2
end
lemma measure_eq_right_of_subset_of_measure_add_eq {s t : set α}
(h : (μ + ν) t ≠ ∞) (h' : s ⊆ t) (h'' : (μ + ν) s = (μ + ν) t) :
ν s = ν t :=
begin
rw add_comm at h'' h,
exact measure_eq_left_of_subset_of_measure_add_eq h h' h''
end
lemma measure_to_measurable_add_inter_left {s t : set α}
(hs : measurable_set s) (ht : (μ + ν) t ≠ ∞) :
μ (to_measurable (μ + ν) t ∩ s) = μ (t ∩ s) :=
begin
refine (measure_inter_eq_of_measure_eq hs _ (subset_to_measurable _ _) _).symm,
{ refine measure_eq_left_of_subset_of_measure_add_eq _ (subset_to_measurable _ _)
(measure_to_measurable t).symm,
rwa measure_to_measurable t, },
{ simp only [not_or_distrib, ennreal.add_eq_top, pi.add_apply, ne.def, coe_add] at ht,
exact ht.1 }
end
lemma measure_to_measurable_add_inter_right {s t : set α}
(hs : measurable_set s) (ht : (μ + ν) t ≠ ∞) :
ν (to_measurable (μ + ν) t ∩ s) = ν (t ∩ s) :=
begin
rw add_comm at ht ⊢,
exact measure_to_measurable_add_inter_left hs ht
end
/-! ### The complete lattice of measures -/
/-- Measures are partially ordered.
The definition of less equal here is equivalent to the definition without the
measurable set condition, and this is shown by `measure.le_iff'`. It is defined
this way since, to prove `μ ≤ ν`, we may simply `intros s hs` instead of rewriting followed
by `intros s hs`. -/
instance [measurable_space α] : partial_order (measure α) :=
{ le := λ m₁ m₂, ∀ s, measurable_set s → m₁ s ≤ m₂ s,
le_refl := λ m s hs, le_rfl,
le_trans := λ m₁ m₂ m₃ h₁ h₂ s hs, le_trans (h₁ s hs) (h₂ s hs),
le_antisymm := λ m₁ m₂ h₁ h₂, ext $
λ s hs, le_antisymm (h₁ s hs) (h₂ s hs) }
theorem le_iff : μ₁ ≤ μ₂ ↔ ∀ s, measurable_set s → μ₁ s ≤ μ₂ s := iff.rfl
theorem to_outer_measure_le : μ₁.to_outer_measure ≤ μ₂.to_outer_measure ↔ μ₁ ≤ μ₂ :=
by rw [← μ₂.trimmed, outer_measure.le_trim_iff]; refl
theorem le_iff' : μ₁ ≤ μ₂ ↔ ∀ s, μ₁ s ≤ μ₂ s :=
to_outer_measure_le.symm
theorem lt_iff : μ < ν ↔ μ ≤ ν ∧ ∃ s, measurable_set s ∧ μ s < ν s :=
lt_iff_le_not_le.trans $ and_congr iff.rfl $ by simp only [le_iff, not_forall, not_le, exists_prop]
theorem lt_iff' : μ < ν ↔ μ ≤ ν ∧ ∃ s, μ s < ν s :=
lt_iff_le_not_le.trans $ and_congr iff.rfl $ by simp only [le_iff', not_forall, not_le]
instance covariant_add_le [measurable_space α] : covariant_class (measure α) (measure α) (+) (≤) :=
⟨λ ν μ₁ μ₂ hμ s hs, add_le_add_left (hμ s hs) _⟩
protected lemma le_add_left (h : μ ≤ ν) : μ ≤ ν' + ν :=
λ s hs, le_add_left (h s hs)
protected lemma le_add_right (h : μ ≤ ν) : μ ≤ ν + ν' :=
λ s hs, le_add_right (h s hs)
section Inf
variables {m : set (measure α)}
lemma Inf_caratheodory (s : set α) (hs : measurable_set s) :
measurable_set[(Inf (to_outer_measure '' m)).caratheodory] s :=
begin
rw [outer_measure.Inf_eq_bounded_by_Inf_gen],
refine outer_measure.bounded_by_caratheodory (λ t, _),
simp only [outer_measure.Inf_gen, le_infi_iff, ball_image_iff, coe_to_outer_measure,
measure_eq_infi t],
intros μ hμ u htu hu,
have hm : ∀ {s t}, s ⊆ t → outer_measure.Inf_gen (to_outer_measure '' m) s ≤ μ t,
{ intros s t hst,
rw [outer_measure.Inf_gen_def],
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_inter_add_diff u hs],
refine add_le_add (hm $ inter_subset_inter_left _ htu) (hm $ diff_subset_diff_left htu)
end
instance [measurable_space α] : has_Inf (measure α) :=
⟨λ m, (Inf (to_outer_measure '' m)).to_measure $ Inf_caratheodory⟩
lemma Inf_apply (hs : measurable_set s) : Inf m s = Inf (to_outer_measure '' m) s :=
to_measure_apply _ _ hs
private lemma measure_Inf_le (h : μ ∈ m) : Inf m ≤ μ :=
have Inf (to_outer_measure '' m) ≤ μ.to_outer_measure := Inf_le (mem_image_of_mem _ h),
λ s hs, by rw [Inf_apply hs, ← to_outer_measure_apply]; exact this s
private lemma measure_le_Inf (h : ∀ μ' ∈ m, μ ≤ μ') : μ ≤ Inf m :=
have μ.to_outer_measure ≤ Inf (to_outer_measure '' m) :=
le_Inf $ ball_image_of_ball $ λ μ hμ, to_outer_measure_le.2 $ h _ hμ,
λ s hs, by rw [Inf_apply hs, ← to_outer_measure_apply]; exact this s
instance [measurable_space α] : complete_semilattice_Inf (measure α) :=
{ Inf_le := λ s a, measure_Inf_le,
le_Inf := λ s a, measure_le_Inf,
..(by apply_instance : partial_order (measure α)),
..(by apply_instance : has_Inf (measure α)), }
instance [measurable_space α] : complete_lattice (measure α) :=
{ bot := 0,
bot_le := λ a s hs, by exact bot_le,
/- Adding an explicit `top` makes `leanchecker` fail, see lean#364, disable for now
top := (⊤ : outer_measure α).to_measure (by rw [outer_measure.top_caratheodory]; exact le_top),
le_top := λ a s hs,
by cases s.eq_empty_or_nonempty with h h;
simp [h, to_measure_apply ⊤ _ hs, outer_measure.top_apply],
-/
.. complete_lattice_of_complete_semilattice_Inf (measure α) }
end Inf
@[simp] lemma _root_.measure_theory.outer_measure.to_measure_top [measurable_space α] :
(⊤ : outer_measure α).to_measure (by rw [outer_measure.top_caratheodory]; exact le_top)
= (⊤ : measure α) :=
top_unique $ λ s hs,
by cases s.eq_empty_or_nonempty with h h;
simp [h, to_measure_apply ⊤ _ hs, outer_measure.top_apply]
@[simp] lemma to_outer_measure_top [measurable_space α] :
(⊤ : measure α).to_outer_measure = (⊤ : outer_measure α) :=
by rw [←outer_measure.to_measure_top, to_measure_to_outer_measure, outer_measure.trim_top]
@[simp] lemma top_add : ⊤ + μ = ⊤ := top_unique $ measure.le_add_right le_rfl
@[simp] lemma add_top : μ + ⊤ = ⊤ := top_unique $ measure.le_add_left le_rfl
protected lemma zero_le {m0 : measurable_space α} (μ : measure α) : 0 ≤ μ := bot_le
lemma nonpos_iff_eq_zero' : μ ≤ 0 ↔ μ = 0 :=
μ.zero_le.le_iff_eq
@[simp] lemma measure_univ_eq_zero : μ univ = 0 ↔ μ = 0 :=
⟨λ h, bot_unique $ λ s hs, trans_rel_left (≤) (measure_mono (subset_univ s)) h, λ h, h.symm ▸ rfl⟩
lemma measure_univ_ne_zero : μ univ ≠ 0 ↔ μ ≠ 0 := measure_univ_eq_zero.not
@[simp] lemma measure_univ_pos : 0 < μ univ ↔ μ ≠ 0 := pos_iff_ne_zero.trans measure_univ_ne_zero
/-! ### Pushforward and pullback -/
/-- Lift a linear map between `outer_measure` spaces such that for each measure `μ` every measurable
set is caratheodory-measurable w.r.t. `f μ` to a linear map between `measure` spaces. -/
def lift_linear {m0 : measurable_space α} (f : outer_measure α →ₗ[ℝ≥0∞] outer_measure β)
(hf : ∀ μ : measure α, ‹_› ≤ (f μ.to_outer_measure).caratheodory) :
measure α →ₗ[ℝ≥0∞] measure β :=
{ to_fun := λ μ, (f μ.to_outer_measure).to_measure (hf μ),
map_add' := λ μ₁ μ₂, ext $ λ s hs, by simp [hs],
map_smul' := λ c μ, ext $ λ s hs, by simp [hs] }
@[simp] lemma lift_linear_apply {f : outer_measure α →ₗ[ℝ≥0∞] outer_measure β} (hf)
{s : set β} (hs : measurable_set s) : lift_linear f hf μ s = f μ.to_outer_measure s :=
to_measure_apply _ _ hs
lemma le_lift_linear_apply {f : outer_measure α →ₗ[ℝ≥0∞] outer_measure β} (hf) (s : set β) :
f μ.to_outer_measure s ≤ lift_linear f hf μ s :=
le_to_measure_apply _ _ s
/-- The pushforward of a measure as a linear map. It is defined to be `0` if `f` is not
a measurable function. -/
def mapₗ [measurable_space α] (f : α → β) : measure α →ₗ[ℝ≥0∞] measure β :=
if hf : measurable f then
lift_linear (outer_measure.map f) $ λ μ s hs t,
le_to_outer_measure_caratheodory μ _ (hf hs) (f ⁻¹' t)
else 0
lemma mapₗ_congr {f g : α → β} (hf : measurable f) (hg : measurable g) (h : f =ᵐ[μ] g) :
mapₗ f μ = mapₗ g μ :=
begin
ext1 s hs,
simpa only [mapₗ, hf, hg, hs, dif_pos, lift_linear_apply, outer_measure.map_apply,
coe_to_outer_measure] using measure_congr (h.preimage s),
end
/-- The pushforward of a measure. It is defined to be `0` if `f` is not an almost everywhere
measurable function. -/
@[irreducible] def map [measurable_space α] (f : α → β) (μ : measure α) : measure β :=
if hf : ae_measurable f μ then mapₗ (hf.mk f) μ else 0
include m0
lemma mapₗ_mk_apply_of_ae_measurable {f : α → β} (hf : ae_measurable f μ) :
mapₗ (hf.mk f) μ = map f μ :=
by simp [map, hf]
lemma mapₗ_apply_of_measurable {f : α → β} (hf : measurable f) (μ : measure α) :
mapₗ f μ = map f μ :=
begin
simp only [← mapₗ_mk_apply_of_ae_measurable hf.ae_measurable],
exact mapₗ_congr hf hf.ae_measurable.measurable_mk hf.ae_measurable.ae_eq_mk
end
@[simp] lemma map_add (μ ν : measure α) {f : α → β} (hf : measurable f) :
(μ + ν).map f = μ.map f + ν.map f :=
by simp [← mapₗ_apply_of_measurable hf]
@[simp] lemma map_zero (f : α → β) :
(0 : measure α).map f = 0 :=
begin
by_cases hf : ae_measurable f (0 : measure α);
simp [map, hf],
end
theorem map_of_not_ae_measurable {f : α → β} {μ : measure α} (hf : ¬ ae_measurable f μ) :
μ.map f = 0 :=
by simp [map, hf]
lemma map_congr {f g : α → β} (h : f =ᵐ[μ] g) : measure.map f μ = measure.map g μ :=
begin
by_cases hf : ae_measurable f μ,
{ have hg : ae_measurable g μ := hf.congr h,
simp only [← mapₗ_mk_apply_of_ae_measurable hf, ← mapₗ_mk_apply_of_ae_measurable hg],
exact mapₗ_congr hf.measurable_mk hg.measurable_mk
(hf.ae_eq_mk.symm.trans (h.trans hg.ae_eq_mk)) },
{ have hg : ¬ (ae_measurable g μ), by simpa [← ae_measurable_congr h] using hf,
simp [map_of_not_ae_measurable, hf, hg] }
end
@[simp] protected lemma map_smul (c : ℝ≥0∞) (μ : measure α) (f : α → β) :
(c • μ).map f = c • μ.map f :=
begin
rcases eq_or_ne c 0 with rfl|hc, { simp },
by_cases hf : ae_measurable f μ,
{ have hfc : ae_measurable f (c • μ) :=
⟨hf.mk f, hf.measurable_mk, (ae_smul_measure_iff hc).2 hf.ae_eq_mk⟩,
simp only [←mapₗ_mk_apply_of_ae_measurable hf, ←mapₗ_mk_apply_of_ae_measurable hfc,
linear_map.map_smulₛₗ, ring_hom.id_apply],
congr' 1,
apply mapₗ_congr hfc.measurable_mk hf.measurable_mk,
exact eventually_eq.trans ((ae_smul_measure_iff hc).1 hfc.ae_eq_mk.symm) hf.ae_eq_mk },
{ have hfc : ¬ (ae_measurable f (c • μ)),
{ assume hfc,
exact hf ⟨hfc.mk f, hfc.measurable_mk, (ae_smul_measure_iff hc).1 hfc.ae_eq_mk⟩ },
simp [map_of_not_ae_measurable hf, map_of_not_ae_measurable hfc] }
end
@[simp] protected lemma map_smul_nnreal (c : ℝ≥0) (μ : measure α) (f : α → β) :
(c • μ).map f = c • μ.map f :=
μ.map_smul (c : ℝ≥0∞) f
/-- We can evaluate the pushforward on measurable sets. For non-measurable sets, see
`measure_theory.measure.le_map_apply` and `measurable_equiv.map_apply`. -/
@[simp] theorem map_apply_of_ae_measurable
{f : α → β} (hf : ae_measurable f μ) {s : set β} (hs : measurable_set s) :
μ.map f s = μ (f ⁻¹' s) :=
by simpa only [mapₗ, hf.measurable_mk, hs, dif_pos, lift_linear_apply, outer_measure.map_apply,
coe_to_outer_measure, ← mapₗ_mk_apply_of_ae_measurable hf]
using measure_congr (hf.ae_eq_mk.symm.preimage s)
@[simp] theorem map_apply
{f : α → β} (hf : measurable f) {s : set β} (hs : measurable_set s) :
μ.map f s = μ (f ⁻¹' s) :=
map_apply_of_ae_measurable hf.ae_measurable hs
lemma map_to_outer_measure {f : α → β} (hf : ae_measurable f μ) :
(μ.map f).to_outer_measure = (outer_measure.map f μ.to_outer_measure).trim :=
begin
rw [← trimmed, outer_measure.trim_eq_trim_iff],
intros s hs,
rw [coe_to_outer_measure, map_apply_of_ae_measurable hf hs, outer_measure.map_apply,
coe_to_outer_measure]
end
@[simp] lemma map_id : map id μ = μ :=
ext $ λ s, map_apply measurable_id
@[simp] lemma map_id' : map (λ x, x) μ = μ := map_id
lemma map_map {g : β → γ} {f : α → β} (hg : measurable g) (hf : measurable f) :
(μ.map f).map g = μ.map (g ∘ f) :=
ext $ λ s hs, by simp [hf, hg, hs, hg hs, hg.comp hf, ← preimage_comp]
@[mono] lemma map_mono {f : α → β} (h : μ ≤ ν) (hf : measurable f) : μ.map f ≤ ν.map f :=
λ s hs, by simp [hf.ae_measurable, hs, h _ (hf hs)]
/-- Even if `s` is not measurable, we can bound `map f μ s` from below.
See also `measurable_equiv.map_apply`. -/
theorem le_map_apply {f : α → β} (hf : ae_measurable f μ) (s : set β) : μ (f ⁻¹' s) ≤ μ.map f s :=
calc μ (f ⁻¹' s) ≤ μ (f ⁻¹' (to_measurable (μ.map f) s)) :
measure_mono $ preimage_mono $ subset_to_measurable _ _
... = μ.map f (to_measurable (μ.map f) s) :
(map_apply_of_ae_measurable hf $ measurable_set_to_measurable _ _).symm
... = μ.map f s : measure_to_measurable _
/-- Even if `s` is not measurable, `map f μ s = 0` implies that `μ (f ⁻¹' s) = 0`. -/
lemma preimage_null_of_map_null {f : α → β} (hf : ae_measurable f μ) {s : set β}
(hs : μ.map f s = 0) : μ (f ⁻¹' s) = 0 :=
nonpos_iff_eq_zero.mp $ (le_map_apply hf s).trans_eq hs
lemma tendsto_ae_map {f : α → β} (hf : ae_measurable f μ) : tendsto f μ.ae (μ.map f).ae :=
λ s hs, preimage_null_of_map_null hf hs
omit m0
/-- Pullback of a `measure` as a linear map. If `f` sends each measurable set to a measurable
set, then for each measurable set `s` we have `comapₗ f μ s = μ (f '' s)`.
If the linearity is not needed, please use `comap` instead, which works for a larger class of
functions. -/
def comapₗ [measurable_space α] (f : α → β) : measure β →ₗ[ℝ≥0∞] measure α :=
if hf : injective f ∧ ∀ s, measurable_set s → measurable_set (f '' s) then
lift_linear (outer_measure.comap f) $ λ μ s hs t,
begin
simp only [coe_to_outer_measure, outer_measure.comap_apply, image_inter hf.1, image_diff hf.1],
apply le_to_outer_measure_caratheodory,
exact hf.2 s hs
end
else 0
lemma comapₗ_apply {β} [measurable_space α] {mβ : measurable_space β}
(f : α → β) (hfi : injective f)
(hf : ∀ s, measurable_set s → measurable_set (f '' s)) (μ : measure β) (hs : measurable_set s) :
comapₗ f μ s = μ (f '' s) :=
begin
rw [comapₗ, dif_pos, lift_linear_apply _ hs, outer_measure.comap_apply, coe_to_outer_measure],
exact ⟨hfi, hf⟩
end
/-- Pullback of a `measure`. If `f` sends each measurable set to a null-measurable set,
then for each measurable set `s` we have `comap f μ s = μ (f '' s)`. -/
def comap [measurable_space α] (f : α → β) (μ : measure β) : measure α :=
if hf : injective f ∧ ∀ s, measurable_set s → null_measurable_set (f '' s) μ then
(outer_measure.comap f μ.to_outer_measure).to_measure $ λ s hs t,
begin
simp only [coe_to_outer_measure, outer_measure.comap_apply, image_inter hf.1, image_diff hf.1],
exact (measure_inter_add_diff₀ _ (hf.2 s hs)).symm
end
else 0
lemma comap_apply₀ [measurable_space α] (f : α → β) (μ : measure β) (hfi : injective f)
(hf : ∀ s, measurable_set s → null_measurable_set (f '' s) μ)
(hs : null_measurable_set s (comap f μ)) :
comap f μ s = μ (f '' s) :=
begin
rw [comap, dif_pos (and.intro hfi hf)] at hs ⊢,
rw [to_measure_apply₀ _ _ hs, outer_measure.comap_apply, coe_to_outer_measure]
end
lemma le_comap_apply {β} [measurable_space α] {mβ : measurable_space β} (f : α → β) (μ : measure β)
(hfi : injective f) (hf : ∀ s, measurable_set s → null_measurable_set (f '' s) μ) (s : set α) :
μ (f '' s) ≤ comap f μ s :=
by { rw [comap, dif_pos (and.intro hfi hf)], exact le_to_measure_apply _ _ _, }
lemma comap_apply {β} [measurable_space α] {mβ : measurable_space β} (f : α → β) (hfi : injective f)
(hf : ∀ s, measurable_set s → measurable_set (f '' s)) (μ : measure β) (hs : measurable_set s) :
comap f μ s = μ (f '' s) :=
comap_apply₀ f μ hfi (λ s hs, (hf s hs).null_measurable_set) hs.null_measurable_set
lemma comapₗ_eq_comap {β} [measurable_space α] {mβ : measurable_space β} (f : α → β)
(hfi : injective f) (hf : ∀ s, measurable_set s → measurable_set (f '' s))
(μ : measure β) (hs : measurable_set s) :
comapₗ f μ s = comap f μ s :=
(comapₗ_apply f hfi hf μ hs).trans (comap_apply f hfi hf μ hs).symm
lemma measure_image_eq_zero_of_comap_eq_zero {β} [measurable_space α] {mβ : measurable_space β}
(f : α → β) (μ : measure β) (hfi : injective f)
(hf : ∀ s, measurable_set s → null_measurable_set (f '' s) μ) {s : set α} (hs : comap f μ s = 0) :
μ (f '' s) = 0 :=
le_antisymm ((le_comap_apply f μ hfi hf s).trans hs.le) (zero_le _)
lemma ae_eq_image_of_ae_eq_comap {β} [measurable_space α] {mβ : measurable_space β}
(f : α → β) (μ : measure β) (hfi : injective f)
(hf : ∀ s, measurable_set s → null_measurable_set (f '' s) μ) {s t : set α}
(hst : s =ᵐ[comap f μ] t) :
f '' s =ᵐ[μ] f '' t :=
begin
rw [eventually_eq, ae_iff] at hst ⊢,
have h_eq_α : {a : α | ¬s a = t a} = s \ t ∪ t \ s,
{ ext1 x, simp only [eq_iff_iff, mem_set_of_eq, mem_union, mem_diff], tauto, },
have h_eq_β : {a : β | ¬(f '' s) a = (f '' t) a} = f '' s \ f '' t ∪ f '' t \ f '' s,
{ ext1 x, simp only [eq_iff_iff, mem_set_of_eq, mem_union, mem_diff], tauto, },
rw [← set.image_diff hfi, ← set.image_diff hfi, ← set.image_union] at h_eq_β,
rw h_eq_β,
rw h_eq_α at hst,
exact measure_image_eq_zero_of_comap_eq_zero f μ hfi hf hst,
end
lemma null_measurable_set.image {β} [measurable_space α] {mβ : measurable_space β}
(f : α → β) (μ : measure β) (hfi : injective f)
(hf : ∀ s, measurable_set s → null_measurable_set (f '' s) μ) {s : set α}
(hs : null_measurable_set s (μ.comap f)) :
null_measurable_set (f '' s) μ :=
begin
refine ⟨to_measurable μ (f '' (to_measurable (μ.comap f) s)),
measurable_set_to_measurable _ _, _⟩,
refine eventually_eq.trans _ (null_measurable_set.to_measurable_ae_eq _).symm,
swap, { exact hf _ (measurable_set_to_measurable _ _), },
have h : to_measurable (comap f μ) s =ᵐ[comap f μ] s,
from @null_measurable_set.to_measurable_ae_eq _ _ (μ.comap f : measure α) s hs,
exact ae_eq_image_of_ae_eq_comap f μ hfi hf h.symm,
end
lemma comap_preimage {β} [measurable_space α] {mβ : measurable_space β} (f : α → β) (μ : measure β)
{s : set β} (hf : injective f) (hf' : measurable f)
(h : ∀ t, measurable_set t → null_measurable_set (f '' t) μ) (hs : measurable_set s) :
μ.comap f (f ⁻¹' s) = μ (s ∩ range f) :=
by rw [comap_apply₀ _ _ hf h (hf' hs).null_measurable_set, image_preimage_eq_inter_range]
section subtype
/-! ### Subtype of a measure space -/
section comap_any_measure
lemma measurable_set.null_measurable_set_subtype_coe
{t : set s} (hs : null_measurable_set s μ) (ht : measurable_set t) :
null_measurable_set ((coe : s → α) '' t) μ :=
begin
rw [subtype.measurable_space, comap_eq_generate_from] at ht,
refine generate_from_induction
(λ t : set s, null_measurable_set (coe '' t) μ)
{t : set s | ∃ (s' : set α), measurable_set s' ∧ coe ⁻¹' s' = t} _ _ _ _ ht,
{ rintros t' ⟨s', hs', rfl⟩,
rw [subtype.image_preimage_coe],
exact hs'.null_measurable_set.inter hs, },
{ simp only [image_empty, null_measurable_set_empty], },
{ intro t',
simp only [←range_diff_image subtype.coe_injective, subtype.range_coe_subtype, set_of_mem_eq],
exact hs.diff, },
{ intro f,
rw image_Union,
exact null_measurable_set.Union, },
end
lemma null_measurable_set.subtype_coe {t : set s} (hs : null_measurable_set s μ)
(ht : null_measurable_set t (μ.comap subtype.val)) :
null_measurable_set ((coe : s → α) '' t) μ :=
null_measurable_set.image coe μ subtype.coe_injective
(λ t, measurable_set.null_measurable_set_subtype_coe hs) ht
lemma measure_subtype_coe_le_comap (hs : null_measurable_set s μ) (t : set s) :
μ ((coe : s → α) '' t) ≤ μ.comap subtype.val t :=
le_comap_apply _ _ subtype.coe_injective (λ t, measurable_set.null_measurable_set_subtype_coe hs) _
lemma measure_subtype_coe_eq_zero_of_comap_eq_zero (hs : null_measurable_set s μ)
{t : set s} (ht : μ.comap subtype.val t = 0) :
μ ((coe : s → α) '' t) = 0 :=
eq_bot_iff.mpr $ (measure_subtype_coe_le_comap hs t).trans ht.le
end comap_any_measure
section measure_space
variables [measure_space α] {p : α → Prop}
instance subtype.measure_space : measure_space (subtype p) :=
{ volume := measure.comap subtype.val volume,
..subtype.measurable_space }
lemma subtype.volume_def : (volume : measure s) = volume.comap subtype.val := rfl
lemma subtype.volume_univ (hs : null_measurable_set s) :
volume (univ : set s) = volume s :=
begin
rw [subtype.volume_def, comap_apply₀ _ _ _ _ measurable_set.univ.null_measurable_set],
{ congr, simp only [subtype.val_eq_coe, image_univ, subtype.range_coe_subtype, set_of_mem_eq], },
{ exact subtype.coe_injective, },
{ exact λ t, measurable_set.null_measurable_set_subtype_coe hs, },
end
lemma volume_subtype_coe_le_volume (hs : null_measurable_set s) (t : set s) :
volume ((coe : s → α) '' t) ≤ volume t :=
measure_subtype_coe_le_comap hs t
lemma volume_subtype_coe_eq_zero_of_volume_eq_zero (hs : null_measurable_set s)
{t : set s} (ht : volume t = 0) :
volume ((coe : s → α) '' t) = 0 :=
measure_subtype_coe_eq_zero_of_comap_eq_zero hs ht
end measure_space
end subtype
/-! ### Restricting a measure -/
/-- Restrict a measure `μ` to a set `s` as an `ℝ≥0∞`-linear map. -/
def restrictₗ {m0 : measurable_space α} (s : set α) : measure α →ₗ[ℝ≥0∞] measure α :=
lift_linear (outer_measure.restrict s) $ λ μ s' hs' t,
begin
suffices : μ (s ∩ t) = μ (s ∩ t ∩ s') + μ (s ∩ t \ s'),
{ simpa [← set.inter_assoc, set.inter_comm _ s, ← inter_diff_assoc] },
exact le_to_outer_measure_caratheodory _ _ hs' _,
end
/-- Restrict a measure `μ` to a set `s`. -/
def restrict {m0 : measurable_space α} (μ : measure α) (s : set α) : measure α := restrictₗ s μ
@[simp] lemma restrictₗ_apply {m0 : measurable_space α} (s : set α) (μ : measure α) :
restrictₗ s μ = μ.restrict s :=
rfl
/-- This lemma shows that `restrict` and `to_outer_measure` commute. Note that the LHS has a
restrict on measures and the RHS has a restrict on outer measures. -/
lemma restrict_to_outer_measure_eq_to_outer_measure_restrict (h : measurable_set s) :
(μ.restrict s).to_outer_measure = outer_measure.restrict s μ.to_outer_measure :=
by simp_rw [restrict, restrictₗ, lift_linear, linear_map.coe_mk, to_measure_to_outer_measure,
outer_measure.restrict_trim h, μ.trimmed]
lemma restrict_apply₀ (ht : null_measurable_set t (μ.restrict s)) :
μ.restrict s t = μ (t ∩ s) :=
(to_measure_apply₀ _ _ ht).trans $ by simp only [coe_to_outer_measure, outer_measure.restrict_apply]
/-- If `t` is a measurable set, then the measure of `t` with respect to the restriction of
the measure to `s` equals the outer measure of `t ∩ s`. An alternate version requiring that `s`
be measurable instead of `t` exists as `measure.restrict_apply'`. -/
@[simp] lemma restrict_apply (ht : measurable_set t) : μ.restrict s t = μ (t ∩ s) :=
restrict_apply₀ ht.null_measurable_set
/-- Restriction of a measure to a subset is monotone both in set and in measure. -/
lemma restrict_mono' {m0 : measurable_space α} ⦃s s' : set α⦄ ⦃μ ν : measure α⦄
(hs : s ≤ᵐ[μ] s') (hμν : μ ≤ ν) :
μ.restrict s ≤ ν.restrict s' :=
assume t ht,
calc μ.restrict s t = μ (t ∩ s) : restrict_apply ht
... ≤ μ (t ∩ s') : measure_mono_ae $ hs.mono $ λ x hx ⟨hxt, hxs⟩, ⟨hxt, hx hxs⟩
... ≤ ν (t ∩ s') : le_iff'.1 hμν (t ∩ s')
... = ν.restrict s' t : (restrict_apply ht).symm
/-- Restriction of a measure to a subset is monotone both in set and in measure. -/
@[mono] lemma restrict_mono {m0 : measurable_space α} ⦃s s' : set α⦄ (hs : s ⊆ s') ⦃μ ν : measure α⦄
(hμν : μ ≤ ν) :
μ.restrict s ≤ ν.restrict s' :=
restrict_mono' (ae_of_all _ hs) hμν
lemma restrict_mono_ae (h : s ≤ᵐ[μ] t) : μ.restrict s ≤ μ.restrict t :=
restrict_mono' h (le_refl μ)
lemma restrict_congr_set (h : s =ᵐ[μ] t) : μ.restrict s = μ.restrict t :=
le_antisymm (restrict_mono_ae h.le) (restrict_mono_ae h.symm.le)
/-- If `s` is a measurable set, then the outer measure of `t` with respect to the restriction of
the measure to `s` equals the outer measure of `t ∩ s`. This is an alternate version of
`measure.restrict_apply`, requiring that `s` is measurable instead of `t`. -/
@[simp] lemma restrict_apply' (hs : measurable_set s) : μ.restrict s t = μ (t ∩ s) :=
by rw [← coe_to_outer_measure, measure.restrict_to_outer_measure_eq_to_outer_measure_restrict hs,
outer_measure.restrict_apply s t _, coe_to_outer_measure]
lemma restrict_apply₀' (hs : null_measurable_set s μ) : μ.restrict s t = μ (t ∩ s) :=
by rw [← restrict_congr_set hs.to_measurable_ae_eq,
restrict_apply' (measurable_set_to_measurable _ _),
measure_congr ((ae_eq_refl t).inter hs.to_measurable_ae_eq)]
lemma restrict_le_self : μ.restrict s ≤ μ :=
λ t ht,
calc μ.restrict s t = μ (t ∩ s) : restrict_apply ht
... ≤ μ t : measure_mono $ inter_subset_left t s
variable (μ)
lemma restrict_eq_self (h : s ⊆ t) : μ.restrict t s = μ s :=
(le_iff'.1 restrict_le_self s).antisymm $
calc μ s ≤ μ (to_measurable (μ.restrict t) s ∩ t) :
measure_mono (subset_inter (subset_to_measurable _ _) h)
... = μ.restrict t s :
by rw [← restrict_apply (measurable_set_to_measurable _ _), measure_to_measurable]
@[simp] lemma restrict_apply_self (s : set α):
(μ.restrict s) s = μ s :=
restrict_eq_self μ subset.rfl
variable {μ}
lemma restrict_apply_univ (s : set α) : μ.restrict s univ = μ s :=
by rw [restrict_apply measurable_set.univ, set.univ_inter]
lemma le_restrict_apply (s t : set α) :
μ (t ∩ s) ≤ μ.restrict s t :=
calc μ (t ∩ s) = μ.restrict s (t ∩ s) : (restrict_eq_self μ (inter_subset_right _ _)).symm
... ≤ μ.restrict s t : measure_mono (inter_subset_left _ _)
lemma restrict_apply_superset (h : s ⊆ t) : μ.restrict s t = μ s :=
((measure_mono (subset_univ _)).trans_eq $ restrict_apply_univ _).antisymm
((restrict_apply_self μ s).symm.trans_le $ measure_mono h)
@[simp] lemma restrict_add {m0 : measurable_space α} (μ ν : measure α) (s : set α) :
(μ + ν).restrict s = μ.restrict s + ν.restrict s :=
(restrictₗ s).map_add μ ν
@[simp] lemma restrict_zero {m0 : measurable_space α} (s : set α) :
(0 : measure α).restrict s = 0 :=
(restrictₗ s).map_zero
@[simp] lemma restrict_smul {m0 : measurable_space α} (c : ℝ≥0∞) (μ : measure α) (s : set α) :
(c • μ).restrict s = c • μ.restrict s :=
(restrictₗ s).map_smul c μ
lemma restrict_restrict₀ (hs : null_measurable_set s (μ.restrict t)) :
(μ.restrict t).restrict s = μ.restrict (s ∩ t) :=
ext $ λ u hu, by simp only [set.inter_assoc, restrict_apply hu,
restrict_apply₀ (hu.null_measurable_set.inter hs)]
@[simp] lemma restrict_restrict (hs : measurable_set s) :
(μ.restrict t).restrict s = μ.restrict (s ∩ t) :=
restrict_restrict₀ hs.null_measurable_set
lemma restrict_restrict_of_subset (h : s ⊆ t) :
(μ.restrict t).restrict s = μ.restrict s :=
begin
ext1 u hu,
rw [restrict_apply hu, restrict_apply hu, restrict_eq_self],
exact (inter_subset_right _ _).trans h
end
lemma restrict_restrict₀' (ht : null_measurable_set t μ) :
(μ.restrict t).restrict s = μ.restrict (s ∩ t) :=
ext $ λ u hu, by simp only [restrict_apply hu, restrict_apply₀' ht, inter_assoc]
lemma restrict_restrict' (ht : measurable_set t) :
(μ.restrict t).restrict s = μ.restrict (s ∩ t) :=
restrict_restrict₀' ht.null_measurable_set
lemma restrict_comm (hs : measurable_set s) :
(μ.restrict t).restrict s = (μ.restrict s).restrict t :=
by rw [restrict_restrict hs, restrict_restrict' hs, inter_comm]
lemma restrict_apply_eq_zero (ht : measurable_set t) : μ.restrict s t = 0 ↔ μ (t ∩ s) = 0 :=
by rw [restrict_apply ht]
lemma measure_inter_eq_zero_of_restrict (h : μ.restrict s t = 0) : μ (t ∩ s) = 0 :=
nonpos_iff_eq_zero.1 (h ▸ le_restrict_apply _ _)
lemma restrict_apply_eq_zero' (hs : measurable_set s) : μ.restrict s t = 0 ↔ μ (t ∩ s) = 0 :=
by rw [restrict_apply' hs]
@[simp] lemma restrict_eq_zero : μ.restrict s = 0 ↔ μ s = 0 :=
by rw [← measure_univ_eq_zero, restrict_apply_univ]
lemma restrict_zero_set {s : set α} (h : μ s = 0) :
μ.restrict s = 0 :=
restrict_eq_zero.2 h
@[simp] lemma restrict_empty : μ.restrict ∅ = 0 := restrict_zero_set measure_empty
@[simp] lemma restrict_univ : μ.restrict univ = μ := ext $ λ s hs, by simp [hs]
lemma restrict_inter_add_diff₀ (s : set α) (ht : null_measurable_set t μ) :
μ.restrict (s ∩ t) + μ.restrict (s \ t) = μ.restrict s :=
begin
ext1 u hu,
simp only [add_apply, restrict_apply hu, ← inter_assoc, diff_eq],
exact measure_inter_add_diff₀ (u ∩ s) ht
end
lemma restrict_inter_add_diff (s : set α) (ht : measurable_set t) :
μ.restrict (s ∩ t) + μ.restrict (s \ t) = μ.restrict s :=
restrict_inter_add_diff₀ s ht.null_measurable_set
lemma restrict_union_add_inter₀ (s : set α) (ht : null_measurable_set t μ) :
μ.restrict (s ∪ t) + μ.restrict (s ∩ t) = μ.restrict s + μ.restrict t :=
by rw [← restrict_inter_add_diff₀ (s ∪ t) ht, union_inter_cancel_right, union_diff_right,
← restrict_inter_add_diff₀ s ht, add_comm, ← add_assoc, add_right_comm]
lemma restrict_union_add_inter (s : set α) (ht : measurable_set t) :
μ.restrict (s ∪ t) + μ.restrict (s ∩ t) = μ.restrict s + μ.restrict t :=
restrict_union_add_inter₀ s ht.null_measurable_set
lemma restrict_union_add_inter' (hs : measurable_set s) (t : set α) :
μ.restrict (s ∪ t) + μ.restrict (s ∩ t) = μ.restrict s + μ.restrict t :=
by simpa only [union_comm, inter_comm, add_comm] using restrict_union_add_inter t hs
lemma restrict_union₀ (h : ae_disjoint μ s t) (ht : null_measurable_set t μ) :
μ.restrict (s ∪ t) = μ.restrict s + μ.restrict t :=
by simp [← restrict_union_add_inter₀ s ht, restrict_zero_set h]
lemma restrict_union (h : disjoint s t) (ht : measurable_set t) :
μ.restrict (s ∪ t) = μ.restrict s + μ.restrict t :=
restrict_union₀ h.ae_disjoint ht.null_measurable_set
lemma restrict_union' (h : disjoint s t) (hs : measurable_set s) :
μ.restrict (s ∪ t) = μ.restrict s + μ.restrict t :=
by rw [union_comm, restrict_union h.symm hs, add_comm]
@[simp] lemma restrict_add_restrict_compl (hs : measurable_set s) :
μ.restrict s + μ.restrict sᶜ = μ :=
by rw [← restrict_union (@disjoint_compl_right (set α) _ _) hs.compl,
union_compl_self, restrict_univ]
@[simp] lemma restrict_compl_add_restrict (hs : measurable_set s) :
μ.restrict sᶜ + μ.restrict s = μ :=
by rw [add_comm, restrict_add_restrict_compl hs]
lemma restrict_union_le (s s' : set α) : μ.restrict (s ∪ s') ≤ μ.restrict s + μ.restrict s' :=
begin
intros t ht,
suffices : μ (t ∩ s ∪ t ∩ s') ≤ μ (t ∩ s) + μ (t ∩ s'),
by simpa [ht, inter_union_distrib_left],
apply measure_union_le
end
lemma restrict_Union_apply_ae [countable ι] {s : ι → set α}
(hd : pairwise (ae_disjoint μ on s))
(hm : ∀ i, null_measurable_set (s i) μ) {t : set α} (ht : measurable_set t) :
μ.restrict (⋃ i, s i) t = ∑' i, μ.restrict (s i) t :=
begin
simp only [restrict_apply, ht, inter_Union],
exact measure_Union₀ (hd.mono $ λ i j h, h.mono (inter_subset_right _ _) (inter_subset_right _ _))
(λ i, (ht.null_measurable_set.inter (hm i)))
end
lemma restrict_Union_apply [countable ι] {s : ι → set α} (hd : pairwise (disjoint on s))
(hm : ∀ i, measurable_set (s i)) {t : set α} (ht : measurable_set t) :
μ.restrict (⋃ i, s i) t = ∑' i, μ.restrict (s i) t :=
restrict_Union_apply_ae hd.ae_disjoint (λ i, (hm i).null_measurable_set) ht
lemma restrict_Union_apply_eq_supr [countable ι] {s : ι → set α}
(hd : directed (⊆) s) {t : set α} (ht : measurable_set t) :
μ.restrict (⋃ i, s i) t = ⨆ i, μ.restrict (s i) t :=
begin
simp only [restrict_apply ht, inter_Union],
rw [measure_Union_eq_supr],
exacts [hd.mono_comp _ (λ s₁ s₂, inter_subset_inter_right _)]
end
/-- The restriction of the pushforward measure is the pushforward of the restriction. For a version
assuming only `ae_measurable`, see `restrict_map_of_ae_measurable`. -/
lemma restrict_map {f : α → β} (hf : measurable f) {s : set β} (hs : measurable_set s) :
(μ.map f).restrict s = (μ.restrict $ f ⁻¹' s).map f :=
ext $ λ t ht, by simp [*, hf ht]
lemma restrict_to_measurable (h : μ s ≠ ∞) : μ.restrict (to_measurable μ s) = μ.restrict s :=
ext $ λ t ht, by rw [restrict_apply ht, restrict_apply ht, inter_comm,
measure_to_measurable_inter ht h, inter_comm]
lemma restrict_eq_self_of_ae_mem {m0 : measurable_space α} ⦃s : set α⦄ ⦃μ : measure α⦄
(hs : ∀ᵐ x ∂μ, x ∈ s) :
μ.restrict s = μ :=
calc μ.restrict s = μ.restrict univ : restrict_congr_set (eventually_eq_univ.mpr hs)
... = μ : restrict_univ
lemma restrict_congr_meas (hs : measurable_set s) :
μ.restrict s = ν.restrict s ↔ ∀ t ⊆ s, measurable_set t → μ t = ν t :=
⟨λ H t hts ht,
by rw [← inter_eq_self_of_subset_left hts, ← restrict_apply ht, H, restrict_apply ht],
λ H, ext $ λ t ht,
by rw [restrict_apply ht, restrict_apply ht, H _ (inter_subset_right _ _) (ht.inter hs)]⟩
lemma restrict_congr_mono (hs : s ⊆ t) (h : μ.restrict t = ν.restrict t) :
μ.restrict s = ν.restrict s :=
by rw [← restrict_restrict_of_subset hs, h, restrict_restrict_of_subset hs]
/-- If two measures agree on all measurable subsets of `s` and `t`, then they agree on all
measurable subsets of `s ∪ t`. -/
lemma restrict_union_congr :
μ.restrict (s ∪ t) = ν.restrict (s ∪ t) ↔
μ.restrict s = ν.restrict s ∧ μ.restrict t = ν.restrict t :=
begin
refine ⟨λ h, ⟨restrict_congr_mono (subset_union_left _ _) h,
restrict_congr_mono (subset_union_right _ _) h⟩, _⟩,
rintro ⟨hs, ht⟩,
ext1 u hu,
simp only [restrict_apply hu, inter_union_distrib_left],
rcases exists_measurable_superset₂ μ ν (u ∩ s) with ⟨US, hsub, hm, hμ, hν⟩,
calc μ (u ∩ s ∪ u ∩ t) = μ (US ∪ u ∩ t) :
measure_union_congr_of_subset hsub hμ.le subset.rfl le_rfl
... = μ US + μ (u ∩ t \ US) : (measure_add_diff hm _).symm
... = restrict μ s u + restrict μ t (u \ US) :
by simp only [restrict_apply, hu, hu.diff hm, hμ, ← inter_comm t, inter_diff_assoc]
... = restrict ν s u + restrict ν t (u \ US) : by rw [hs, ht]
... = ν US + ν (u ∩ t \ US) :
by simp only [restrict_apply, hu, hu.diff hm, hν, ← inter_comm t, inter_diff_assoc]
... = ν (US ∪ u ∩ t) : measure_add_diff hm _
... = ν (u ∩ s ∪ u ∩ t) :
eq.symm $ measure_union_congr_of_subset hsub hν.le subset.rfl le_rfl
end
lemma restrict_finset_bUnion_congr {s : finset ι} {t : ι → set α} :
μ.restrict (⋃ i ∈ s, t i) = ν.restrict (⋃ i ∈ s, t i) ↔
∀ i ∈ s, μ.restrict (t i) = ν.restrict (t i) :=
begin
induction s using finset.induction_on with i s hi hs, { simp },
simp only [forall_eq_or_imp, Union_Union_eq_or_left, finset.mem_insert],
rw [restrict_union_congr, ← hs]
end
lemma restrict_Union_congr [countable ι] {s : ι → set α} :
μ.restrict (⋃ i, s i) = ν.restrict (⋃ i, s i) ↔
∀ i, μ.restrict (s i) = ν.restrict (s i) :=
begin
refine ⟨λ h i, restrict_congr_mono (subset_Union _ _) h, λ h, _⟩,
ext1 t ht,
have D : directed (⊆) (λ t : finset ι, ⋃ i ∈ t, s i) :=
directed_of_sup (λ t₁ t₂ ht, bUnion_subset_bUnion_left ht),
rw [Union_eq_Union_finset],
simp only [restrict_Union_apply_eq_supr D ht,
restrict_finset_bUnion_congr.2 (λ i hi, h i)],
end
lemma restrict_bUnion_congr {s : set ι} {t : ι → set α} (hc : s.countable) :
μ.restrict (⋃ i ∈ s, t i) = ν.restrict (⋃ i ∈ s, t i) ↔
∀ i ∈ s, μ.restrict (t i) = ν.restrict (t i) :=
begin
haveI := hc.to_encodable,
simp only [bUnion_eq_Union, set_coe.forall', restrict_Union_congr]
end
lemma restrict_sUnion_congr {S : set (set α)} (hc : S.countable) :
μ.restrict (⋃₀ S) = ν.restrict (⋃₀ S) ↔ ∀ s ∈ S, μ.restrict s = ν.restrict s :=
by rw [sUnion_eq_bUnion, restrict_bUnion_congr hc]
/-- This lemma shows that `Inf` and `restrict` commute for measures. -/
lemma restrict_Inf_eq_Inf_restrict {m0 : measurable_space α} {m : set (measure α)}
(hm : m.nonempty) (ht : measurable_set t) :
(Inf m).restrict t = Inf ((λ μ : measure α, μ.restrict t) '' m) :=
begin
ext1 s hs,
simp_rw [Inf_apply hs, restrict_apply hs, Inf_apply (measurable_set.inter hs ht), set.image_image,
restrict_to_outer_measure_eq_to_outer_measure_restrict ht, ← set.image_image _ to_outer_measure,
← outer_measure.restrict_Inf_eq_Inf_restrict _ (hm.image _),
outer_measure.restrict_apply]
end
lemma exists_mem_of_measure_ne_zero_of_ae (hs : μ s ≠ 0)
{p : α → Prop} (hp : ∀ᵐ x ∂μ.restrict s, p x) :
∃ x, x ∈ s ∧ p x :=
begin
rw [← μ.restrict_apply_self, ← frequently_ae_mem_iff] at hs,
exact (hs.and_eventually hp).exists,
end
/-! ### Extensionality results -/
/-- Two measures are equal if they have equal restrictions on a spanning collection of sets
(formulated using `Union`). -/
lemma ext_iff_of_Union_eq_univ [countable ι] {s : ι → set α} (hs : (⋃ i, s i) = univ) :
μ = ν ↔ ∀ i, μ.restrict (s i) = ν.restrict (s i) :=
by rw [← restrict_Union_congr, hs, restrict_univ, restrict_univ]
alias ext_iff_of_Union_eq_univ ↔ _ ext_of_Union_eq_univ
/-- Two measures are equal if they have equal restrictions on a spanning collection of sets
(formulated using `bUnion`). -/
lemma ext_iff_of_bUnion_eq_univ {S : set ι} {s : ι → set α} (hc : S.countable)
(hs : (⋃ i ∈ S, s i) = univ) :
μ = ν ↔ ∀ i ∈ S, μ.restrict (s i) = ν.restrict (s i) :=
by rw [← restrict_bUnion_congr hc, hs, restrict_univ, restrict_univ]
alias ext_iff_of_bUnion_eq_univ ↔ _ ext_of_bUnion_eq_univ
/-- Two measures are equal if they have equal restrictions on a spanning collection of sets
(formulated using `sUnion`). -/
lemma ext_iff_of_sUnion_eq_univ {S : set (set α)} (hc : S.countable) (hs : (⋃₀ S) = univ) :
μ = ν ↔ ∀ s ∈ S, μ.restrict s = ν.restrict s :=
ext_iff_of_bUnion_eq_univ hc $ by rwa ← sUnion_eq_bUnion
alias ext_iff_of_sUnion_eq_univ ↔ _ ext_of_sUnion_eq_univ
lemma ext_of_generate_from_of_cover {S T : set (set α)}
(h_gen : ‹_› = generate_from S) (hc : T.countable)
(h_inter : is_pi_system S) (hU : ⋃₀ T = univ) (htop : ∀ t ∈ T, μ t ≠ ∞)
(ST_eq : ∀ (t ∈ T) (s ∈ S), μ (s ∩ t) = ν (s ∩ t)) (T_eq : ∀ t ∈ T, μ t = ν t) :
μ = ν :=
begin
refine ext_of_sUnion_eq_univ hc hU (λ t ht, _),
ext1 u hu,
simp only [restrict_apply hu],
refine induction_on_inter h_gen h_inter _ (ST_eq t ht) _ _ hu,
{ simp only [set.empty_inter, measure_empty] },
{ intros v hv hvt,
have := T_eq t ht,
rw [set.inter_comm] at hvt ⊢,
rwa [← measure_inter_add_diff t hv, ← measure_inter_add_diff t hv, ← hvt,
ennreal.add_right_inj] at this,
exact ne_top_of_le_ne_top (htop t ht) (measure_mono $ set.inter_subset_left _ _) },
{ intros f hfd hfm h_eq,
simp only [← restrict_apply (hfm _), ← restrict_apply (measurable_set.Union hfm)] at h_eq ⊢,
simp only [measure_Union hfd hfm, h_eq] }
end
/-- Two measures are equal if they are equal on the π-system generating the σ-algebra,
and they are both finite on a increasing spanning sequence of sets in the π-system.
This lemma is formulated using `sUnion`. -/
lemma ext_of_generate_from_of_cover_subset {S T : set (set α)}
(h_gen : ‹_› = generate_from S) (h_inter : is_pi_system S)
(h_sub : T ⊆ S) (hc : T.countable) (hU : ⋃₀ T = univ) (htop : ∀ s ∈ T, μ s ≠ ∞)
(h_eq : ∀ s ∈ S, μ s = ν s) :
μ = ν :=
begin
refine ext_of_generate_from_of_cover h_gen hc h_inter hU htop _ (λ t ht, h_eq t (h_sub ht)),
intros t ht s hs, cases (s ∩ t).eq_empty_or_nonempty with H H,
{ simp only [H, measure_empty] },
{ exact h_eq _ (h_inter _ hs _ (h_sub ht) H) }
end
/-- Two measures are equal if they are equal on the π-system generating the σ-algebra,
and they are both finite on a increasing spanning sequence of sets in the π-system.
This lemma is formulated using `Union`.
`finite_spanning_sets_in.ext` is a reformulation of this lemma. -/
lemma ext_of_generate_from_of_Union (C : set (set α)) (B : ℕ → set α)
(hA : ‹_› = generate_from C) (hC : is_pi_system C) (h1B : (⋃ i, B i) = univ)
(h2B : ∀ i, B i ∈ C) (hμB : ∀ i, μ (B i) ≠ ∞) (h_eq : ∀ s ∈ C, μ s = ν s) : μ = ν :=
begin
refine ext_of_generate_from_of_cover_subset hA hC _ (countable_range B) h1B _ h_eq,
{ rintro _ ⟨i, rfl⟩, apply h2B },
{ rintro _ ⟨i, rfl⟩, apply hμB }
end
section dirac
variable [measurable_space α]
/-- The dirac measure. -/
def dirac (a : α) : measure α :=
(outer_measure.dirac a).to_measure (by simp)
instance : measure_space punit := ⟨dirac punit.star⟩
lemma le_dirac_apply {a} : s.indicator 1 a ≤ dirac a s :=
outer_measure.dirac_apply a s ▸ le_to_measure_apply _ _ _
@[simp] lemma dirac_apply' (a : α) (hs : measurable_set s) :
dirac a s = s.indicator 1 a :=
to_measure_apply _ _ hs
@[simp] lemma dirac_apply_of_mem {a : α} (h : a ∈ s) :
dirac a s = 1 :=
begin
have : ∀ t : set α, a ∈ t → t.indicator (1 : α → ℝ≥0∞) a = 1,
from λ t ht, indicator_of_mem ht 1,
refine le_antisymm (this univ trivial ▸ _) (this s h ▸ le_dirac_apply),
rw [← dirac_apply' a measurable_set.univ],
exact measure_mono (subset_univ s)
end
@[simp] lemma dirac_apply [measurable_singleton_class α] (a : α) (s : set α) :
dirac a s = s.indicator 1 a :=
begin
by_cases h : a ∈ s, by rw [dirac_apply_of_mem h, indicator_of_mem h, pi.one_apply],
rw [indicator_of_not_mem h, ← nonpos_iff_eq_zero],
calc dirac a s ≤ dirac a {a}ᶜ : measure_mono (subset_compl_comm.1 $ singleton_subset_iff.2 h)
... = 0 : by simp [dirac_apply' _ (measurable_set_singleton _).compl]
end
lemma map_dirac {f : α → β} (hf : measurable f) (a : α) :
(dirac a).map f = dirac (f a) :=
ext $ λ s hs, by simp [hs, map_apply hf hs, hf hs, indicator_apply]
@[simp] lemma restrict_singleton (μ : measure α) (a : α) : μ.restrict {a} = μ {a} • dirac a :=
begin
ext1 s hs,
by_cases ha : a ∈ s,
{ have : s ∩ {a} = {a}, by simpa,
simp * },
{ have : s ∩ {a} = ∅, from inter_singleton_eq_empty.2 ha,
simp * }
end
end dirac
section sum
include m0
/-- Sum of an indexed family of measures. -/
def sum (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 _)
lemma le_sum_apply (f : ι → measure α) (s : set α) : (∑' i, f i s) ≤ sum f s :=
le_to_measure_apply _ _ _
@[simp] lemma sum_apply (f : ι → measure α) {s : set α} (hs : measurable_set s) :
sum f s = ∑' i, f i s :=
to_measure_apply _ _ hs
lemma le_sum (μ : ι → measure α) (i : ι) : μ i ≤ sum μ :=
λ s hs, by simp only [sum_apply μ hs, ennreal.le_tsum i]
@[simp] lemma sum_apply_eq_zero [countable ι] {μ : ι → measure α} {s : set α} :
sum μ s = 0 ↔ ∀ i, μ i s = 0 :=
begin
refine ⟨λ h i, nonpos_iff_eq_zero.1 $ h ▸ le_iff'.1 (le_sum μ i) _, λ h, nonpos_iff_eq_zero.1 _⟩,
rcases exists_measurable_superset_forall_eq μ s with ⟨t, hst, htm, ht⟩,
calc sum μ s ≤ sum μ t : measure_mono hst
... = 0 : by simp *
end
lemma sum_apply_eq_zero' {μ : ι → measure α} {s : set α} (hs : measurable_set s) :
sum μ s = 0 ↔ ∀ i, μ i s = 0 :=
by simp [hs]
lemma sum_comm {ι' : Type*} (μ : ι → ι' → measure α) :
sum (λ n, sum (μ n)) = sum (λ m, sum (λ n, μ n m)) :=
by { ext1 s hs, simp_rw [sum_apply _ hs], rw ennreal.tsum_comm, }
lemma ae_sum_iff [countable ι] {μ : ι → measure α} {p : α → Prop} :
(∀ᵐ x ∂(sum μ), p x) ↔ ∀ i, ∀ᵐ x ∂(μ i), p x :=
sum_apply_eq_zero
lemma ae_sum_iff' {μ : ι → measure α} {p : α → Prop} (h : measurable_set {x | p x}) :
(∀ᵐ x ∂(sum μ), p x) ↔ ∀ i, ∀ᵐ x ∂(μ i), p x :=
sum_apply_eq_zero' h.compl
@[simp] lemma sum_fintype [fintype ι] (μ : ι → measure α) : sum μ = ∑ i, μ i :=
by { ext1 s hs, simp only [sum_apply, finset_sum_apply, hs, tsum_fintype] }
@[simp] lemma sum_coe_finset (s : finset ι) (μ : ι → measure α) :
sum (λ i : s, μ i) = ∑ i in s, μ i :=
by rw [sum_fintype, finset.sum_coe_sort s μ]
@[simp] lemma ae_sum_eq [countable ι] (μ : ι → measure α) : (sum μ).ae = ⨆ i, (μ i).ae :=
filter.ext $ λ s, ae_sum_iff.trans mem_supr.symm
@[simp] lemma sum_bool (f : bool → measure α) : sum f = f tt + f ff :=
by rw [sum_fintype, fintype.sum_bool]
@[simp] lemma sum_cond (μ ν : measure α) : sum (λ b, cond b μ ν) = μ + ν := sum_bool _
@[simp] lemma restrict_sum (μ : ι → measure α) {s : set α} (hs : measurable_set s) :
(sum μ).restrict s = sum (λ i, (μ i).restrict s) :=
ext $ λ t ht, by simp only [sum_apply, restrict_apply, ht, ht.inter hs]
@[simp] lemma sum_of_empty [is_empty ι] (μ : ι → measure α) : sum μ = 0 :=
by rw [← measure_univ_eq_zero, sum_apply _ measurable_set.univ, tsum_empty]
lemma sum_add_sum_compl (s : set ι) (μ : ι → measure α) :
sum (λ i : s, μ i) + sum (λ i : sᶜ, μ i) = sum μ :=
begin
ext1 t ht,
simp only [add_apply, sum_apply _ ht],
exact @tsum_add_tsum_compl ℝ≥0∞ ι _ _ _ (λ i, μ i t) _ s ennreal.summable ennreal.summable
end
lemma sum_congr {μ ν : ℕ → measure α} (h : ∀ n, μ n = ν n) : sum μ = sum ν :=
congr_arg sum (funext h)
lemma sum_add_sum (μ ν : ℕ → measure α) : sum μ + sum ν = sum (λ n, μ n + ν n) :=
begin
ext1 s hs,
simp only [add_apply, sum_apply _ hs, pi.add_apply, coe_add,
tsum_add ennreal.summable ennreal.summable],
end
/-- If `f` is a map with countable codomain, then `μ.map f` is a sum of Dirac measures. -/
lemma map_eq_sum [countable β] [measurable_singleton_class β] (μ : measure α) (f : α → β)
(hf : measurable f) :
μ.map f = sum (λ b : β, μ (f ⁻¹' {b}) • dirac b) :=
begin
ext1 s hs,
have : ∀ y ∈ s, measurable_set (f ⁻¹' {y}), from λ y _, hf (measurable_set_singleton _),
simp [← tsum_measure_preimage_singleton (to_countable s) this, *,
tsum_subtype s (λ b, μ (f ⁻¹' {b})), ← indicator_mul_right s (λ b, μ (f ⁻¹' {b}))]
end
/-- A measure on a countable type is a sum of Dirac measures. -/
@[simp] lemma sum_smul_dirac [countable α] [measurable_singleton_class α] (μ : measure α) :
sum (λ a, μ {a} • dirac a) = μ :=
by simpa using (map_eq_sum μ id measurable_id).symm
/-- Given that `α` is a countable, measurable space with all singleton sets measurable,
write the measure of a set `s` as the sum of the measure of `{x}` for all `x ∈ s`. -/
lemma tsum_indicator_apply_singleton [countable α] [measurable_singleton_class α]
(μ : measure α) (s : set α) (hs : measurable_set s) :
∑' (x : α), s.indicator (λ x, μ {x}) x = μ s :=
calc ∑' (x : α), s.indicator (λ x, μ {x}) x = measure.sum (λ a, μ {a} • measure.dirac a) s :
by simp only [measure.sum_apply _ hs, measure.smul_apply, smul_eq_mul, measure.dirac_apply,
set.indicator_apply, mul_ite, pi.one_apply, mul_one, mul_zero]
... = μ s : by rw μ.sum_smul_dirac
omit m0
end sum
lemma restrict_Union_ae [countable ι] {s : ι → set α} (hd : pairwise (ae_disjoint μ on s))
(hm : ∀ i, null_measurable_set (s i) μ) :
μ.restrict (⋃ i, s i) = sum (λ i, μ.restrict (s i)) :=
ext $ λ t ht, by simp only [sum_apply _ ht, restrict_Union_apply_ae hd hm ht]
lemma restrict_Union [countable ι] {s : ι → set α} (hd : pairwise (disjoint on s))
(hm : ∀ i, measurable_set (s i)) :
μ.restrict (⋃ i, s i) = sum (λ i, μ.restrict (s i)) :=
restrict_Union_ae hd.ae_disjoint (λ i, (hm i).null_measurable_set)
lemma restrict_Union_le [countable ι] {s : ι → set α} :
μ.restrict (⋃ i, s i) ≤ sum (λ i, μ.restrict (s i)) :=
begin
intros t ht,
suffices : μ (⋃ i, t ∩ s i) ≤ ∑' i, μ (t ∩ s i), by simpa [ht, inter_Union],
apply measure_Union_le
end
section count
variable [measurable_space α]
/-- Counting measure on any measurable space. -/
def count : measure α := sum dirac
lemma le_count_apply : (∑' i : s, 1 : ℝ≥0∞) ≤ count s :=
calc (∑' i : s, 1 : ℝ≥0∞) = ∑' i, indicator s 1 i : tsum_subtype s 1
... ≤ ∑' i, dirac i s : ennreal.tsum_le_tsum $ λ x, le_dirac_apply
... ≤ count s : le_sum_apply _ _
lemma count_apply (hs : measurable_set s) : count s = ∑' i : s, 1 :=
by simp only [count, sum_apply, hs, dirac_apply', ← tsum_subtype s 1, pi.one_apply]
@[simp] lemma count_empty : count (∅ : set α) = 0 :=
by rw [count_apply measurable_set.empty, tsum_empty]
@[simp] lemma count_apply_finset' {s : finset α} (s_mble : measurable_set (s : set α)) :
count (↑s : set α) = s.card :=
calc count (↑s : set α) = ∑' i : (↑s : set α), 1 : count_apply s_mble
... = ∑ i in s, 1 : s.tsum_subtype 1
... = s.card : by simp
@[simp] lemma count_apply_finset [measurable_singleton_class α] (s : finset α) :
count (↑s : set α) = s.card :=
count_apply_finset' s.measurable_set
lemma count_apply_finite' {s : set α} (s_fin : s.finite) (s_mble : measurable_set s) :
count s = s_fin.to_finset.card :=
by simp [← @count_apply_finset' _ _ s_fin.to_finset
(by simpa only [finite.coe_to_finset] using s_mble)]
lemma count_apply_finite [measurable_singleton_class α] (s : set α) (hs : s.finite) :
count s = hs.to_finset.card :=
by rw [← count_apply_finset, finite.coe_to_finset]
/-- `count` measure evaluates to infinity at infinite sets. -/
lemma count_apply_infinite (hs : s.infinite) : count s = ∞ :=
begin
refine top_unique (le_of_tendsto' ennreal.tendsto_nat_nhds_top $ λ n, _),
rcases hs.exists_subset_card_eq n with ⟨t, ht, rfl⟩,
calc (t.card : ℝ≥0∞) = ∑ i in t, 1 : by simp
... = ∑' i : (t : set α), 1 : (t.tsum_subtype 1).symm
... ≤ count (t : set α) : le_count_apply
... ≤ count s : measure_mono ht
end
@[simp] lemma count_apply_eq_top' (s_mble : measurable_set s) : count s = ∞ ↔ s.infinite :=
begin
by_cases hs : s.finite,
{ simp [set.infinite, hs, count_apply_finite' hs s_mble], },
{ change s.infinite at hs,
simp [hs, count_apply_infinite], }
end
@[simp] lemma count_apply_eq_top [measurable_singleton_class α] : count s = ∞ ↔ s.infinite :=
begin
by_cases hs : s.finite,
{ exact count_apply_eq_top' hs.measurable_set, },
{ change s.infinite at hs,
simp [hs, count_apply_infinite], },
end
@[simp] lemma count_apply_lt_top' (s_mble : measurable_set s) : count s < ∞ ↔ s.finite :=
calc count s < ∞ ↔ count s ≠ ∞ : lt_top_iff_ne_top
... ↔ ¬s.infinite : not_congr (count_apply_eq_top' s_mble)
... ↔ s.finite : not_not
@[simp] lemma count_apply_lt_top [measurable_singleton_class α] : count s < ∞ ↔ s.finite :=
calc count s < ∞ ↔ count s ≠ ∞ : lt_top_iff_ne_top
... ↔ ¬s.infinite : not_congr count_apply_eq_top
... ↔ s.finite : not_not
lemma empty_of_count_eq_zero' (s_mble : measurable_set s) (hsc : count s = 0) : s = ∅ :=
begin
have hs : s.finite,
{ rw [← count_apply_lt_top' s_mble, hsc],
exact with_top.zero_lt_top },
simpa [count_apply_finite' hs s_mble] using hsc,
end
lemma empty_of_count_eq_zero [measurable_singleton_class α] (hsc : count s = 0) : s = ∅ :=
begin
have hs : s.finite,
{ rw [← count_apply_lt_top, hsc],
exact with_top.zero_lt_top },
simpa [count_apply_finite _ hs] using hsc,
end
@[simp] lemma count_eq_zero_iff' (s_mble : measurable_set s) : count s = 0 ↔ s = ∅ :=
⟨empty_of_count_eq_zero' s_mble, λ h, h.symm ▸ count_empty⟩
@[simp] lemma count_eq_zero_iff [measurable_singleton_class α] : count s = 0 ↔ s = ∅ :=
⟨empty_of_count_eq_zero, λ h, h.symm ▸ count_empty⟩
lemma count_ne_zero' (hs' : s.nonempty) (s_mble : measurable_set s) : count s ≠ 0 :=
begin
rw [ne.def, count_eq_zero_iff' s_mble],
exact hs'.ne_empty,
end
lemma count_ne_zero [measurable_singleton_class α] (hs' : s.nonempty) : count s ≠ 0 :=
begin
rw [ne.def, count_eq_zero_iff],
exact hs'.ne_empty,
end
@[simp] lemma count_singleton' {a : α} (ha : measurable_set ({a} : set α)) :
count ({a} : set α) = 1 :=
begin
rw [count_apply_finite' (set.finite_singleton a) ha, set.finite.to_finset],
simp,
end
@[simp] lemma count_singleton [measurable_singleton_class α] (a : α) : count ({a} : set α) = 1 :=
count_singleton' (measurable_set_singleton a)
lemma count_injective_image' {f : β → α} (hf : function.injective f) {s : set β}
(s_mble : measurable_set s) (fs_mble : measurable_set (f '' s)):
count (f '' s) = count s :=
begin
by_cases hs : s.finite,
{ lift s to finset β using hs,
rw [← finset.coe_image, count_apply_finset' _, count_apply_finset' s_mble,
s.card_image_of_injective hf],
simpa only [finset.coe_image] using fs_mble, },
rw count_apply_infinite hs,
rw ← (finite_image_iff $ hf.inj_on _) at hs,
rw count_apply_infinite hs,
end
lemma count_injective_image [measurable_singleton_class α] [measurable_singleton_class β]
{f : β → α} (hf : function.injective f) (s : set β) :
count (f '' s) = count s :=
begin
by_cases hs : s.finite,
{ exact count_injective_image' hf hs.measurable_set (finite.image f hs).measurable_set, },
rw count_apply_infinite hs,
rw ← (finite_image_iff $ hf.inj_on _) at hs,
rw count_apply_infinite hs,
end
end count
/-! ### Absolute continuity -/
/-- We say that `μ` is absolutely continuous with respect to `ν`, or that `μ` is dominated by `ν`,
if `ν(A) = 0` implies that `μ(A) = 0`. -/
def absolutely_continuous {m0 : measurable_space α} (μ ν : measure α) : Prop :=
∀ ⦃s : set α⦄, ν s = 0 → μ s = 0
localized "infix (name := measure.absolutely_continuous)
` ≪ `:50 := measure_theory.measure.absolutely_continuous" in measure_theory
lemma absolutely_continuous_of_le (h : μ ≤ ν) : μ ≪ ν :=
λ s hs, nonpos_iff_eq_zero.1 $ hs ▸ le_iff'.1 h s
alias absolutely_continuous_of_le ← _root_.has_le.le.absolutely_continuous
lemma absolutely_continuous_of_eq (h : μ = ν) : μ ≪ ν :=
h.le.absolutely_continuous
alias absolutely_continuous_of_eq ← _root_.eq.absolutely_continuous
namespace absolutely_continuous
lemma mk (h : ∀ ⦃s : set α⦄, measurable_set s → ν s = 0 → μ s = 0) : μ ≪ ν :=
begin
intros s hs,
rcases exists_measurable_superset_of_null hs with ⟨t, h1t, h2t, h3t⟩,
exact measure_mono_null h1t (h h2t h3t),
end
@[refl] protected lemma refl {m0 : measurable_space α} (μ : measure α) : μ ≪ μ :=
rfl.absolutely_continuous
protected lemma rfl : μ ≪ μ := λ s hs, hs
instance [measurable_space α] : is_refl (measure α) (≪) := ⟨λ μ, absolutely_continuous.rfl⟩
@[trans] protected lemma trans (h1 : μ₁ ≪ μ₂) (h2 : μ₂ ≪ μ₃) : μ₁ ≪ μ₃ :=
λ s hs, h1 $ h2 hs
@[mono] protected lemma map (h : μ ≪ ν) {f : α → β} (hf : measurable f) : μ.map f ≪ ν.map f :=
absolutely_continuous.mk $ λ s hs, by simpa [hf, hs] using @h _
protected lemma smul [monoid R] [distrib_mul_action R ℝ≥0∞] [is_scalar_tower R ℝ≥0∞ ℝ≥0∞]
(h : μ ≪ ν) (c : R) : c • μ ≪ ν :=
λ s hνs, by simp only [h hνs, smul_eq_mul, smul_apply, smul_zero]
end absolutely_continuous
lemma absolutely_continuous_of_le_smul {μ' : measure α} {c : ℝ≥0∞} (hμ'_le : μ' ≤ c • μ) :
μ' ≪ μ :=
(measure.absolutely_continuous_of_le hμ'_le).trans (measure.absolutely_continuous.rfl.smul c)
lemma ae_le_iff_absolutely_continuous : μ.ae ≤ ν.ae ↔ μ ≪ ν :=
⟨λ h s, by { rw [measure_zero_iff_ae_nmem, measure_zero_iff_ae_nmem], exact λ hs, h hs },
λ h s hs, h hs⟩
alias ae_le_iff_absolutely_continuous ↔
_root_.has_le.le.absolutely_continuous_of_ae absolutely_continuous.ae_le
alias absolutely_continuous.ae_le ← ae_mono'
lemma absolutely_continuous.ae_eq (h : μ ≪ ν) {f g : α → δ} (h' : f =ᵐ[ν] g) : f =ᵐ[μ] g :=
h.ae_le h'
/-! ### Quasi measure preserving maps (a.k.a. non-singular maps) -/
/-- A map `f : α → β` is said to be *quasi measure preserving* (a.k.a. non-singular) w.r.t. measures
`μa` and `μb` if it is measurable and `μb s = 0` implies `μa (f ⁻¹' s) = 0`. -/
@[protect_proj]
structure quasi_measure_preserving {m0 : measurable_space α} (f : α → β)
(μa : measure α . volume_tac) (μb : measure β . volume_tac) : Prop :=
(measurable : measurable f)
(absolutely_continuous : μa.map f ≪ μb)
namespace quasi_measure_preserving
protected lemma id {m0 : measurable_space α} (μ : measure α) : quasi_measure_preserving id μ μ :=
⟨measurable_id, map_id.absolutely_continuous⟩
variables {μa μa' : measure α} {μb μb' : measure β} {μc : measure γ} {f : α → β}
protected lemma _root_.measurable.quasi_measure_preserving {m0 : measurable_space α}
(hf : measurable f) (μ : measure α) : quasi_measure_preserving f μ (μ.map f) :=
⟨hf, absolutely_continuous.rfl⟩
lemma mono_left (h : quasi_measure_preserving f μa μb)
(ha : μa' ≪ μa) : quasi_measure_preserving f μa' μb :=
⟨h.1, (ha.map h.1).trans h.2⟩
lemma mono_right (h : quasi_measure_preserving f μa μb)
(ha : μb ≪ μb') : quasi_measure_preserving f μa μb' :=
⟨h.1, h.2.trans ha⟩
@[mono] lemma mono (ha : μa' ≪ μa) (hb : μb ≪ μb') (h : quasi_measure_preserving f μa μb) :
quasi_measure_preserving f μa' μb' :=
(h.mono_left ha).mono_right hb
protected lemma comp {g : β → γ} {f : α → β} (hg : quasi_measure_preserving g μb μc)
(hf : quasi_measure_preserving f μa μb) :
quasi_measure_preserving (g ∘ f) μa μc :=
⟨hg.measurable.comp hf.measurable, by { rw ← map_map hg.1 hf.1, exact (hf.2.map hg.1).trans hg.2 }⟩
protected lemma iterate {f : α → α} (hf : quasi_measure_preserving f μa μa) :
∀ n, quasi_measure_preserving (f^[n]) μa μa
| 0 := quasi_measure_preserving.id μa
| (n + 1) := (iterate n).comp hf
protected lemma ae_measurable (hf : quasi_measure_preserving f μa μb) : ae_measurable f μa :=
hf.1.ae_measurable
lemma ae_map_le (h : quasi_measure_preserving f μa μb) : (μa.map f).ae ≤ μb.ae :=
h.2.ae_le
lemma tendsto_ae (h : quasi_measure_preserving f μa μb) : tendsto f μa.ae μb.ae :=
(tendsto_ae_map h.ae_measurable).mono_right h.ae_map_le
lemma ae (h : quasi_measure_preserving f μa μb) {p : β → Prop} (hg : ∀ᵐ x ∂μb, p x) :
∀ᵐ x ∂μa, p (f x) :=
h.tendsto_ae hg
lemma ae_eq (h : quasi_measure_preserving f μa μb) {g₁ g₂ : β → δ} (hg : g₁ =ᵐ[μb] g₂) :
g₁ ∘ f =ᵐ[μa] g₂ ∘ f :=
h.ae hg
lemma preimage_null (h : quasi_measure_preserving f μa μb) {s : set β} (hs : μb s = 0) :
μa (f ⁻¹' s) = 0 :=
preimage_null_of_map_null h.ae_measurable (h.2 hs)
lemma preimage_mono_ae {s t : set β} (hf : quasi_measure_preserving f μa μb) (h : s ≤ᵐ[μb] t) :
f⁻¹' s ≤ᵐ[μa] f⁻¹' t :=
eventually_map.mp $ eventually.filter_mono (tendsto_ae_map hf.ae_measurable)
(eventually.filter_mono hf.ae_map_le h)
lemma preimage_ae_eq {s t : set β} (hf : quasi_measure_preserving f μa μb) (h : s =ᵐ[μb] t) :
f⁻¹' s =ᵐ[μa] f⁻¹' t :=
eventually_le.antisymm (hf.preimage_mono_ae h.le) (hf.preimage_mono_ae h.symm.le)
lemma preimage_iterate_ae_eq {s : set α} {f : α → α} (hf : quasi_measure_preserving f μ μ) (k : ℕ)
(hs : f⁻¹' s =ᵐ[μ] s) : (f^[k])⁻¹' s =ᵐ[μ] s :=
begin
induction k with k ih, { simp, },
rw [iterate_succ, preimage_comp],
exact eventually_eq.trans (hf.preimage_ae_eq ih) hs,
end
lemma image_zpow_ae_eq {s : set α} {e : α ≃ α} (he : quasi_measure_preserving e μ μ)
(he' : quasi_measure_preserving e.symm μ μ) (k : ℤ) (hs : e '' s =ᵐ[μ] s) : ⇑(e^k) '' s =ᵐ[μ] s :=
begin
rw equiv.image_eq_preimage,
obtain ⟨k, rfl | rfl⟩ := k.eq_coe_or_neg,
{ replace hs : ⇑(e⁻¹)⁻¹' s =ᵐ[μ] s, by rwa equiv.image_eq_preimage at hs,
replace he' : (⇑(e⁻¹)^[k])⁻¹' s =ᵐ[μ] s := he'.preimage_iterate_ae_eq k hs,
rwa [equiv.perm.iterate_eq_pow e⁻¹ k, inv_pow e k] at he', },
{ rw [zpow_neg, zpow_coe_nat],
replace hs : e⁻¹' s =ᵐ[μ] s, { convert he.preimage_ae_eq hs.symm, rw equiv.preimage_image, },
replace he : (⇑e^[k])⁻¹' s =ᵐ[μ] s := he.preimage_iterate_ae_eq k hs,
rwa [equiv.perm.iterate_eq_pow e k] at he, },
end
lemma limsup_preimage_iterate_ae_eq {f : α → α} (hf : quasi_measure_preserving f μ μ)
(hs : f⁻¹' s =ᵐ[μ] s) :
-- Need `@` below because of diamond; see gh issue #16932
@limsup (set α) ℕ _ (λ n, (preimage f)^[n] s) at_top =ᵐ[μ] s :=
begin
have : ∀ n, (preimage f)^[n] s =ᵐ[μ] s,
{ intros n,
induction n with n ih, { simp, },
simpa only [iterate_succ', comp_app] using ae_eq_trans (hf.ae_eq ih) hs, },
exact (limsup_ae_eq_of_forall_ae_eq (λ n, (preimage f)^[n] s) this).trans (ae_eq_refl _),
end
lemma liminf_preimage_iterate_ae_eq {f : α → α} (hf : quasi_measure_preserving f μ μ)
(hs : f⁻¹' s =ᵐ[μ] s) :
-- Need `@` below because of diamond; see gh issue #16932
@liminf (set α) ℕ _ (λ n, (preimage f)^[n] s) at_top =ᵐ[μ] s :=
begin
-- Need `@` below because of diamond; see gh issue #16932
rw [← ae_eq_set_compl_compl, @filter.liminf_compl (set α)],
rw [← ae_eq_set_compl_compl, ← preimage_compl] at hs,
convert hf.limsup_preimage_iterate_ae_eq hs,
ext1 n,
simp only [← set.preimage_iterate_eq, comp_app, preimage_compl],
end
/-- By replacing a measurable set that is almost invariant with the `limsup` of its preimages, we
obtain a measurable set that is almost equal and strictly invariant.
(The `liminf` would work just as well.) -/
lemma exists_preimage_eq_of_preimage_ae {f : α → α} (h : quasi_measure_preserving f μ μ)
(hs : measurable_set s) (hs' : f⁻¹' s =ᵐ[μ] s) :
∃ (t : set α), measurable_set t ∧ t =ᵐ[μ] s ∧ f⁻¹' t = t :=
⟨limsup (λ n, (preimage f)^[n] s) at_top,
measurable_set.measurable_set_limsup $ λ n, @preimage_iterate_eq α f n ▸ h.measurable.iterate n hs,
h.limsup_preimage_iterate_ae_eq hs',
(complete_lattice_hom.set_preimage f).apply_limsup_iterate s⟩
open_locale pointwise
@[to_additive]
lemma smul_ae_eq_of_ae_eq
{G α : Type*} [group G] [mul_action G α] [measurable_space α] {s t : set α} {μ : measure α}
(g : G) (h_qmp : quasi_measure_preserving ((•) g⁻¹ : α → α) μ μ) (h_ae_eq : s =ᵐ[μ] t) :
(g • s : set α) =ᵐ[μ] (g • t : set α) :=
by simpa only [← preimage_smul_inv] using h_qmp.ae_eq h_ae_eq
end quasi_measure_preserving
section pointwise
open_locale pointwise
@[to_additive]
lemma pairwise_ae_disjoint_of_ae_disjoint_forall_ne_one
{G α : Type*} [group G] [mul_action G α] [measurable_space α] {μ : measure α} {s : set α}
(h_ae_disjoint : ∀ g ≠ (1 : G), ae_disjoint μ (g • s) s)
(h_qmp : ∀ (g : G), quasi_measure_preserving ((•) g : α → α) μ μ) :
pairwise (ae_disjoint μ on (λ (g : G), g • s)) :=
begin
intros g₁ g₂ hg,
let g := g₂⁻¹ * g₁,
replace hg : g ≠ 1, { rw [ne.def, inv_mul_eq_one], exact hg.symm, },
have : ((•) g₂⁻¹)⁻¹' (g • s ∩ s) = (g₁ • s) ∩ (g₂ • s),
{ rw [preimage_eq_iff_eq_image (mul_action.bijective g₂⁻¹), image_smul, smul_set_inter,
smul_smul, smul_smul, inv_mul_self, one_smul], },
change μ ((g₁ • s) ∩ (g₂ • s)) = 0,
exact this ▸ (h_qmp g₂⁻¹).preimage_null (h_ae_disjoint g hg),
end
end pointwise
/-! ### The `cofinite` filter -/
/-- The filter of sets `s` such that `sᶜ` has finite measure. -/
def cofinite {m0 : measurable_space α} (μ : measure α) : filter α :=
{ sets := {s | μ sᶜ < ∞},
univ_sets := by simp,
inter_sets := λ s t hs ht, by { simp only [compl_inter, mem_set_of_eq],
calc μ (sᶜ ∪ tᶜ) ≤ μ sᶜ + μ tᶜ : measure_union_le _ _
... < ∞ : ennreal.add_lt_top.2 ⟨hs, ht⟩ },
sets_of_superset := λ s t hs hst, lt_of_le_of_lt (measure_mono $ compl_subset_compl.2 hst) hs }
lemma mem_cofinite : s ∈ μ.cofinite ↔ μ sᶜ < ∞ := iff.rfl
lemma compl_mem_cofinite : sᶜ ∈ μ.cofinite ↔ μ s < ∞ :=
by rw [mem_cofinite, compl_compl]
lemma eventually_cofinite {p : α → Prop} : (∀ᶠ x in μ.cofinite, p x) ↔ μ {x | ¬p x} < ∞ := iff.rfl
end measure
open measure
open_locale measure_theory
/-- The preimage of a null measurable set under a (quasi) measure preserving map is a null
measurable set. -/
lemma null_measurable_set.preimage {ν : measure β} {f : α → β} {t : set β}
(ht : null_measurable_set t ν) (hf : quasi_measure_preserving f μ ν) :
null_measurable_set (f ⁻¹' t) μ :=
⟨f ⁻¹' (to_measurable ν t), hf.measurable (measurable_set_to_measurable _ _),
hf.ae_eq ht.to_measurable_ae_eq.symm⟩
lemma null_measurable_set.mono_ac (h : null_measurable_set s μ) (hle : ν ≪ μ) :
null_measurable_set s ν :=
h.preimage $ (quasi_measure_preserving.id μ).mono_left hle
lemma null_measurable_set.mono (h : null_measurable_set s μ) (hle : ν ≤ μ) :
null_measurable_set s ν :=
h.mono_ac hle.absolutely_continuous
lemma ae_disjoint.preimage {ν : measure β} {f : α → β} {s t : set β}
(ht : ae_disjoint ν s t) (hf : quasi_measure_preserving f μ ν) :
ae_disjoint μ (f ⁻¹' s) (f ⁻¹' t) :=
hf.preimage_null ht
@[simp] lemma ae_eq_bot : μ.ae = ⊥ ↔ μ = 0 :=
by rw [← empty_mem_iff_bot, mem_ae_iff, compl_empty, measure_univ_eq_zero]
@[simp] lemma ae_ne_bot : μ.ae.ne_bot ↔ μ ≠ 0 :=
ne_bot_iff.trans (not_congr ae_eq_bot)
@[simp] lemma ae_zero {m0 : measurable_space α} : (0 : measure α).ae = ⊥ := ae_eq_bot.2 rfl
@[mono] lemma ae_mono (h : μ ≤ ν) : μ.ae ≤ ν.ae := h.absolutely_continuous.ae_le
lemma mem_ae_map_iff {f : α → β} (hf : ae_measurable f μ) {s : set β} (hs : measurable_set s) :
s ∈ (μ.map f).ae ↔ (f ⁻¹' s) ∈ μ.ae :=
by simp only [mem_ae_iff, map_apply_of_ae_measurable hf hs.compl, preimage_compl]
lemma mem_ae_of_mem_ae_map
{f : α → β} (hf : ae_measurable f μ) {s : set β} (hs : s ∈ (μ.map f).ae) :
f ⁻¹' s ∈ μ.ae :=
(tendsto_ae_map hf).eventually hs
lemma ae_map_iff
{f : α → β} (hf : ae_measurable f μ) {p : β → Prop} (hp : measurable_set {x | p x}) :
(∀ᵐ y ∂ (μ.map f), p y) ↔ ∀ᵐ x ∂ μ, p (f x) :=
mem_ae_map_iff hf hp
lemma ae_of_ae_map {f : α → β} (hf : ae_measurable f μ) {p : β → Prop} (h : ∀ᵐ y ∂ (μ.map f), p y) :
∀ᵐ x ∂ μ, p (f x) :=
mem_ae_of_mem_ae_map hf h
lemma ae_map_mem_range {m0 : measurable_space α} (f : α → β) (hf : measurable_set (range f))
(μ : measure α) :
∀ᵐ x ∂(μ.map f), x ∈ range f :=
begin
by_cases h : ae_measurable f μ,
{ change range f ∈ (μ.map f).ae,
rw mem_ae_map_iff h hf,
apply eventually_of_forall,
exact mem_range_self },
{ simp [map_of_not_ae_measurable h] }
end
@[simp] lemma ae_restrict_Union_eq [countable ι] (s : ι → set α) :
(μ.restrict (⋃ i, s i)).ae = ⨆ i, (μ.restrict (s i)).ae :=
le_antisymm (ae_sum_eq (λ i, μ.restrict (s i)) ▸ ae_mono restrict_Union_le) $
supr_le $ λ i, ae_mono $ restrict_mono (subset_Union s i) le_rfl
@[simp] lemma ae_restrict_union_eq (s t : set α) :
(μ.restrict (s ∪ t)).ae = (μ.restrict s).ae ⊔ (μ.restrict t).ae :=
by simp [union_eq_Union, supr_bool_eq]
lemma ae_restrict_bUnion_eq (s : ι → set α) {t : set ι} (ht : t.countable) :
(μ.restrict (⋃ i ∈ t, s i)).ae = ⨆ i ∈ t, (μ.restrict (s i)).ae :=
begin
haveI := ht.to_subtype,
rw [bUnion_eq_Union, ae_restrict_Union_eq, ← supr_subtype''],
end
lemma ae_restrict_bUnion_finset_eq (s : ι → set α) (t : finset ι) :
(μ.restrict (⋃ i ∈ t, s i)).ae = ⨆ i ∈ t, (μ.restrict (s i)).ae :=
ae_restrict_bUnion_eq s t.countable_to_set
lemma ae_restrict_Union_iff [countable ι] (s : ι → set α) (p : α → Prop) :
(∀ᵐ x ∂ (μ.restrict (⋃ i, s i)), p x) ↔ (∀ i, (∀ᵐ x ∂ (μ.restrict (s i)), p x)) :=
by simp
lemma ae_restrict_union_iff (s t : set α) (p : α → Prop) :
(∀ᵐ x ∂ (μ.restrict (s ∪ t)), p x) ↔
((∀ᵐ x ∂ (μ.restrict s), p x) ∧ (∀ᵐ x ∂ (μ.restrict t), p x)) :=
by simp
lemma ae_restrict_bUnion_iff (s : ι → set α) {t : set ι} (ht : t.countable) (p : α → Prop) :
(∀ᵐ x ∂(μ.restrict (⋃ i ∈ t, s i)), p x) ↔ ∀ i ∈ t, ∀ᵐ x ∂(μ.restrict (s i)), p x :=
by simp_rw [filter.eventually, ae_restrict_bUnion_eq s ht, mem_supr]
@[simp] lemma ae_restrict_bUnion_finset_iff (s : ι → set α) (t : finset ι) (p : α → Prop) :
(∀ᵐ x ∂(μ.restrict (⋃ i ∈ t, s i)), p x) ↔ ∀ i ∈ t, ∀ᵐ x ∂(μ.restrict (s i)), p x :=
by simp_rw [filter.eventually, ae_restrict_bUnion_finset_eq s, mem_supr]
lemma ae_eq_restrict_Union_iff [countable ι] (s : ι → set α) (f g : α → δ) :
f =ᵐ[μ.restrict (⋃ i, s i)] g ↔ ∀ i, f =ᵐ[μ.restrict (s i)] g :=
by simp_rw [eventually_eq, ae_restrict_Union_eq, eventually_supr]
lemma ae_eq_restrict_bUnion_iff (s : ι → set α) {t : set ι} (ht : t.countable) (f g : α → δ) :
f =ᵐ[μ.restrict (⋃ i ∈ t, s i)] g ↔ ∀ i ∈ t, f =ᵐ[μ.restrict (s i)] g :=
by simp_rw [ae_restrict_bUnion_eq s ht, eventually_eq, eventually_supr]
lemma ae_eq_restrict_bUnion_finset_iff (s : ι → set α) (t : finset ι) (f g : α → δ) :
f =ᵐ[μ.restrict (⋃ i ∈ t, s i)] g ↔ ∀ i ∈ t, f =ᵐ[μ.restrict (s i)] g :=
ae_eq_restrict_bUnion_iff s t.countable_to_set f g
lemma ae_restrict_uIoc_eq [linear_order α] (a b : α) :
(μ.restrict (Ι a b)).ae = (μ.restrict (Ioc a b)).ae ⊔ (μ.restrict (Ioc b a)).ae :=
by simp only [uIoc_eq_union, ae_restrict_union_eq]
/-- See also `measure_theory.ae_uIoc_iff`. -/
lemma ae_restrict_uIoc_iff [linear_order α] {a b : α} {P : α → Prop} :
(∀ᵐ x ∂μ.restrict (Ι a b), P x) ↔
(∀ᵐ x ∂μ.restrict (Ioc a b), P x) ∧ (∀ᵐ x ∂μ.restrict (Ioc b a), P x) :=
by rw [ae_restrict_uIoc_eq, eventually_sup]
lemma ae_restrict_iff {p : α → Prop} (hp : measurable_set {x | p x}) :
(∀ᵐ x ∂(μ.restrict s), p x) ↔ ∀ᵐ x ∂μ, x ∈ s → p x :=
begin
simp only [ae_iff, ← compl_set_of, restrict_apply hp.compl],
congr' with x, simp [and_comm]
end
lemma ae_imp_of_ae_restrict {s : set α} {p : α → Prop} (h : ∀ᵐ x ∂(μ.restrict s), p x) :
∀ᵐ x ∂μ, x ∈ s → p x :=
begin
simp only [ae_iff] at h ⊢,
simpa [set_of_and, inter_comm] using measure_inter_eq_zero_of_restrict h
end
lemma ae_restrict_iff' {p : α → Prop} (hs : measurable_set s) :
(∀ᵐ x ∂(μ.restrict s), p x) ↔ ∀ᵐ x ∂μ, x ∈ s → p x :=
begin
simp only [ae_iff, ← compl_set_of, restrict_apply_eq_zero' hs],
congr' with x, simp [and_comm]
end
lemma _root_.filter.eventually_eq.restrict {f g : α → δ} {s : set α} (hfg : f =ᵐ[μ] g) :
f =ᵐ[μ.restrict s] g :=
begin -- note that we cannot use `ae_restrict_iff` since we do not require measurability
refine hfg.filter_mono _,
rw measure.ae_le_iff_absolutely_continuous,
exact measure.absolutely_continuous_of_le measure.restrict_le_self,
end
lemma ae_restrict_mem (hs : measurable_set s) :
∀ᵐ x ∂(μ.restrict s), x ∈ s :=
(ae_restrict_iff' hs).2 (filter.eventually_of_forall (λ x, id))
lemma ae_restrict_mem₀ (hs : null_measurable_set s μ) : ∀ᵐ x ∂(μ.restrict s), x ∈ s :=
begin
rcases hs.exists_measurable_subset_ae_eq with ⟨t, hts, htm, ht_eq⟩,
rw ← restrict_congr_set ht_eq,
exact (ae_restrict_mem htm).mono hts
end
lemma ae_restrict_of_ae {s : set α} {p : α → Prop} (h : ∀ᵐ x ∂μ, p x) :
(∀ᵐ x ∂(μ.restrict s), p x) :=
eventually.filter_mono (ae_mono measure.restrict_le_self) h
lemma ae_restrict_iff'₀ {p : α → Prop} (hs : null_measurable_set s μ) :
(∀ᵐ x ∂(μ.restrict s), p x) ↔ ∀ᵐ x ∂μ, x ∈ s → p x :=
begin
refine ⟨λ h, ae_imp_of_ae_restrict h, λ h, _⟩,
filter_upwards [ae_restrict_mem₀ hs, ae_restrict_of_ae h] with x hx h'x using h'x hx,
end
lemma ae_restrict_of_ae_restrict_of_subset {s t : set α} {p : α → Prop} (hst : s ⊆ t)
(h : ∀ᵐ x ∂(μ.restrict t), p x) :
(∀ᵐ x ∂(μ.restrict s), p x) :=
h.filter_mono (ae_mono $ measure.restrict_mono hst (le_refl μ))
lemma ae_of_ae_restrict_of_ae_restrict_compl (t : set α) {p : α → Prop}
(ht : ∀ᵐ x ∂(μ.restrict t), p x) (htc : ∀ᵐ x ∂(μ.restrict tᶜ), p x) :
∀ᵐ x ∂μ, p x :=
nonpos_iff_eq_zero.1 $
calc μ {x | ¬p x} = μ ({x | ¬p x} ∩ t ∪ {x | ¬p x} ∩ tᶜ) :
by rw [← inter_union_distrib_left, union_compl_self, inter_univ]
... ≤ μ ({x | ¬p x} ∩ t) + μ ({x | ¬p x} ∩ tᶜ) : measure_union_le _ _
... ≤ μ.restrict t {x | ¬p x} + μ.restrict tᶜ {x | ¬p x} :
add_le_add (le_restrict_apply _ _) (le_restrict_apply _ _)
... = 0 : by rw [ae_iff.1 ht, ae_iff.1 htc, zero_add]
lemma mem_map_restrict_ae_iff {β} {s : set α} {t : set β} {f : α → β} (hs : measurable_set s) :
t ∈ filter.map f (μ.restrict s).ae ↔ μ ((f ⁻¹' t)ᶜ ∩ s) = 0 :=
by rw [mem_map, mem_ae_iff, measure.restrict_apply' hs]
lemma ae_smul_measure {p : α → Prop} [monoid R] [distrib_mul_action R ℝ≥0∞]
[is_scalar_tower R ℝ≥0∞ ℝ≥0∞] (h : ∀ᵐ x ∂μ, p x) (c : R) :
∀ᵐ x ∂(c • μ), p x :=
ae_iff.2 $ by rw [smul_apply, ae_iff.1 h, smul_zero]
lemma ae_add_measure_iff {p : α → Prop} {ν} : (∀ᵐ x ∂μ + ν, p x) ↔ (∀ᵐ x ∂μ, p x) ∧ ∀ᵐ x ∂ν, p x :=
add_eq_zero_iff
lemma ae_eq_comp' {ν : measure β} {f : α → β} {g g' : β → δ} (hf : ae_measurable f μ)
(h : g =ᵐ[ν] g') (h2 : μ.map f ≪ ν) : g ∘ f =ᵐ[μ] g' ∘ f :=
(tendsto_ae_map hf).mono_right h2.ae_le h
lemma measure.quasi_measure_preserving.ae_eq_comp {ν : measure β} {f : α → β} {g g' : β → δ}
(hf : quasi_measure_preserving f μ ν) (h : g =ᵐ[ν] g') : g ∘ f =ᵐ[μ] g' ∘ f :=
ae_eq_comp' hf.ae_measurable h hf.absolutely_continuous
lemma ae_eq_comp {f : α → β} {g g' : β → δ} (hf : ae_measurable f μ)
(h : g =ᵐ[μ.map f] g') : g ∘ f =ᵐ[μ] g' ∘ f :=
ae_eq_comp' hf h absolutely_continuous.rfl
lemma sub_ae_eq_zero {β} [add_group β] (f g : α → β) : f - g =ᵐ[μ] 0 ↔ f =ᵐ[μ] g :=
begin
refine ⟨λ h, h.mono (λ x hx, _), λ h, h.mono (λ x hx, _)⟩,
{ rwa [pi.sub_apply, pi.zero_apply, sub_eq_zero] at hx, },
{ rwa [pi.sub_apply, pi.zero_apply, sub_eq_zero], },
end
lemma le_ae_restrict : μ.ae ⊓ 𝓟 s ≤ (μ.restrict s).ae :=
λ s hs, eventually_inf_principal.2 (ae_imp_of_ae_restrict hs)
@[simp] lemma ae_restrict_eq (hs : measurable_set s) : (μ.restrict s).ae = μ.ae ⊓ 𝓟 s :=
begin
ext t,
simp only [mem_inf_principal, mem_ae_iff, restrict_apply_eq_zero' hs, compl_set_of,
not_imp, and_comm (_ ∈ s)],
refl
end
@[simp] lemma ae_restrict_eq_bot {s} : (μ.restrict s).ae = ⊥ ↔ μ s = 0 :=
ae_eq_bot.trans restrict_eq_zero
@[simp] lemma ae_restrict_ne_bot {s} : (μ.restrict s).ae.ne_bot ↔ 0 < μ s :=
ne_bot_iff.trans $ (not_congr ae_restrict_eq_bot).trans pos_iff_ne_zero.symm
lemma self_mem_ae_restrict {s} (hs : measurable_set s) : s ∈ (μ.restrict s).ae :=
by simp only [ae_restrict_eq hs, exists_prop, mem_principal, mem_inf_iff];
exact ⟨_, univ_mem, s, subset.rfl, (univ_inter s).symm⟩
/-- If two measurable sets are ae_eq then any proposition that is almost everywhere true on one
is almost everywhere true on the other -/
lemma ae_restrict_of_ae_eq_of_ae_restrict {s t} (hst : s =ᵐ[μ] t) {p : α → Prop} :
(∀ᵐ x ∂μ.restrict s, p x) → (∀ᵐ x ∂μ.restrict t, p x) :=
by simp [measure.restrict_congr_set hst]
/-- If two measurable sets are ae_eq then any proposition that is almost everywhere true on one
is almost everywhere true on the other -/
lemma ae_restrict_congr_set {s t} (hst : s =ᵐ[μ] t) {p : α → Prop} :
(∀ᵐ x ∂μ.restrict s, p x) ↔ (∀ᵐ x ∂μ.restrict t, p x) :=
⟨ae_restrict_of_ae_eq_of_ae_restrict hst, ae_restrict_of_ae_eq_of_ae_restrict hst.symm⟩
/-- A version of the **Borel-Cantelli lemma**: if `pᵢ` is a sequence of predicates such that
`∑ μ {x | pᵢ x}` is finite, then the measure of `x` such that `pᵢ x` holds frequently as `i → ∞` (or
equivalently, `pᵢ x` holds for infinitely many `i`) is equal to zero. -/
lemma measure_set_of_frequently_eq_zero {p : ℕ → α → Prop} (hp : ∑' i, μ {x | p i x} ≠ ∞) :
μ {x | ∃ᶠ n in at_top, p n x} = 0 :=
by simpa only [limsup_eq_infi_supr_of_nat, frequently_at_top, set_of_forall, set_of_exists]
using measure_limsup_eq_zero hp
/-- A version of the **Borel-Cantelli lemma**: if `sᵢ` is a sequence of sets such that
`∑ μ sᵢ` exists, then for almost all `x`, `x` does not belong to almost all `sᵢ`. -/
lemma ae_eventually_not_mem {s : ℕ → set α} (hs : ∑' i, μ (s i) ≠ ∞) :
∀ᵐ x ∂ μ, ∀ᶠ n in at_top, x ∉ s n :=
measure_set_of_frequently_eq_zero hs
section intervals
lemma bsupr_measure_Iic [preorder α] {s : set α} (hsc : s.countable)
(hst : ∀ x : α, ∃ y ∈ s, x ≤ y) (hdir : directed_on (≤) s) :
(⨆ x ∈ s, μ (Iic x)) = μ univ :=
begin
rw ← measure_bUnion_eq_supr hsc,
{ congr, exact Union₂_eq_univ_iff.2 hst },
{ exact directed_on_iff_directed.2 (hdir.directed_coe.mono_comp _ $ λ x y, Iic_subset_Iic.2) }
end
variables [partial_order α] {a b : α}
lemma Iio_ae_eq_Iic' (ha : μ {a} = 0) : Iio a =ᵐ[μ] Iic a :=
by rw [←Iic_diff_right, diff_ae_eq_self, measure_mono_null (set.inter_subset_right _ _) ha]
lemma Ioi_ae_eq_Ici' (ha : μ {a} = 0) : Ioi a =ᵐ[μ] Ici a := @Iio_ae_eq_Iic' αᵒᵈ ‹_› ‹_› _ _ ha
lemma Ioo_ae_eq_Ioc' (hb : μ {b} = 0) : Ioo a b =ᵐ[μ] Ioc a b :=
(ae_eq_refl _).inter (Iio_ae_eq_Iic' hb)
lemma Ioc_ae_eq_Icc' (ha : μ {a} = 0) : Ioc a b =ᵐ[μ] Icc a b :=
(Ioi_ae_eq_Ici' ha).inter (ae_eq_refl _)
lemma Ioo_ae_eq_Ico' (ha : μ {a} = 0) : Ioo a b =ᵐ[μ] Ico a b :=
(Ioi_ae_eq_Ici' ha).inter (ae_eq_refl _)
lemma Ioo_ae_eq_Icc' (ha : μ {a} = 0) (hb : μ {b} = 0) : Ioo a b =ᵐ[μ] Icc a b :=
(Ioi_ae_eq_Ici' ha).inter (Iio_ae_eq_Iic' hb)
lemma Ico_ae_eq_Icc' (hb : μ {b} = 0) : Ico a b =ᵐ[μ] Icc a b :=
(ae_eq_refl _).inter (Iio_ae_eq_Iic' hb)
lemma Ico_ae_eq_Ioc' (ha : μ {a} = 0) (hb : μ {b} = 0) : Ico a b =ᵐ[μ] Ioc a b :=
(Ioo_ae_eq_Ico' ha).symm.trans (Ioo_ae_eq_Ioc' hb)
end intervals
section dirac
variable [measurable_space α]
lemma mem_ae_dirac_iff {a : α} (hs : measurable_set s) : s ∈ (dirac a).ae ↔ a ∈ s :=
by by_cases a ∈ s; simp [mem_ae_iff, dirac_apply', hs.compl, indicator_apply, *]
lemma ae_dirac_iff {a : α} {p : α → Prop} (hp : measurable_set {x | p x}) :
(∀ᵐ x ∂(dirac a), p x) ↔ p a :=
mem_ae_dirac_iff hp
@[simp] lemma ae_dirac_eq [measurable_singleton_class α] (a : α) : (dirac a).ae = pure a :=
by { ext s, simp [mem_ae_iff, imp_false] }
lemma ae_eq_dirac' [measurable_singleton_class β] {a : α} {f : α → β} (hf : measurable f) :
f =ᵐ[dirac a] const α (f a) :=
(ae_dirac_iff $ show measurable_set (f ⁻¹' {f a}), from hf $ measurable_set_singleton _).2 rfl
lemma ae_eq_dirac [measurable_singleton_class α] {a : α} (f : α → δ) :
f =ᵐ[dirac a] const α (f a) :=
by simp [filter.eventually_eq]
end dirac
section is_finite_measure
include m0
/-- A measure `μ` is called finite if `μ univ < ∞`. -/
class is_finite_measure (μ : measure α) : Prop := (measure_univ_lt_top : μ univ < ∞)
lemma not_is_finite_measure_iff : ¬ is_finite_measure μ ↔ μ set.univ = ∞ :=
begin
refine ⟨λ h, _, λ h, λ h', h'.measure_univ_lt_top.ne h⟩,
by_contra h',
exact h ⟨lt_top_iff_ne_top.mpr h'⟩,
end
instance restrict.is_finite_measure (μ : measure α) [hs : fact (μ s < ∞)] :
is_finite_measure (μ.restrict s) :=
⟨by simp [hs.elim]⟩
lemma measure_lt_top (μ : measure α) [is_finite_measure μ] (s : set α) : μ s < ∞ :=
(measure_mono (subset_univ s)).trans_lt is_finite_measure.measure_univ_lt_top
instance is_finite_measure_restrict (μ : measure α) (s : set α) [h : is_finite_measure μ] :
is_finite_measure (μ.restrict s) :=
⟨by simp [measure_lt_top μ s]⟩
lemma measure_ne_top (μ : measure α) [is_finite_measure μ] (s : set α) : μ s ≠ ∞ :=
ne_of_lt (measure_lt_top μ s)
lemma measure_compl_le_add_of_le_add [is_finite_measure μ] (hs : measurable_set s)
(ht : measurable_set t) {ε : ℝ≥0∞} (h : μ s ≤ μ t + ε) :
μ tᶜ ≤ μ sᶜ + ε :=
begin
rw [measure_compl ht (measure_ne_top μ _), measure_compl hs (measure_ne_top μ _),
tsub_le_iff_right],
calc μ univ = μ univ - μ s + μ s :
(tsub_add_cancel_of_le $ measure_mono s.subset_univ).symm
... ≤ μ univ - μ s + (μ t + ε) : add_le_add_left h _
... = _ : by rw [add_right_comm, add_assoc]
end
lemma measure_compl_le_add_iff [is_finite_measure μ] (hs : measurable_set s)
(ht : measurable_set t) {ε : ℝ≥0∞} :
μ sᶜ ≤ μ tᶜ + ε ↔ μ t ≤ μ s + ε :=
⟨λ h, compl_compl s ▸ compl_compl t ▸ measure_compl_le_add_of_le_add hs.compl ht.compl h,
measure_compl_le_add_of_le_add ht hs⟩
/-- The measure of the whole space with respect to a finite measure, considered as `ℝ≥0`. -/
def measure_univ_nnreal (μ : measure α) : ℝ≥0 := (μ univ).to_nnreal
@[simp] lemma coe_measure_univ_nnreal (μ : measure α) [is_finite_measure μ] :
↑(measure_univ_nnreal μ) = μ univ :=
ennreal.coe_to_nnreal (measure_ne_top μ univ)
instance is_finite_measure_zero : is_finite_measure (0 : measure α) := ⟨by simp⟩
@[priority 100]
instance is_finite_measure_of_is_empty [is_empty α] : is_finite_measure μ :=
by { rw eq_zero_of_is_empty μ, apply_instance }
@[simp] lemma measure_univ_nnreal_zero : measure_univ_nnreal (0 : measure α) = 0 := rfl
omit m0
instance is_finite_measure_add [is_finite_measure μ] [is_finite_measure ν] :
is_finite_measure (μ + ν) :=
{ measure_univ_lt_top :=
begin
rw [measure.coe_add, pi.add_apply, ennreal.add_lt_top],
exact ⟨measure_lt_top _ _, measure_lt_top _ _⟩,
end }
instance is_finite_measure_smul_nnreal [is_finite_measure μ] {r : ℝ≥0} :
is_finite_measure (r • μ) :=
{ measure_univ_lt_top := ennreal.mul_lt_top ennreal.coe_ne_top (measure_ne_top _ _) }
instance is_finite_measure_smul_of_nnreal_tower
{R} [has_smul R ℝ≥0] [has_smul R ℝ≥0∞] [is_scalar_tower R ℝ≥0 ℝ≥0∞]
[is_scalar_tower R ℝ≥0∞ ℝ≥0∞]
[is_finite_measure μ] {r : R} :
is_finite_measure (r • μ) :=
begin
rw ←smul_one_smul ℝ≥0 r μ,
apply_instance,
end
lemma is_finite_measure_of_le (μ : measure α) [is_finite_measure μ] (h : ν ≤ μ) :
is_finite_measure ν :=
{ measure_univ_lt_top := lt_of_le_of_lt (h set.univ measurable_set.univ) (measure_lt_top _ _) }
@[instance] lemma measure.is_finite_measure_map {m : measurable_space α}
(μ : measure α) [is_finite_measure μ] (f : α → β) :
is_finite_measure (μ.map f) :=
begin
by_cases hf : ae_measurable f μ,
{ constructor, rw map_apply_of_ae_measurable hf measurable_set.univ, exact measure_lt_top μ _ },
{ rw map_of_not_ae_measurable hf, exact measure_theory.is_finite_measure_zero }
end
@[simp] lemma measure_univ_nnreal_eq_zero [is_finite_measure μ] :
measure_univ_nnreal μ = 0 ↔ μ = 0 :=
begin
rw [← measure_theory.measure.measure_univ_eq_zero, ← coe_measure_univ_nnreal],
norm_cast
end
lemma measure_univ_nnreal_pos [is_finite_measure μ] (hμ : μ ≠ 0) : 0 < measure_univ_nnreal μ :=
begin
contrapose! hμ,
simpa [measure_univ_nnreal_eq_zero, le_zero_iff] using hμ
end
/-- `le_of_add_le_add_left` is normally applicable to `ordered_cancel_add_comm_monoid`,
but it holds for measures with the additional assumption that μ is finite. -/
lemma measure.le_of_add_le_add_left [is_finite_measure μ] (A2 : μ + ν₁ ≤ μ + ν₂) : ν₁ ≤ ν₂ :=
λ S B1, ennreal.le_of_add_le_add_left (measure_theory.measure_ne_top μ S) (A2 S B1)
lemma summable_measure_to_real [hμ : is_finite_measure μ]
{f : ℕ → set α} (hf₁ : ∀ (i : ℕ), measurable_set (f i)) (hf₂ : pairwise (disjoint on f)) :
summable (λ x, (μ (f x)).to_real) :=
begin
apply ennreal.summable_to_real,
rw ← measure_theory.measure_Union hf₂ hf₁,
exact ne_of_lt (measure_lt_top _ _)
end
lemma ae_eq_univ_iff_measure_eq [is_finite_measure μ] (hs : null_measurable_set s μ) :
s =ᵐ[μ] univ ↔ μ s = μ univ :=
begin
refine ⟨measure_congr, λ h, _⟩,
obtain ⟨t, -, ht₁, ht₂⟩ := hs.exists_measurable_subset_ae_eq,
exact ht₂.symm.trans (ae_eq_of_subset_of_measure_ge (subset_univ t)
(eq.le ((measure_congr ht₂).trans h).symm) ht₁ (measure_ne_top μ univ)),
end
lemma ae_iff_measure_eq [is_finite_measure μ] {p : α → Prop}
(hp : null_measurable_set {a | p a} μ) :
(∀ᵐ a ∂μ, p a) ↔ μ {a | p a} = μ univ :=
by rw [← ae_eq_univ_iff_measure_eq hp, eventually_eq_univ, eventually_iff]
lemma ae_mem_iff_measure_eq [is_finite_measure μ] {s : set α}
(hs : null_measurable_set s μ) :
(∀ᵐ a ∂μ, a ∈ s) ↔ μ s = μ univ :=
ae_iff_measure_eq hs
instance [finite α] [measurable_space α] : is_finite_measure (measure.count : measure α) :=
⟨by { casesI nonempty_fintype α,
simpa [measure.count_apply, tsum_fintype] using (ennreal.nat_ne_top _).lt_top }⟩
end is_finite_measure
section is_probability_measure
include m0
/-- A measure `μ` is called a probability measure if `μ univ = 1`. -/
class is_probability_measure (μ : measure α) : Prop := (measure_univ : μ univ = 1)
export is_probability_measure (measure_univ)
attribute [simp] is_probability_measure.measure_univ
@[priority 100]
instance is_probability_measure.to_is_finite_measure (μ : measure α) [is_probability_measure μ] :
is_finite_measure μ :=
⟨by simp only [measure_univ, ennreal.one_lt_top]⟩
lemma is_probability_measure.ne_zero (μ : measure α) [is_probability_measure μ] : μ ≠ 0 :=
mt measure_univ_eq_zero.2 $ by simp [measure_univ]
@[priority 200]
instance is_probability_measure.ae_ne_bot [is_probability_measure μ] : ne_bot μ.ae :=
ae_ne_bot.2 (is_probability_measure.ne_zero μ)
omit m0
instance measure.dirac.is_probability_measure [measurable_space α] {x : α} :
is_probability_measure (dirac x) :=
⟨dirac_apply_of_mem $ mem_univ x⟩
lemma prob_add_prob_compl [is_probability_measure μ]
(h : measurable_set s) : μ s + μ sᶜ = 1 :=
(measure_add_measure_compl h).trans measure_univ
lemma prob_le_one [is_probability_measure μ] : μ s ≤ 1 :=
(measure_mono $ set.subset_univ _).trans_eq measure_univ
lemma is_probability_measure_smul [is_finite_measure μ] (h : μ ≠ 0) :
is_probability_measure ((μ univ)⁻¹ • μ) :=
begin
constructor,
rw [smul_apply, smul_eq_mul, ennreal.inv_mul_cancel],
{ rwa [ne, measure_univ_eq_zero] },
{ exact measure_ne_top _ _ }
end
lemma is_probability_measure_map [is_probability_measure μ] {f : α → β} (hf : ae_measurable f μ) :
is_probability_measure (map f μ) :=
⟨by simp [map_apply_of_ae_measurable, hf]⟩
@[simp] lemma one_le_prob_iff [is_probability_measure μ] : 1 ≤ μ s ↔ μ s = 1 :=
⟨λ h, le_antisymm prob_le_one h, λ h, h ▸ le_refl _⟩
/-- Note that this is not quite as useful as it looks because the measure takes values in `ℝ≥0∞`.
Thus the subtraction appearing is the truncated subtraction of `ℝ≥0∞`, rather than the
better-behaved subtraction of `ℝ`. -/
lemma prob_compl_eq_one_sub [is_probability_measure μ] (hs : measurable_set s) :
μ sᶜ = 1 - μ s :=
by simpa only [measure_univ] using measure_compl hs (measure_lt_top μ s).ne
@[simp] lemma prob_compl_eq_zero_iff [is_probability_measure μ] (hs : measurable_set s) :
μ sᶜ = 0 ↔ μ s = 1 :=
by simp only [prob_compl_eq_one_sub hs, tsub_eq_zero_iff_le, one_le_prob_iff]
@[simp] lemma prob_compl_eq_one_iff [is_probability_measure μ] (hs : measurable_set s) :
μ sᶜ = 1 ↔ μ s = 0 :=
by rwa [← prob_compl_eq_zero_iff hs.compl, compl_compl]
end is_probability_measure
section no_atoms
/-- Measure `μ` *has no atoms* if the measure of each singleton is zero.
NB: Wikipedia assumes that for any measurable set `s` with positive `μ`-measure,
there exists a measurable `t ⊆ s` such that `0 < μ t < μ s`. While this implies `μ {x} = 0`,
the converse is not true. -/
class has_no_atoms {m0 : measurable_space α} (μ : measure α) : Prop :=
(measure_singleton : ∀ x, μ {x} = 0)
export has_no_atoms (measure_singleton)
attribute [simp] measure_singleton
variables [has_no_atoms μ]
lemma _root_.set.subsingleton.measure_zero {α : Type*} {m : measurable_space α} {s : set α}
(hs : s.subsingleton) (μ : measure α) [has_no_atoms μ] :
μ s = 0 :=
hs.induction_on measure_empty measure_singleton
lemma measure.restrict_singleton' {a : α} :
μ.restrict {a} = 0 :=
by simp only [measure_singleton, measure.restrict_eq_zero]
instance (s : set α) : has_no_atoms (μ.restrict s) :=
begin
refine ⟨λ x, _⟩,
obtain ⟨t, hxt, ht1, ht2⟩ := exists_measurable_superset_of_null (measure_singleton x : μ {x} = 0),
apply measure_mono_null hxt,
rw measure.restrict_apply ht1,
apply measure_mono_null (inter_subset_left t s) ht2
end
lemma _root_.set.countable.measure_zero {α : Type*} {m : measurable_space α} {s : set α}
(h : s.countable) (μ : measure α) [has_no_atoms μ] :
μ s = 0 :=
begin
rw [← bUnion_of_singleton s, ← nonpos_iff_eq_zero],
refine le_trans (measure_bUnion_le h _) _,
simp
end
lemma _root_.set.countable.ae_not_mem {α : Type*} {m : measurable_space α} {s : set α}
(h : s.countable) (μ : measure α) [has_no_atoms μ] :
∀ᵐ x ∂μ, x ∉ s :=
by simpa only [ae_iff, not_not] using h.measure_zero μ
lemma _root_.set.finite.measure_zero {α : Type*} {m : measurable_space α} {s : set α}
(h : s.finite) (μ : measure α) [has_no_atoms μ] : μ s = 0 :=
h.countable.measure_zero μ
lemma _root_.finset.measure_zero {α : Type*} {m : measurable_space α}
(s : finset α) (μ : measure α) [has_no_atoms μ] : μ s = 0 :=
s.finite_to_set.measure_zero μ
lemma insert_ae_eq_self (a : α) (s : set α) :
(insert a s : set α) =ᵐ[μ] s :=
union_ae_eq_right.2 $ measure_mono_null (diff_subset _ _) (measure_singleton _)
section
variables [partial_order α] {a b : α}
lemma Iio_ae_eq_Iic : Iio a =ᵐ[μ] Iic a :=
Iio_ae_eq_Iic' (measure_singleton a)
lemma Ioi_ae_eq_Ici : Ioi a =ᵐ[μ] Ici a :=
Ioi_ae_eq_Ici' (measure_singleton a)
lemma Ioo_ae_eq_Ioc : Ioo a b =ᵐ[μ] Ioc a b :=
Ioo_ae_eq_Ioc' (measure_singleton b)
lemma Ioc_ae_eq_Icc : Ioc a b =ᵐ[μ] Icc a b :=
Ioc_ae_eq_Icc' (measure_singleton a)
lemma Ioo_ae_eq_Ico : Ioo a b =ᵐ[μ] Ico a b :=
Ioo_ae_eq_Ico' (measure_singleton a)
lemma Ioo_ae_eq_Icc : Ioo a b =ᵐ[μ] Icc a b :=
Ioo_ae_eq_Icc' (measure_singleton a) (measure_singleton b)
lemma Ico_ae_eq_Icc : Ico a b =ᵐ[μ] Icc a b :=
Ico_ae_eq_Icc' (measure_singleton b)
lemma Ico_ae_eq_Ioc : Ico a b =ᵐ[μ] Ioc a b :=
Ico_ae_eq_Ioc' (measure_singleton a) (measure_singleton b)
end
open_locale interval
lemma uIoc_ae_eq_interval [linear_order α] {a b : α} : Ι a b =ᵐ[μ] [a, b] := Ioc_ae_eq_Icc
end no_atoms
lemma ite_ae_eq_of_measure_zero {γ} (f : α → γ) (g : α → γ) (s : set α) (hs_zero : μ s = 0) :
(λ x, ite (x ∈ s) (f x) (g x)) =ᵐ[μ] g :=
begin
have h_ss : sᶜ ⊆ {a : α | ite (a ∈ s) (f a) (g a) = g a},
from λ x hx, by simp [(set.mem_compl_iff _ _).mp hx],
refine measure_mono_null _ hs_zero,
nth_rewrite 0 ←compl_compl s,
rwa set.compl_subset_compl,
end
lemma ite_ae_eq_of_measure_compl_zero {γ} (f : α → γ) (g : α → γ) (s : set α) (hs_zero : μ sᶜ = 0) :
(λ x, ite (x ∈ s) (f x) (g x)) =ᵐ[μ] f :=
by { filter_upwards [hs_zero], intros, split_ifs, refl }
namespace measure
/-- A measure is called finite at filter `f` if it is finite at some set `s ∈ f`.
Equivalently, it is eventually finite at `s` in `f.small_sets`. -/
def finite_at_filter {m0 : measurable_space α} (μ : measure α) (f : filter α) : Prop :=
∃ s ∈ f, μ s < ∞
lemma finite_at_filter_of_finite {m0 : measurable_space α} (μ : measure α) [is_finite_measure μ]
(f : filter α) :
μ.finite_at_filter f :=
⟨univ, univ_mem, measure_lt_top μ univ⟩
lemma finite_at_filter.exists_mem_basis {f : filter α} (hμ : finite_at_filter μ f)
{p : ι → Prop} {s : ι → set α} (hf : f.has_basis p s) :
∃ i (hi : p i), μ (s i) < ∞ :=
(hf.exists_iff (λ s t hst ht, (measure_mono hst).trans_lt ht)).1 hμ
lemma finite_at_bot {m0 : measurable_space α} (μ : measure α) : μ.finite_at_filter ⊥ :=
⟨∅, mem_bot, by simp only [measure_empty, with_top.zero_lt_top]⟩
/-- `μ` has finite spanning sets in `C` if there is a countable sequence of sets in `C` that have
finite measures. This structure is a type, which is useful if we want to record extra properties
about the sets, such as that they are monotone.
`sigma_finite` is defined in terms of this: `μ` is σ-finite if there exists a sequence of
finite spanning sets in the collection of all measurable sets. -/
@[protect_proj, nolint has_nonempty_instance]
structure finite_spanning_sets_in {m0 : measurable_space α} (μ : measure α) (C : set (set α)) :=
(set : ℕ → set α)
(set_mem : ∀ i, set i ∈ C)
(finite : ∀ i, μ (set i) < ∞)
(spanning : (⋃ i, set i) = univ)
end measure
open measure
/-- A measure `μ` is called σ-finite if there is a countable collection of sets
`{ A i | i ∈ ℕ }` such that `μ (A i) < ∞` and `⋃ i, A i = s`. -/
class sigma_finite {m0 : measurable_space α} (μ : measure α) : Prop :=
(out' : nonempty (μ.finite_spanning_sets_in univ))
theorem sigma_finite_iff :
sigma_finite μ ↔ nonempty (μ.finite_spanning_sets_in univ) :=
⟨λ h, h.1, λ h, ⟨h⟩⟩
theorem sigma_finite.out (h : sigma_finite μ) :
nonempty (μ.finite_spanning_sets_in univ) := h.1
include m0
/-- If `μ` is σ-finite it has finite spanning sets in the collection of all measurable sets. -/
def measure.to_finite_spanning_sets_in (μ : measure α) [h : sigma_finite μ] :
μ.finite_spanning_sets_in {s | measurable_set s} :=
{ set := λ n, to_measurable μ (h.out.some.set n),
set_mem := λ n, measurable_set_to_measurable _ _,
finite := λ n, by { rw measure_to_measurable, exact h.out.some.finite n },
spanning := eq_univ_of_subset (Union_mono $ λ n, subset_to_measurable _ _)
h.out.some.spanning }
/-- A noncomputable way to get a monotone collection of sets that span `univ` and have finite
measure using `classical.some`. This definition satisfies monotonicity in addition to all other
properties in `sigma_finite`. -/
def spanning_sets (μ : measure α) [sigma_finite μ] (i : ℕ) : set α :=
accumulate μ.to_finite_spanning_sets_in.set i
lemma monotone_spanning_sets (μ : measure α) [sigma_finite μ] :
monotone (spanning_sets μ) :=
monotone_accumulate
lemma measurable_spanning_sets (μ : measure α) [sigma_finite μ] (i : ℕ) :
measurable_set (spanning_sets μ i) :=
measurable_set.Union $ λ j, measurable_set.Union $
λ hij, μ.to_finite_spanning_sets_in.set_mem j
lemma measure_spanning_sets_lt_top (μ : measure α) [sigma_finite μ] (i : ℕ) :
μ (spanning_sets μ i) < ∞ :=
measure_bUnion_lt_top (finite_le_nat i) $ λ j _, (μ.to_finite_spanning_sets_in.finite j).ne
lemma Union_spanning_sets (μ : measure α) [sigma_finite μ] :
(⋃ i : ℕ, spanning_sets μ i) = univ :=
by simp_rw [spanning_sets, Union_accumulate, μ.to_finite_spanning_sets_in.spanning]
lemma is_countably_spanning_spanning_sets (μ : measure α) [sigma_finite μ] :
is_countably_spanning (range (spanning_sets μ)) :=
⟨spanning_sets μ, mem_range_self, Union_spanning_sets μ⟩
/-- `spanning_sets_index μ x` is the least `n : ℕ` such that `x ∈ spanning_sets μ n`. -/
def spanning_sets_index (μ : measure α) [sigma_finite μ] (x : α) : ℕ :=
nat.find $ Union_eq_univ_iff.1 (Union_spanning_sets μ) x
lemma measurable_spanning_sets_index (μ : measure α) [sigma_finite μ] :
measurable (spanning_sets_index μ) :=
measurable_find _ $ measurable_spanning_sets μ
lemma preimage_spanning_sets_index_singleton (μ : measure α) [sigma_finite μ] (n : ℕ) :
spanning_sets_index μ ⁻¹' {n} = disjointed (spanning_sets μ) n :=
preimage_find_eq_disjointed _ _ _
lemma spanning_sets_index_eq_iff (μ : measure α) [sigma_finite μ] {x : α} {n : ℕ} :
spanning_sets_index μ x = n ↔ x ∈ disjointed (spanning_sets μ) n :=
by convert set.ext_iff.1 (preimage_spanning_sets_index_singleton μ n) x
lemma mem_disjointed_spanning_sets_index (μ : measure α) [sigma_finite μ] (x : α) :
x ∈ disjointed (spanning_sets μ) (spanning_sets_index μ x) :=
(spanning_sets_index_eq_iff μ).1 rfl
lemma mem_spanning_sets_index (μ : measure α) [sigma_finite μ] (x : α) :
x ∈ spanning_sets μ (spanning_sets_index μ x) :=
disjointed_subset _ _ (mem_disjointed_spanning_sets_index μ x)
lemma mem_spanning_sets_of_index_le (μ : measure α) [sigma_finite μ] (x : α)
{n : ℕ} (hn : spanning_sets_index μ x ≤ n) :
x ∈ spanning_sets μ n :=
monotone_spanning_sets μ hn (mem_spanning_sets_index μ x)
lemma eventually_mem_spanning_sets (μ : measure α) [sigma_finite μ] (x : α) :
∀ᶠ n in at_top, x ∈ spanning_sets μ n :=
eventually_at_top.2 ⟨spanning_sets_index μ x, λ b, mem_spanning_sets_of_index_le μ x⟩
omit m0
namespace measure
lemma supr_restrict_spanning_sets [sigma_finite μ] (hs : measurable_set s) :
(⨆ i, μ.restrict (spanning_sets μ i) s) = μ s :=
calc (⨆ i, μ.restrict (spanning_sets μ i) s) = μ.restrict (⋃ i, spanning_sets μ i) s :
(restrict_Union_apply_eq_supr (directed_of_sup (monotone_spanning_sets μ)) hs).symm
... = μ s : by rw [Union_spanning_sets, restrict_univ]
/-- In a σ-finite space, any measurable set of measure `> r` contains a measurable subset of
finite measure `> r`. -/
lemma exists_subset_measure_lt_top [sigma_finite μ]
{r : ℝ≥0∞} (hs : measurable_set s) (h's : r < μ s) :
∃ t, measurable_set t ∧ t ⊆ s ∧ r < μ t ∧ μ t < ∞ :=
begin
rw [← supr_restrict_spanning_sets hs,
@lt_supr_iff _ _ _ r (λ (i : ℕ), μ.restrict (spanning_sets μ i) s)] at h's,
rcases h's with ⟨n, hn⟩,
simp only [restrict_apply hs] at hn,
refine ⟨s ∩ spanning_sets μ n, hs.inter (measurable_spanning_sets _ _), inter_subset_left _ _,
hn, _⟩,
exact (measure_mono (inter_subset_right _ _)).trans_lt (measure_spanning_sets_lt_top _ _),
end
/-- A set in a σ-finite space has zero measure if and only if its intersection with
all members of the countable family of finite measure spanning sets has zero measure. -/
lemma forall_measure_inter_spanning_sets_eq_zero
[measurable_space α] {μ : measure α} [sigma_finite μ] (s : set α) :
(∀ n, μ (s ∩ (spanning_sets μ n)) = 0) ↔ μ s = 0 :=
begin
nth_rewrite 0 (show s = ⋃ n, (s ∩ (spanning_sets μ n)),
by rw [← inter_Union, Union_spanning_sets, inter_univ]),
rw [measure_Union_null_iff],
end
/-- A set in a σ-finite space has positive measure if and only if its intersection with
some member of the countable family of finite measure spanning sets has positive measure. -/
lemma exists_measure_inter_spanning_sets_pos
[measurable_space α] {μ : measure α} [sigma_finite μ] (s : set α) :
(∃ n, 0 < μ (s ∩ (spanning_sets μ n))) ↔ 0 < μ s :=
begin
rw ← not_iff_not,
simp only [not_exists, not_lt, nonpos_iff_eq_zero],
exact forall_measure_inter_spanning_sets_eq_zero s,
end
/-- If the union of disjoint measurable sets has finite measure, then there are only
finitely many members of the union whose measure exceeds any given positive number. -/
lemma finite_const_le_meas_of_disjoint_Union {ι : Type*} [measurable_space α] (μ : measure α)
{ε : ℝ≥0∞} (ε_pos : 0 < ε) {As : ι → set α} (As_mble : ∀ (i : ι), measurable_set (As i))
(As_disj : pairwise (disjoint on As)) (Union_As_finite : μ (⋃ i, As i) ≠ ∞) :
set.finite {i : ι | ε ≤ μ (As i)} :=
begin
by_contradiction con,
have aux := lt_of_le_of_lt (tsum_meas_le_meas_Union_of_disjoint μ As_mble As_disj)
(lt_top_iff_ne_top.mpr Union_As_finite),
exact con (ennreal.finite_const_le_of_tsum_ne_top aux.ne ε_pos.ne.symm),
end
/-- If the union of disjoint measurable sets has finite measure, then there are only
countably many members of the union whose measure is positive. -/
lemma countable_meas_pos_of_disjoint_of_meas_Union_ne_top {ι : Type*} [measurable_space α]
(μ : measure α) {As : ι → set α} (As_mble : ∀ (i : ι), measurable_set (As i))
(As_disj : pairwise (disjoint on As)) (Union_As_finite : μ (⋃ i, As i) ≠ ∞) :
set.countable {i : ι | 0 < μ (As i)} :=
begin
set posmeas := {i : ι | 0 < μ (As i)} with posmeas_def,
rcases exists_seq_strict_anti_tendsto' (zero_lt_one : (0 : ℝ≥0∞) < 1)
with ⟨as, as_decr, as_mem, as_lim⟩,
set fairmeas := λ (n : ℕ) , {i : ι | as n ≤ μ (As i)} with fairmeas_def,
have countable_union : posmeas = (⋃ n, fairmeas n) ,
{ have fairmeas_eq : ∀ n, fairmeas n = (λ i, μ (As i)) ⁻¹' Ici (as n),
from λ n, by simpa only [fairmeas_def],
simpa only [fairmeas_eq, posmeas_def, ← preimage_Union,
Union_Ici_eq_Ioi_of_lt_of_tendsto (0 : ℝ≥0∞) (λ n, (as_mem n).1) as_lim], },
rw countable_union,
refine countable_Union (λ n, finite.countable _),
refine finite_const_le_meas_of_disjoint_Union μ (as_mem n).1 As_mble As_disj Union_As_finite,
end
/-- In a σ-finite space, among disjoint measurable sets, only countably many can have positive
measure. -/
lemma countable_meas_pos_of_disjoint_Union
{ι : Type*} [measurable_space α] {μ : measure α} [sigma_finite μ]
{As : ι → set α} (As_mble : ∀ (i : ι), measurable_set (As i))
(As_disj : pairwise (disjoint on As)) :
set.countable {i : ι | 0 < μ (As i)} :=
begin
have obs : {i : ι | 0 < μ (As i)} ⊆ (⋃ n, {i : ι | 0 < μ ((As i) ∩ (spanning_sets μ n))}),
{ intros i i_in_nonzeroes,
by_contra con,
simp only [mem_Union, mem_set_of_eq, not_exists, not_lt, nonpos_iff_eq_zero] at *,
simpa [(forall_measure_inter_spanning_sets_eq_zero _).mp con] using i_in_nonzeroes, },
apply countable.mono obs,
refine countable_Union (λ n, countable_meas_pos_of_disjoint_of_meas_Union_ne_top μ _ _ _),
{ exact λ i, measurable_set.inter (As_mble i) (measurable_spanning_sets μ n), },
{ exact λ i j i_ne_j b hbi hbj, As_disj i_ne_j
(hbi.trans (inter_subset_left _ _)) (hbj.trans (inter_subset_left _ _)), },
{ refine (lt_of_le_of_lt (measure_mono _) (measure_spanning_sets_lt_top μ n)).ne,
exact Union_subset (λ i, inter_subset_right _ _), },
end
lemma countable_meas_level_set_pos {α β : Type*}
[measurable_space α] {μ : measure α} [sigma_finite μ]
[measurable_space β] [measurable_singleton_class β] {g : α → β} (g_mble : measurable g) :
set.countable {t : β | 0 < μ {a : α | g a = t}} :=
begin
have level_sets_disjoint : pairwise (disjoint on (λ (t : β), {a : α | g a = t})),
from λ s t hst, disjoint.preimage g (disjoint_singleton.mpr hst),
exact measure.countable_meas_pos_of_disjoint_Union
(λ b, g_mble (‹measurable_singleton_class β›.measurable_set_singleton b)) level_sets_disjoint,
end
/-- If a set `t` is covered by a countable family of finite measure sets, then its measurable
superset `to_measurable μ t` (which has the same measure as `t`) satisfies,
for any measurable set `s`, the equality `μ (to_measurable μ t ∩ s) = μ (t ∩ s)`. -/
lemma measure_to_measurable_inter_of_cover
{s : set α} (hs : measurable_set s) {t : set α} {v : ℕ → set α} (hv : t ⊆ ⋃ n, v n)
(h'v : ∀ n, μ (t ∩ v n) ≠ ∞) :
μ (to_measurable μ t ∩ s) = μ (t ∩ s) :=
begin
-- we show that there is a measurable superset of `t` satisfying the conclusion for any
-- measurable set `s`. It is built on each member of a spanning family using `to_measurable`
-- (which is well behaved for finite measure sets thanks to `measure_to_measurable_inter`), and
-- the desired property passes to the union.
have A : ∃ t' ⊇ t, measurable_set t' ∧ (∀ u, measurable_set u → μ (t' ∩ u) = μ (t ∩ u)),
{ let w := λ n, to_measurable μ (t ∩ v n),
have hw : ∀ n, μ (w n) < ∞,
{ assume n,
simp_rw [w, measure_to_measurable],
exact (h'v n).lt_top },
set t' := ⋃ n, to_measurable μ (t ∩ disjointed w n) with ht',
have tt' : t ⊆ t' := calc
t ⊆ ⋃ n, t ∩ disjointed w n :
begin
rw [← inter_Union, Union_disjointed, inter_Union],
assume x hx,
rcases mem_Union.1 (hv hx) with ⟨n, hn⟩,
refine mem_Union.2 ⟨n, _⟩,
have : x ∈ t ∩ v n := ⟨hx, hn⟩,
exact ⟨hx, subset_to_measurable μ _ this⟩,
end
... ⊆ ⋃ n, to_measurable μ (t ∩ disjointed w n) :
Union_mono (λ n, subset_to_measurable _ _),
refine ⟨t', tt', measurable_set.Union (λ n, measurable_set_to_measurable μ _), λ u hu, _⟩,
apply le_antisymm _ (measure_mono (inter_subset_inter tt' subset.rfl)),
calc μ (t' ∩ u) ≤ ∑' n, μ (to_measurable μ (t ∩ disjointed w n) ∩ u) :
by { rw [ht', Union_inter], exact measure_Union_le _ }
... = ∑' n, μ ((t ∩ disjointed w n) ∩ u) :
begin
congr' 1,
ext1 n,
apply measure_to_measurable_inter hu,
apply ne_of_lt,
calc μ (t ∩ disjointed w n)
≤ μ (t ∩ w n) : measure_mono ((inter_subset_inter_right _ (disjointed_le w n)))
... ≤ μ (w n) : measure_mono (inter_subset_right _ _)
... < ∞ : hw n
end
... = ∑' n, μ.restrict (t ∩ u) (disjointed w n) :
begin
congr' 1,
ext1 n,
rw [restrict_apply, inter_comm t _, inter_assoc],
apply measurable_set.disjointed (λ n, _),
exact measurable_set_to_measurable _ _
end
... = μ.restrict (t ∩ u) (⋃ n, disjointed w n) :
begin
rw measure_Union,
{ exact disjoint_disjointed _ },
{ intro i,
apply measurable_set.disjointed (λ n, _),
exact measurable_set_to_measurable _ _ }
end
... ≤ μ.restrict (t ∩ u) univ : measure_mono (subset_univ _)
... = μ (t ∩ u) : by rw [restrict_apply measurable_set.univ, univ_inter] },
-- thanks to the definition of `to_measurable`, the previous property will also be shared
-- by `to_measurable μ t`, which is enough to conclude the proof.
rw [to_measurable],
split_ifs with ht,
{ apply measure_congr,
exact ae_eq_set_inter ht.some_spec.snd.2 (ae_eq_refl _) },
{ exact A.some_spec.snd.2 s hs },
end
lemma restrict_to_measurable_of_cover {s : set α} {v : ℕ → set α} (hv : s ⊆ ⋃ n, v n)
(h'v : ∀ n, μ (s ∩ v n) ≠ ∞) :
μ.restrict (to_measurable μ s) = μ.restrict s :=
ext $ λ t ht, by simp only [restrict_apply ht, inter_comm t,
measure_to_measurable_inter_of_cover ht hv h'v]
/-- The measurable superset `to_measurable μ t` of `t` (which has the same measure as `t`)
satisfies, for any measurable set `s`, the equality `μ (to_measurable μ t ∩ s) = μ (t ∩ s)`.
This only holds when `μ` is σ-finite. For a version without this assumption (but requiring
that `t` has finite measure), see `measure_to_measurable_inter`. -/
lemma measure_to_measurable_inter_of_sigma_finite
[sigma_finite μ] {s : set α} (hs : measurable_set s) (t : set α) :
μ (to_measurable μ t ∩ s) = μ (t ∩ s) :=
begin
have : t ⊆ ⋃ n, spanning_sets μ n,
{ rw Union_spanning_sets, exact subset_univ _ },
apply measure_to_measurable_inter_of_cover hs this (λ n, ne_of_lt _),
calc μ (t ∩ spanning_sets μ n) ≤ μ(spanning_sets μ n) : measure_mono (inter_subset_right _ _)
... < ∞ : measure_spanning_sets_lt_top μ n,
end
@[simp] lemma restrict_to_measurable_of_sigma_finite [sigma_finite μ] (s : set α) :
μ.restrict (to_measurable μ s) = μ.restrict s :=
ext $ λ t ht, by simp only [restrict_apply ht, inter_comm t,
measure_to_measurable_inter_of_sigma_finite ht]
namespace finite_spanning_sets_in
variables {C D : set (set α)}
/-- If `μ` has finite spanning sets in `C` and `C ∩ {s | μ s < ∞} ⊆ D` then `μ` has finite spanning
sets in `D`. -/
protected def mono' (h : μ.finite_spanning_sets_in C) (hC : C ∩ {s | μ s < ∞} ⊆ D) :
μ.finite_spanning_sets_in D :=
⟨h.set, λ i, hC ⟨h.set_mem i, h.finite i⟩, h.finite, h.spanning⟩
/-- If `μ` has finite spanning sets in `C` and `C ⊆ D` then `μ` has finite spanning sets in `D`. -/
protected def mono (h : μ.finite_spanning_sets_in C) (hC : C ⊆ D) : μ.finite_spanning_sets_in D :=
h.mono' (λ s hs, hC hs.1)
/-- If `μ` has finite spanning sets in the collection of measurable sets `C`, then `μ` is σ-finite.
-/
protected lemma sigma_finite (h : μ.finite_spanning_sets_in C) :
sigma_finite μ :=
⟨⟨h.mono $ subset_univ C⟩⟩
/-- An extensionality for measures. It is `ext_of_generate_from_of_Union` formulated in terms of
`finite_spanning_sets_in`. -/
protected lemma ext {ν : measure α} {C : set (set α)} (hA : ‹_› = generate_from C)
(hC : is_pi_system C) (h : μ.finite_spanning_sets_in C) (h_eq : ∀ s ∈ C, μ s = ν s) : μ = ν :=
ext_of_generate_from_of_Union C _ hA hC h.spanning h.set_mem (λ i, (h.finite i).ne) h_eq
protected lemma is_countably_spanning (h : μ.finite_spanning_sets_in C) : is_countably_spanning C :=
⟨h.set, h.set_mem, h.spanning⟩
end finite_spanning_sets_in
lemma sigma_finite_of_countable {S : set (set α)} (hc : S.countable)
(hμ : ∀ s ∈ S, μ s < ∞) (hU : ⋃₀ S = univ) :
sigma_finite μ :=
begin
obtain ⟨s, hμ, hs⟩ : ∃ s : ℕ → set α, (∀ n, μ (s n) < ∞) ∧ (⋃ n, s n) = univ,
from (@exists_seq_cover_iff_countable _ (λ x, μ x < ⊤) ⟨∅, by simp⟩).2 ⟨S, hc, hμ, hU⟩,
exact ⟨⟨⟨λ n, s n, λ n, trivial, hμ, hs⟩⟩⟩,
end
/-- Given measures `μ`, `ν` where `ν ≤ μ`, `finite_spanning_sets_in.of_le` provides the induced
`finite_spanning_set` with respect to `ν` from a `finite_spanning_set` with respect to `μ`. -/
def finite_spanning_sets_in.of_le (h : ν ≤ μ) {C : set (set α)}
(S : μ.finite_spanning_sets_in C) : ν.finite_spanning_sets_in C :=
{ set := S.set,
set_mem := S.set_mem,
finite := λ n, lt_of_le_of_lt (le_iff'.1 h _) (S.finite n),
spanning := S.spanning }
lemma sigma_finite_of_le (μ : measure α) [hs : sigma_finite μ]
(h : ν ≤ μ) : sigma_finite ν :=
⟨hs.out.map $ finite_spanning_sets_in.of_le h⟩
end measure
/-- Every finite measure is σ-finite. -/
@[priority 100]
instance is_finite_measure.to_sigma_finite {m0 : measurable_space α} (μ : measure α)
[is_finite_measure μ] :
sigma_finite μ :=
⟨⟨⟨λ _, univ, λ _, trivial, λ _, measure_lt_top μ _, Union_const _⟩⟩⟩
lemma sigma_finite_bot_iff (μ : @measure α ⊥) : sigma_finite μ ↔ is_finite_measure μ :=
begin
refine ⟨λ h, ⟨_⟩, λ h, by { haveI := h, apply_instance, }⟩,
haveI : sigma_finite μ := h,
let s := spanning_sets μ,
have hs_univ : (⋃ i, s i) = set.univ := Union_spanning_sets μ,
have hs_meas : ∀ i, measurable_set[⊥] (s i) := measurable_spanning_sets μ,
simp_rw measurable_space.measurable_set_bot_iff at hs_meas,
by_cases h_univ_empty : set.univ = ∅,
{ rw [h_univ_empty, measure_empty], exact ennreal.zero_ne_top.lt_top, },
obtain ⟨i, hsi⟩ : ∃ i, s i = set.univ,
{ by_contra h_not_univ,
push_neg at h_not_univ,
have h_empty : ∀ i, s i = ∅, by simpa [h_not_univ] using hs_meas,
simp [h_empty] at hs_univ,
exact h_univ_empty hs_univ.symm, },
rw ← hsi,
exact measure_spanning_sets_lt_top μ i,
end
include m0
instance restrict.sigma_finite (μ : measure α) [sigma_finite μ] (s : set α) :
sigma_finite (μ.restrict s) :=
begin
refine ⟨⟨⟨spanning_sets μ, λ _, trivial, λ i, _, Union_spanning_sets μ⟩⟩⟩,
rw [restrict_apply (measurable_spanning_sets μ i)],
exact (measure_mono $ inter_subset_left _ _).trans_lt (measure_spanning_sets_lt_top μ i)
end
instance sum.sigma_finite {ι} [finite ι] (μ : ι → measure α) [∀ i, sigma_finite (μ i)] :
sigma_finite (sum μ) :=
begin
casesI nonempty_fintype ι,
have : ∀ n, measurable_set (⋂ (i : ι), spanning_sets (μ i) n) :=
λ n, measurable_set.Inter (λ i, measurable_spanning_sets (μ i) n),
refine ⟨⟨⟨λ n, ⋂ i, spanning_sets (μ i) n, λ _, trivial, λ n, _, _⟩⟩⟩,
{ rw [sum_apply _ (this n), tsum_fintype, ennreal.sum_lt_top_iff],
rintro i -,
exact (measure_mono $ Inter_subset _ i).trans_lt (measure_spanning_sets_lt_top (μ i) n) },
{ rw [Union_Inter_of_monotone], simp_rw [Union_spanning_sets, Inter_univ],
exact λ i, monotone_spanning_sets (μ i), }
end
instance add.sigma_finite (μ ν : measure α) [sigma_finite μ] [sigma_finite ν] :
sigma_finite (μ + ν) :=
by { rw [← sum_cond], refine @sum.sigma_finite _ _ _ _ _ (bool.rec _ _); simpa }
lemma sigma_finite.of_map (μ : measure α) {f : α → β} (hf : ae_measurable f μ)
(h : sigma_finite (μ.map f)) :
sigma_finite μ :=
⟨⟨⟨λ n, f ⁻¹' (spanning_sets (μ.map f) n),
λ n, trivial,
λ n, by simp only [← map_apply_of_ae_measurable hf, measurable_spanning_sets,
measure_spanning_sets_lt_top],
by rw [← preimage_Union, Union_spanning_sets, preimage_univ]⟩⟩⟩
lemma _root_.measurable_equiv.sigma_finite_map {μ : measure α} (f : α ≃ᵐ β) (h : sigma_finite μ) :
sigma_finite (μ.map f) :=
by { refine sigma_finite.of_map _ f.symm.measurable.ae_measurable _,
rwa [map_map f.symm.measurable f.measurable, f.symm_comp_self, measure.map_id] }
/-- Similar to `ae_of_forall_measure_lt_top_ae_restrict`, but where you additionally get the
hypothesis that another σ-finite measure has finite values on `s`. -/
lemma ae_of_forall_measure_lt_top_ae_restrict' {μ : measure α} (ν : measure α) [sigma_finite μ]
[sigma_finite ν] (P : α → Prop)
(h : ∀ s, measurable_set s → μ s < ∞ → ν s < ∞ → ∀ᵐ x ∂(μ.restrict s), P x) :
∀ᵐ x ∂μ, P x :=
begin
have : ∀ n, ∀ᵐ x ∂μ, x ∈ spanning_sets (μ + ν) n → P x,
{ intro n,
have := h (spanning_sets (μ + ν) n) (measurable_spanning_sets _ _) _ _,
exacts [(ae_restrict_iff' (measurable_spanning_sets _ _)).mp this,
(self_le_add_right _ _).trans_lt (measure_spanning_sets_lt_top (μ + ν) _),
(self_le_add_left _ _).trans_lt (measure_spanning_sets_lt_top (μ + ν) _)] },
filter_upwards [ae_all_iff.2 this] with _ hx using hx _ (mem_spanning_sets_index _ _)
end
/-- To prove something for almost all `x` w.r.t. a σ-finite measure, it is sufficient to show that
this holds almost everywhere in sets where the measure has finite value. -/
lemma ae_of_forall_measure_lt_top_ae_restrict {μ : measure α} [sigma_finite μ] (P : α → Prop)
(h : ∀ s, measurable_set s → μ s < ∞ → ∀ᵐ x ∂(μ.restrict s), P x) :
∀ᵐ x ∂μ, P x :=
ae_of_forall_measure_lt_top_ae_restrict' μ P $ λ s hs h2s _, h s hs h2s
/-- A measure is called locally finite if it is finite in some neighborhood of each point. -/
class is_locally_finite_measure [topological_space α] (μ : measure α) : Prop :=
(finite_at_nhds : ∀ x, μ.finite_at_filter (𝓝 x))
@[priority 100] -- see Note [lower instance priority]
instance is_finite_measure.to_is_locally_finite_measure [topological_space α] (μ : measure α)
[is_finite_measure μ] :
is_locally_finite_measure μ :=
⟨λ x, finite_at_filter_of_finite _ _⟩
lemma measure.finite_at_nhds [topological_space α] (μ : measure α)
[is_locally_finite_measure μ] (x : α) :
μ.finite_at_filter (𝓝 x) :=
is_locally_finite_measure.finite_at_nhds x
lemma measure.smul_finite (μ : measure α) [is_finite_measure μ] {c : ℝ≥0∞} (hc : c ≠ ∞) :
is_finite_measure (c • μ) :=
begin
lift c to ℝ≥0 using hc,
exact measure_theory.is_finite_measure_smul_nnreal,
end
lemma measure.exists_is_open_measure_lt_top [topological_space α] (μ : measure α)
[is_locally_finite_measure μ] (x : α) :
∃ s : set α, x ∈ s ∧ is_open s ∧ μ s < ∞ :=
by simpa only [exists_prop, and.assoc]
using (μ.finite_at_nhds x).exists_mem_basis (nhds_basis_opens x)
instance is_locally_finite_measure_smul_nnreal [topological_space α] (μ : measure α)
[is_locally_finite_measure μ] (c : ℝ≥0) : is_locally_finite_measure (c • μ) :=
begin
refine ⟨λ x, _⟩,
rcases μ.exists_is_open_measure_lt_top x with ⟨o, xo, o_open, μo⟩,
refine ⟨o, o_open.mem_nhds xo, _⟩,
apply ennreal.mul_lt_top _ μo.ne,
simp only [ring_hom.to_monoid_hom_eq_coe, ring_hom.coe_monoid_hom, ennreal.coe_ne_top,
ennreal.coe_of_nnreal_hom, ne.def, not_false_iff],
end
protected lemma measure.is_topological_basis_is_open_lt_top [topological_space α] (μ : measure α)
[is_locally_finite_measure μ] :
topological_space.is_topological_basis {s | is_open s ∧ μ s < ∞} :=
begin
refine topological_space.is_topological_basis_of_open_of_nhds (λ s hs, hs.1) _,
assume x s xs hs,
rcases μ.exists_is_open_measure_lt_top x with ⟨v, xv, hv, μv⟩,
refine ⟨v ∩ s, ⟨hv.inter hs, lt_of_le_of_lt _ μv⟩, ⟨xv, xs⟩, inter_subset_right _ _⟩,
exact measure_mono (inter_subset_left _ _),
end
/-- A measure `μ` is finite on compacts if any compact set `K` satisfies `μ K < ∞`. -/
@[protect_proj] class is_finite_measure_on_compacts [topological_space α] (μ : measure α) : Prop :=
(lt_top_of_is_compact : ∀ ⦃K : set α⦄, is_compact K → μ K < ∞)
/-- A compact subset has finite measure for a measure which is finite on compacts. -/
lemma _root_.is_compact.measure_lt_top
[topological_space α] {μ : measure α} [is_finite_measure_on_compacts μ]
⦃K : set α⦄ (hK : is_compact K) : μ K < ∞ :=
is_finite_measure_on_compacts.lt_top_of_is_compact hK
/-- A bounded subset has finite measure for a measure which is finite on compact sets, in a
proper space. -/
lemma _root_.metric.bounded.measure_lt_top [pseudo_metric_space α] [proper_space α]
{μ : measure α} [is_finite_measure_on_compacts μ] ⦃s : set α⦄ (hs : metric.bounded s) :
μ s < ∞ :=
calc μ s ≤ μ (closure s) : measure_mono subset_closure
... < ∞ : (metric.is_compact_of_is_closed_bounded is_closed_closure hs.closure).measure_lt_top
lemma measure_closed_ball_lt_top [pseudo_metric_space α] [proper_space α]
{μ : measure α} [is_finite_measure_on_compacts μ] {x : α} {r : ℝ} :
μ (metric.closed_ball x r) < ∞ :=
metric.bounded_closed_ball.measure_lt_top
lemma measure_ball_lt_top [pseudo_metric_space α] [proper_space α]
{μ : measure α} [is_finite_measure_on_compacts μ] {x : α} {r : ℝ} :
μ (metric.ball x r) < ∞ :=
metric.bounded_ball.measure_lt_top
protected lemma is_finite_measure_on_compacts.smul [topological_space α] (μ : measure α)
[is_finite_measure_on_compacts μ] {c : ℝ≥0∞} (hc : c ≠ ∞) :
is_finite_measure_on_compacts (c • μ) :=
⟨λ K hK, ennreal.mul_lt_top hc (hK.measure_lt_top).ne⟩
/-- Note this cannot be an instance because it would form a typeclass loop with
`is_finite_measure_on_compacts_of_is_locally_finite_measure`. -/
lemma compact_space.is_finite_measure
[topological_space α] [compact_space α] [is_finite_measure_on_compacts μ] :
is_finite_measure μ :=
⟨is_finite_measure_on_compacts.lt_top_of_is_compact is_compact_univ⟩
omit m0
@[priority 100] -- see Note [lower instance priority]
instance sigma_finite_of_locally_finite [topological_space α]
[second_countable_topology α] [is_locally_finite_measure μ] :
sigma_finite μ :=
begin
choose s hsx hsμ using μ.finite_at_nhds,
rcases topological_space.countable_cover_nhds hsx with ⟨t, htc, htU⟩,
refine measure.sigma_finite_of_countable (htc.image s) (ball_image_iff.2 $ λ x hx, hsμ x) _,
rwa sUnion_image
end
/-- A measure which is finite on compact sets in a locally compact space is locally finite.
Not registered as an instance to avoid a loop with the other direction. -/
lemma is_locally_finite_measure_of_is_finite_measure_on_compacts [topological_space α]
[locally_compact_space α] [is_finite_measure_on_compacts μ] :
is_locally_finite_measure μ :=
⟨begin
intro x,
rcases exists_compact_mem_nhds x with ⟨K, K_compact, K_mem⟩,
exact ⟨K, K_mem, K_compact.measure_lt_top⟩,
end⟩
lemma exists_pos_measure_of_cover [countable ι] {U : ι → set α} (hU : (⋃ i, U i) = univ)
(hμ : μ ≠ 0) : ∃ i, 0 < μ (U i) :=
begin
contrapose! hμ with H,
rw [← measure_univ_eq_zero, ← hU],
exact measure_Union_null (λ i, nonpos_iff_eq_zero.1 (H i))
end
lemma exists_pos_preimage_ball [pseudo_metric_space δ] (f : α → δ) (x : δ) (hμ : μ ≠ 0) :
∃ n : ℕ, 0 < μ (f ⁻¹' metric.ball x n) :=
exists_pos_measure_of_cover (by rw [← preimage_Union, metric.Union_ball_nat, preimage_univ]) hμ
lemma exists_pos_ball [pseudo_metric_space α] (x : α) (hμ : μ ≠ 0) :
∃ n : ℕ, 0 < μ (metric.ball x n) :=
exists_pos_preimage_ball id x hμ
/-- If a set has zero measure in a neighborhood of each of its points, then it has zero measure
in a second-countable space. -/
lemma null_of_locally_null [topological_space α] [second_countable_topology α]
(s : set α) (hs : ∀ x ∈ s, ∃ u ∈ 𝓝[s] x, μ u = 0) :
μ s = 0 :=
μ.to_outer_measure.null_of_locally_null s hs
lemma exists_mem_forall_mem_nhds_within_pos_measure [topological_space α]
[second_countable_topology α] {s : set α} (hs : μ s ≠ 0) :
∃ x ∈ s, ∀ t ∈ 𝓝[s] x, 0 < μ t :=
μ.to_outer_measure.exists_mem_forall_mem_nhds_within_pos hs
lemma exists_ne_forall_mem_nhds_pos_measure_preimage {β} [topological_space β] [t1_space β]
[second_countable_topology β] [nonempty β] {f : α → β} (h : ∀ b, ∃ᵐ x ∂μ, f x ≠ b) :
∃ a b : β, a ≠ b ∧ (∀ s ∈ 𝓝 a, 0 < μ (f ⁻¹' s)) ∧ (∀ t ∈ 𝓝 b, 0 < μ (f ⁻¹' t)) :=
begin
-- We use an `outer_measure` so that the proof works without `measurable f`
set m : outer_measure β := outer_measure.map f μ.to_outer_measure,
replace h : ∀ b : β, m {b}ᶜ ≠ 0 := λ b, not_eventually.mpr (h b),
inhabit β,
have : m univ ≠ 0, from ne_bot_of_le_ne_bot (h default) (m.mono' $ subset_univ _),
rcases m.exists_mem_forall_mem_nhds_within_pos this with ⟨b, -, hb⟩,
simp only [nhds_within_univ] at hb,
rcases m.exists_mem_forall_mem_nhds_within_pos (h b) with ⟨a, hab : a ≠ b, ha⟩,
simp only [is_open_compl_singleton.nhds_within_eq hab] at ha,
exact ⟨a, b, hab, ha, hb⟩
end
/-- If two finite measures give the same mass to the whole space and coincide on a π-system made
of measurable sets, then they coincide on all sets in the σ-algebra generated by the π-system. -/
lemma ext_on_measurable_space_of_generate_finite {α} (m₀ : measurable_space α)
{μ ν : measure α} [is_finite_measure μ]
(C : set (set α)) (hμν : ∀ s ∈ C, μ s = ν s) {m : measurable_space α}
(h : m ≤ m₀) (hA : m = measurable_space.generate_from C) (hC : is_pi_system C)
(h_univ : μ set.univ = ν set.univ) {s : set α} (hs : measurable_set[m] s) :
μ s = ν s :=
begin
haveI : is_finite_measure ν := begin
constructor,
rw ← h_univ,
apply is_finite_measure.measure_univ_lt_top,
end,
refine induction_on_inter hA hC (by simp) hμν _ _ hs,
{ intros t h1t h2t,
have h1t_ : @measurable_set α m₀ t, from h _ h1t,
rw [@measure_compl α m₀ μ t h1t_ (@measure_ne_top α m₀ μ _ t),
@measure_compl α m₀ ν t h1t_ (@measure_ne_top α m₀ ν _ t), h_univ, h2t], },
{ intros f h1f h2f h3f,
have h2f_ : ∀ (i : ℕ), @measurable_set α m₀ (f i), from (λ i, h _ (h2f i)),
have h_Union : @measurable_set α m₀ (⋃ (i : ℕ), f i),from @measurable_set.Union α ℕ m₀ _ f h2f_,
simp [measure_Union, h_Union, h1f, h3f, h2f_], },
end
/-- Two finite measures are equal if they are equal on the π-system generating the σ-algebra
(and `univ`). -/
lemma ext_of_generate_finite (C : set (set α)) (hA : m0 = generate_from C) (hC : is_pi_system C)
[is_finite_measure μ] (hμν : ∀ s ∈ C, μ s = ν s) (h_univ : μ univ = ν univ) :
μ = ν :=
measure.ext (λ s hs, ext_on_measurable_space_of_generate_finite m0 C hμν le_rfl hA hC h_univ hs)
namespace measure
section disjointed
include m0
/-- Given `S : μ.finite_spanning_sets_in {s | measurable_set s}`,
`finite_spanning_sets_in.disjointed` provides a `finite_spanning_sets_in {s | measurable_set s}`
such that its underlying sets are pairwise disjoint. -/
protected def finite_spanning_sets_in.disjointed {μ : measure α}
(S : μ.finite_spanning_sets_in {s | measurable_set s}) :
μ.finite_spanning_sets_in {s | measurable_set s} :=
⟨disjointed S.set, measurable_set.disjointed S.set_mem,
λ n, lt_of_le_of_lt (measure_mono (disjointed_subset S.set n)) (S.finite _),
S.spanning ▸ Union_disjointed⟩
lemma finite_spanning_sets_in.disjointed_set_eq {μ : measure α}
(S : μ.finite_spanning_sets_in {s | measurable_set s}) :
S.disjointed.set = disjointed S.set :=
rfl
lemma exists_eq_disjoint_finite_spanning_sets_in
(μ ν : measure α) [sigma_finite μ] [sigma_finite ν] :
∃ (S : μ.finite_spanning_sets_in {s | measurable_set s})
(T : ν.finite_spanning_sets_in {s | measurable_set s}),
S.set = T.set ∧ pairwise (disjoint on S.set) :=
let S := (μ + ν).to_finite_spanning_sets_in.disjointed in
⟨S.of_le (measure.le_add_right le_rfl), S.of_le (measure.le_add_left le_rfl),
rfl, disjoint_disjointed _⟩
end disjointed
namespace finite_at_filter
variables {f g : filter α}
lemma filter_mono (h : f ≤ g) : μ.finite_at_filter g → μ.finite_at_filter f :=
λ ⟨s, hs, hμ⟩, ⟨s, h hs, hμ⟩
lemma inf_of_left (h : μ.finite_at_filter f) : μ.finite_at_filter (f ⊓ g) :=
h.filter_mono inf_le_left
lemma inf_of_right (h : μ.finite_at_filter g) : μ.finite_at_filter (f ⊓ g) :=
h.filter_mono inf_le_right
@[simp] lemma inf_ae_iff : μ.finite_at_filter (f ⊓ μ.ae) ↔ μ.finite_at_filter f :=
begin
refine ⟨_, λ h, h.filter_mono inf_le_left⟩,
rintros ⟨s, ⟨t, ht, u, hu, rfl⟩, hμ⟩,
suffices : μ t ≤ μ (t ∩ u), from ⟨t, ht, this.trans_lt hμ⟩,
exact measure_mono_ae (mem_of_superset hu (λ x hu ht, ⟨ht, hu⟩))
end
alias inf_ae_iff ↔ of_inf_ae _
lemma filter_mono_ae (h : f ⊓ μ.ae ≤ g) (hg : μ.finite_at_filter g) : μ.finite_at_filter f :=
inf_ae_iff.1 (hg.filter_mono h)
protected lemma measure_mono (h : μ ≤ ν) : ν.finite_at_filter f → μ.finite_at_filter f :=
λ ⟨s, hs, hν⟩, ⟨s, hs, (measure.le_iff'.1 h s).trans_lt hν⟩
@[mono] protected lemma mono (hf : f ≤ g) (hμ : μ ≤ ν) :
ν.finite_at_filter g → μ.finite_at_filter f :=
λ h, (h.filter_mono hf).measure_mono hμ
protected lemma eventually (h : μ.finite_at_filter f) : ∀ᶠ s in f.small_sets, μ s < ∞ :=
(eventually_small_sets' $ λ s t hst ht, (measure_mono hst).trans_lt ht).2 h
lemma filter_sup : μ.finite_at_filter f → μ.finite_at_filter g → μ.finite_at_filter (f ⊔ g) :=
λ ⟨s, hsf, hsμ⟩ ⟨t, htg, htμ⟩,
⟨s ∪ t, union_mem_sup hsf htg, (measure_union_le s t).trans_lt (ennreal.add_lt_top.2 ⟨hsμ, htμ⟩)⟩
end finite_at_filter
lemma finite_at_nhds_within [topological_space α] {m0 : measurable_space α} (μ : measure α)
[is_locally_finite_measure μ] (x : α) (s : set α) :
μ.finite_at_filter (𝓝[s] x) :=
(finite_at_nhds μ x).inf_of_left
@[simp] lemma finite_at_principal : μ.finite_at_filter (𝓟 s) ↔ μ s < ∞ :=
⟨λ ⟨t, ht, hμ⟩, (measure_mono ht).trans_lt hμ, λ h, ⟨s, mem_principal_self s, h⟩⟩
lemma is_locally_finite_measure_of_le [topological_space α] {m : measurable_space α}
{μ ν : measure α} [H : is_locally_finite_measure μ] (h : ν ≤ μ) :
is_locally_finite_measure ν :=
let F := H.finite_at_nhds in ⟨λ x, (F x).measure_mono h⟩
end measure
end measure_theory
open measure_theory measure_theory.measure
namespace measurable_embedding
variables {m0 : measurable_space α} {m1 : measurable_space β} {f : α → β}
(hf : measurable_embedding f)
include hf
theorem map_apply (μ : measure α) (s : set β) : μ.map f s = μ (f ⁻¹' s) :=
begin
refine le_antisymm _ (le_map_apply hf.measurable.ae_measurable s),
set t := f '' (to_measurable μ (f ⁻¹' s)) ∪ (range f)ᶜ,
have htm : measurable_set t,
from (hf.measurable_set_image.2 $ measurable_set_to_measurable _ _).union
hf.measurable_set_range.compl,
have hst : s ⊆ t,
{ rw [subset_union_compl_iff_inter_subset, ← image_preimage_eq_inter_range],
exact image_subset _ (subset_to_measurable _ _) },
have hft : f ⁻¹' t = to_measurable μ (f ⁻¹' s),
by rw [preimage_union, preimage_compl, preimage_range, compl_univ, union_empty,
hf.injective.preimage_image],
calc μ.map f s ≤ μ.map f t : measure_mono hst
... = μ (f ⁻¹' s) :
by rw [map_apply hf.measurable htm, hft, measure_to_measurable]
end
lemma map_comap (μ : measure β) : (comap f μ).map f = μ.restrict (range f) :=
begin
ext1 t ht,
rw [hf.map_apply, comap_apply f hf.injective hf.measurable_set_image' _ (hf.measurable ht),
image_preimage_eq_inter_range, restrict_apply ht]
end
lemma comap_apply (μ : measure β) (s : set α) : comap f μ s = μ (f '' s) :=
calc comap f μ s = comap f μ (f ⁻¹' (f '' s)) : by rw hf.injective.preimage_image
... = (comap f μ).map f (f '' s) : (hf.map_apply _ _).symm
... = μ (f '' s) : by rw [hf.map_comap, restrict_apply' hf.measurable_set_range,
inter_eq_self_of_subset_left (image_subset_range _ _)]
lemma ae_map_iff {p : β → Prop} {μ : measure α} : (∀ᵐ x ∂(μ.map f), p x) ↔ ∀ᵐ x ∂μ, p (f x) :=
by simp only [ae_iff, hf.map_apply, preimage_set_of_eq]
lemma restrict_map (μ : measure α) (s : set β) :
(μ.map f).restrict s = (μ.restrict $ f ⁻¹' s).map f :=
measure.ext $ λ t ht, by simp [hf.map_apply, ht, hf.measurable ht]
protected lemma comap_preimage (μ : measure β) {s : set β} (hs : measurable_set s) :
μ.comap f (f ⁻¹' s) = μ (s ∩ range f) :=
comap_preimage _ _ hf.injective hf.measurable
(λ t ht, (hf.measurable_set_image' ht).null_measurable_set) hs
end measurable_embedding
section subtype
lemma comap_subtype_coe_apply {m0 : measurable_space α} {s : set α} (hs : measurable_set s)
(μ : measure α) (t : set s) :
comap coe μ t = μ (coe '' t) :=
(measurable_embedding.subtype_coe hs).comap_apply _ _
lemma map_comap_subtype_coe {m0 : measurable_space α} {s : set α} (hs : measurable_set s)
(μ : measure α) : (comap coe μ).map (coe : s → α) = μ.restrict s :=
by rw [(measurable_embedding.subtype_coe hs).map_comap, subtype.range_coe]
lemma ae_restrict_iff_subtype {m0 : measurable_space α} {μ : measure α} {s : set α}
(hs : measurable_set s) {p : α → Prop} :
(∀ᵐ x ∂(μ.restrict s), p x) ↔ ∀ᵐ x ∂(comap (coe : s → α) μ), p ↑x :=
by rw [← map_comap_subtype_coe hs, (measurable_embedding.subtype_coe hs).ae_map_iff]
variables [measure_space α] {s t : set α}
/-!
### Volume on `s : set α`
-/
instance _root_.set_coe.measure_space (s : set α) : measure_space s :=
⟨comap (coe : s → α) volume⟩
lemma volume_set_coe_def (s : set α) : (volume : measure s) = comap (coe : s → α) volume := rfl
lemma measurable_set.map_coe_volume {s : set α} (hs : measurable_set s) :
volume.map (coe : s → α) = restrict volume s :=
by rw [volume_set_coe_def, (measurable_embedding.subtype_coe hs).map_comap volume,
subtype.range_coe]
lemma volume_image_subtype_coe {s : set α} (hs : measurable_set s) (t : set s) :
volume (coe '' t : set α) = volume t :=
(comap_subtype_coe_apply hs volume t).symm
@[simp] lemma volume_preimage_coe (hs : null_measurable_set s) (ht : measurable_set t) :
volume ((coe : s → α) ⁻¹' t) = volume (t ∩ s) :=
by rw [volume_set_coe_def, comap_apply₀ _ _ subtype.coe_injective
(λ h, measurable_set.null_measurable_set_subtype_coe hs)
(measurable_subtype_coe ht).null_measurable_set, image_preimage_eq_inter_range, subtype.range_coe]
end subtype
namespace measurable_equiv
/-! Interactions of measurable equivalences and measures -/
open equiv measure_theory.measure
variables [measurable_space α] [measurable_space β] {μ : measure α} {ν : measure β}
/-- If we map a measure along a measurable equivalence, we can compute the measure on all sets
(not just the measurable ones). -/
protected theorem map_apply (f : α ≃ᵐ β) (s : set β) : μ.map f s = μ (f ⁻¹' s) :=
f.measurable_embedding.map_apply _ _
@[simp] lemma map_symm_map (e : α ≃ᵐ β) : (μ.map e).map e.symm = μ :=
by simp [map_map e.symm.measurable e.measurable]
@[simp] lemma map_map_symm (e : α ≃ᵐ β) : (ν.map e.symm).map e = ν :=
by simp [map_map e.measurable e.symm.measurable]
lemma map_measurable_equiv_injective (e : α ≃ᵐ β) : injective (map e) :=
by { intros μ₁ μ₂ hμ, apply_fun map e.symm at hμ, simpa [map_symm_map e] using hμ }
lemma map_apply_eq_iff_map_symm_apply_eq (e : α ≃ᵐ β) : μ.map e = ν ↔ ν.map e.symm = μ :=
by rw [← (map_measurable_equiv_injective e).eq_iff, map_map_symm, eq_comm]
lemma restrict_map (e : α ≃ᵐ β) (s : set β) : (μ.map e).restrict s = (μ.restrict $ e ⁻¹' s).map e :=
e.measurable_embedding.restrict_map _ _
lemma map_ae (f : α ≃ᵐ β) (μ : measure α) : filter.map f μ.ae = (map f μ).ae :=
by { ext s, simp_rw [mem_map, mem_ae_iff, ← preimage_compl, f.map_apply] }
lemma quasi_measure_preserving_symm (μ : measure α) (e : α ≃ᵐ β) :
quasi_measure_preserving e.symm (map e μ) μ :=
⟨e.symm.measurable, by rw [measure.map_map, e.symm_comp_self, measure.map_id]; measurability⟩
end measurable_equiv
namespace measure_theory
lemma outer_measure.to_measure_zero [measurable_space α] : (0 : outer_measure α).to_measure
((le_top).trans outer_measure.zero_caratheodory.symm.le) = 0 :=
by rw [← measure.measure_univ_eq_zero, to_measure_apply _ _ measurable_set.univ,
outer_measure.coe_zero, pi.zero_apply]
section trim
/-- Restriction of a measure to a sub-sigma algebra.
It is common to see a measure `μ` on a measurable space structure `m0` as being also a measure on
any `m ≤ m0`. Since measures in mathlib have to be trimmed to the measurable space, `μ` itself
cannot be a measure on `m`, hence the definition of `μ.trim hm`.
This notion is related to `outer_measure.trim`, see the lemma
`to_outer_measure_trim_eq_trim_to_outer_measure`. -/
def measure.trim {m m0 : measurable_space α} (μ : @measure α m0) (hm : m ≤ m0) : @measure α m :=
@outer_measure.to_measure α m μ.to_outer_measure (hm.trans (le_to_outer_measure_caratheodory μ))
@[simp] lemma trim_eq_self [measurable_space α] {μ : measure α} : μ.trim le_rfl = μ :=
by simp [measure.trim]
variables {m m0 : measurable_space α} {μ : measure α} {s : set α}
lemma to_outer_measure_trim_eq_trim_to_outer_measure (μ : measure α) (hm : m ≤ m0) :
@measure.to_outer_measure _ m (μ.trim hm) = @outer_measure.trim _ m μ.to_outer_measure :=
by rw [measure.trim, to_measure_to_outer_measure]
@[simp] lemma zero_trim (hm : m ≤ m0) : (0 : measure α).trim hm = (0 : @measure α m) :=
by simp [measure.trim, outer_measure.to_measure_zero]
lemma trim_measurable_set_eq (hm : m ≤ m0) (hs : @measurable_set α m s) : μ.trim hm s = μ s :=
by simp [measure.trim, hs]
lemma le_trim (hm : m ≤ m0) : μ s ≤ μ.trim hm s :=
by { simp_rw [measure.trim], exact (@le_to_measure_apply _ m _ _ _), }
lemma measure_eq_zero_of_trim_eq_zero (hm : m ≤ m0) (h : μ.trim hm s = 0) : μ s = 0 :=
le_antisymm ((le_trim hm).trans (le_of_eq h)) (zero_le _)
lemma measure_trim_to_measurable_eq_zero {hm : m ≤ m0} (hs : μ.trim hm s = 0) :
μ (@to_measurable α m (μ.trim hm) s) = 0 :=
measure_eq_zero_of_trim_eq_zero hm (by rwa measure_to_measurable)
lemma ae_of_ae_trim (hm : m ≤ m0) {μ : measure α} {P : α → Prop} (h : ∀ᵐ x ∂(μ.trim hm), P x) :
∀ᵐ x ∂μ, P x :=
measure_eq_zero_of_trim_eq_zero hm h
lemma ae_eq_of_ae_eq_trim {E} {hm : m ≤ m0} {f₁ f₂ : α → E}
(h12 : f₁ =ᶠ[@measure.ae α m (μ.trim hm)] f₂) :
f₁ =ᵐ[μ] f₂ :=
measure_eq_zero_of_trim_eq_zero hm h12
lemma ae_le_of_ae_le_trim {E} [has_le E] {hm : m ≤ m0} {f₁ f₂ : α → E}
(h12 : f₁ ≤ᶠ[@measure.ae α m (μ.trim hm)] f₂) :
f₁ ≤ᵐ[μ] f₂ :=
measure_eq_zero_of_trim_eq_zero hm h12
lemma trim_trim {m₁ m₂ : measurable_space α} {hm₁₂ : m₁ ≤ m₂} {hm₂ : m₂ ≤ m0} :
(μ.trim hm₂).trim hm₁₂ = μ.trim (hm₁₂.trans hm₂) :=
begin
ext1 t ht,
rw [trim_measurable_set_eq hm₁₂ ht, trim_measurable_set_eq (hm₁₂.trans hm₂) ht,
trim_measurable_set_eq hm₂ (hm₁₂ t ht)],
end
lemma restrict_trim (hm : m ≤ m0) (μ : measure α) (hs : @measurable_set α m s) :
@measure.restrict α m (μ.trim hm) s = (μ.restrict s).trim hm :=
begin
ext1 t ht,
rw [@measure.restrict_apply α m _ _ _ ht, trim_measurable_set_eq hm ht,
measure.restrict_apply (hm t ht),
trim_measurable_set_eq hm (@measurable_set.inter α m t s ht hs)],
end
instance is_finite_measure_trim (hm : m ≤ m0) [is_finite_measure μ] :
is_finite_measure (μ.trim hm) :=
{ measure_univ_lt_top :=
by { rw trim_measurable_set_eq hm (@measurable_set.univ _ m), exact measure_lt_top _ _, } }
lemma sigma_finite_trim_mono {m m₂ m0 : measurable_space α} {μ : measure α} (hm : m ≤ m0)
(hm₂ : m₂ ≤ m) [sigma_finite (μ.trim (hm₂.trans hm))] :
sigma_finite (μ.trim hm) :=
begin
have h := measure.finite_spanning_sets_in (μ.trim (hm₂.trans hm)) set.univ,
refine measure.finite_spanning_sets_in.sigma_finite _,
{ use set.univ, },
{ refine
{ set := spanning_sets (μ.trim (hm₂.trans hm)),
set_mem := λ _, set.mem_univ _,
finite := λ i, _, -- This is the only one left to prove
spanning := Union_spanning_sets _, },
calc (μ.trim hm) (spanning_sets (μ.trim (hm₂.trans hm)) i)
= ((μ.trim hm).trim hm₂) (spanning_sets (μ.trim (hm₂.trans hm)) i) :
by rw @trim_measurable_set_eq α m₂ m (μ.trim hm) _ hm₂ (measurable_spanning_sets _ _)
... = (μ.trim (hm₂.trans hm)) (spanning_sets (μ.trim (hm₂.trans hm)) i) :
by rw @trim_trim _ _ μ _ _ hm₂ hm
... < ∞ : measure_spanning_sets_lt_top _ _, },
end
lemma sigma_finite_trim_bot_iff : sigma_finite (μ.trim bot_le) ↔ is_finite_measure μ :=
begin
rw sigma_finite_bot_iff,
refine ⟨λ h, ⟨_⟩, λ h, ⟨_⟩⟩; have h_univ := h.measure_univ_lt_top,
{ rwa trim_measurable_set_eq bot_le measurable_set.univ at h_univ, },
{ rwa trim_measurable_set_eq bot_le measurable_set.univ, },
end
end trim
end measure_theory
namespace is_compact
variables [topological_space α] [measurable_space α] {μ : measure α} {s : set α}
/-- If `s` is a compact set and `μ` is finite at `𝓝 x` for every `x ∈ s`, then `s` admits an open
superset of finite measure. -/
lemma exists_open_superset_measure_lt_top' (h : is_compact s)
(hμ : ∀ x ∈ s, μ.finite_at_filter (𝓝 x)) :
∃ U ⊇ s, is_open U ∧ μ U < ∞ :=
begin
refine is_compact.induction_on h _ _ _ _,
{ use ∅, simp [superset] },
{ rintro s t hst ⟨U, htU, hUo, hU⟩, exact ⟨U, hst.trans htU, hUo, hU⟩ },
{ rintro s t ⟨U, hsU, hUo, hU⟩ ⟨V, htV, hVo, hV⟩,
refine ⟨U ∪ V, union_subset_union hsU htV, hUo.union hVo,
(measure_union_le _ _).trans_lt $ ennreal.add_lt_top.2 ⟨hU, hV⟩⟩ },
{ intros x hx,
rcases (hμ x hx).exists_mem_basis (nhds_basis_opens _) with ⟨U, ⟨hx, hUo⟩, hU⟩,
exact ⟨U, nhds_within_le_nhds (hUo.mem_nhds hx), U, subset.rfl, hUo, hU⟩ }
end
/-- If `s` is a compact set and `μ` is a locally finite measure, then `s` admits an open superset of
finite measure. -/
lemma exists_open_superset_measure_lt_top (h : is_compact s)
(μ : measure α) [is_locally_finite_measure μ] :
∃ U ⊇ s, is_open U ∧ μ U < ∞ :=
h.exists_open_superset_measure_lt_top' $ λ x hx, μ.finite_at_nhds x
lemma measure_lt_top_of_nhds_within (h : is_compact s) (hμ : ∀ x ∈ s, μ.finite_at_filter (𝓝[s] x)) :
μ s < ∞ :=
is_compact.induction_on h (by simp) (λ s t hst ht, (measure_mono hst).trans_lt ht)
(λ s t hs ht, (measure_union_le s t).trans_lt (ennreal.add_lt_top.2 ⟨hs, ht⟩)) hμ
lemma measure_zero_of_nhds_within (hs : is_compact s) :
(∀ a ∈ s, ∃ t ∈ 𝓝[s] a, μ t = 0) → μ s = 0 :=
by simpa only [← compl_mem_ae_iff] using hs.compl_mem_sets_of_nhds_within
end is_compact
@[priority 100] -- see Note [lower instance priority]
instance is_finite_measure_on_compacts_of_is_locally_finite_measure
[topological_space α] {m : measurable_space α} {μ : measure α}
[is_locally_finite_measure μ] : is_finite_measure_on_compacts μ :=
⟨λ s hs, hs.measure_lt_top_of_nhds_within $ λ x hx, μ.finite_at_nhds_within _ _⟩
lemma is_finite_measure_iff_is_finite_measure_on_compacts_of_compact_space
[topological_space α] [measurable_space α] {μ : measure α} [compact_space α] :
is_finite_measure μ ↔ is_finite_measure_on_compacts μ :=
begin
split; introsI,
{ apply_instance, },
{ exact compact_space.is_finite_measure, },
end
/-- Compact covering of a `σ`-compact topological space as
`measure_theory.measure.finite_spanning_sets_in`. -/
def measure_theory.measure.finite_spanning_sets_in_compact [topological_space α]
[sigma_compact_space α] {m : measurable_space α} (μ : measure α) [is_locally_finite_measure μ] :
μ.finite_spanning_sets_in {K | is_compact K} :=
{ set := compact_covering α,
set_mem := is_compact_compact_covering α,
finite := λ n, (is_compact_compact_covering α n).measure_lt_top,
spanning := Union_compact_covering α }
/-- A locally finite measure on a `σ`-compact topological space admits a finite spanning sequence
of open sets. -/
def measure_theory.measure.finite_spanning_sets_in_open [topological_space α]
[sigma_compact_space α] {m : measurable_space α} (μ : measure α) [is_locally_finite_measure μ] :
μ.finite_spanning_sets_in {K | is_open K} :=
{ set := λ n, ((is_compact_compact_covering α n).exists_open_superset_measure_lt_top μ).some,
set_mem := λ n,
((is_compact_compact_covering α n).exists_open_superset_measure_lt_top μ).some_spec.snd.1,
finite := λ n,
((is_compact_compact_covering α n).exists_open_superset_measure_lt_top μ).some_spec.snd.2,
spanning := eq_univ_of_subset (Union_mono $ λ n,
((is_compact_compact_covering α n).exists_open_superset_measure_lt_top μ).some_spec.fst)
(Union_compact_covering α) }
open topological_space
/-- A locally finite measure on a second countable topological space admits a finite spanning
sequence of open sets. -/
@[irreducible] def measure_theory.measure.finite_spanning_sets_in_open' [topological_space α]
[second_countable_topology α] {m : measurable_space α} (μ : measure α)
[is_locally_finite_measure μ] :
μ.finite_spanning_sets_in {K | is_open K} :=
begin
suffices H : nonempty (μ.finite_spanning_sets_in {K | is_open K}), from H.some,
casesI is_empty_or_nonempty α,
{ exact
⟨{ set := λ n, ∅, set_mem := λ n, by simp, finite := λ n, by simp, spanning := by simp }⟩ },
inhabit α,
let S : set (set α) := {s | is_open s ∧ μ s < ∞},
obtain ⟨T, T_count, TS, hT⟩ : ∃ T : set (set α), T.countable ∧ T ⊆ S ∧ ⋃₀ T = ⋃₀ S :=
is_open_sUnion_countable S (λ s hs, hs.1),
rw μ.is_topological_basis_is_open_lt_top.sUnion_eq at hT,
have T_ne : T.nonempty,
{ by_contra h'T,
simp only [not_nonempty_iff_eq_empty.1 h'T, sUnion_empty] at hT,
simpa only [← hT] using mem_univ (default : α) },
obtain ⟨f, hf⟩ : ∃ f : ℕ → set α, T = range f, from T_count.exists_eq_range T_ne,
have fS : ∀ n, f n ∈ S,
{ assume n,
apply TS,
rw hf,
exact mem_range_self n },
refine ⟨{ set := f, set_mem := λ n, (fS n).1, finite := λ n, (fS n).2, spanning := _ }⟩,
apply eq_univ_of_forall (λ x, _),
obtain ⟨t, tT, xt⟩ : ∃ (t : set α), t ∈ range f ∧ x ∈ t,
{ have : x ∈ ⋃₀ T, by simp only [hT],
simpa only [mem_sUnion, exists_prop, ← hf] },
obtain ⟨n, rfl⟩ : ∃ (n : ℕ), f n = t, by simpa only using tT,
exact mem_Union_of_mem _ xt,
end
section measure_Ixx
variables [preorder α] [topological_space α] [compact_Icc_space α]
{m : measurable_space α} {μ : measure α} [is_locally_finite_measure μ] {a b : α}
lemma measure_Icc_lt_top : μ (Icc a b) < ∞ := is_compact_Icc.measure_lt_top
lemma measure_Ico_lt_top : μ (Ico a b) < ∞ :=
(measure_mono Ico_subset_Icc_self).trans_lt measure_Icc_lt_top
lemma measure_Ioc_lt_top : μ (Ioc a b) < ∞ :=
(measure_mono Ioc_subset_Icc_self).trans_lt measure_Icc_lt_top
lemma measure_Ioo_lt_top : μ (Ioo a b) < ∞ :=
(measure_mono Ioo_subset_Icc_self).trans_lt measure_Icc_lt_top
end measure_Ixx
section piecewise
variables [measurable_space α] {μ : measure α} {s t : set α} {f g : α → β}
lemma piecewise_ae_eq_restrict (hs : measurable_set s) : piecewise s f g =ᵐ[μ.restrict s] f :=
begin
rw [ae_restrict_eq hs],
exact (piecewise_eq_on s f g).eventually_eq.filter_mono inf_le_right
end
lemma piecewise_ae_eq_restrict_compl (hs : measurable_set s) :
piecewise s f g =ᵐ[μ.restrict sᶜ] g :=
begin
rw [ae_restrict_eq hs.compl],
exact (piecewise_eq_on_compl s f g).eventually_eq.filter_mono inf_le_right
end
lemma piecewise_ae_eq_of_ae_eq_set (hst : s =ᵐ[μ] t) : s.piecewise f g =ᵐ[μ] t.piecewise f g :=
hst.mem_iff.mono $ λ x hx, by simp [piecewise, hx]
end piecewise
section indicator_function
variables [measurable_space α] {μ : measure α} {s t : set α} {f : α → β}
lemma mem_map_indicator_ae_iff_mem_map_restrict_ae_of_zero_mem [has_zero β] {t : set β}
(ht : (0 : β) ∈ t) (hs : measurable_set s) :
t ∈ filter.map (s.indicator f) μ.ae ↔ t ∈ filter.map f (μ.restrict s).ae :=
begin
simp_rw [mem_map, mem_ae_iff],
rw [measure.restrict_apply' hs, set.indicator_preimage, set.ite],
simp_rw [set.compl_union, set.compl_inter],
change μ (((f ⁻¹' t)ᶜ ∪ sᶜ) ∩ ((λ x, (0 : β)) ⁻¹' t \ s)ᶜ) = 0 ↔ μ ((f ⁻¹' t)ᶜ ∩ s) = 0,
simp only [ht, ← set.compl_eq_univ_diff, compl_compl, set.compl_union, if_true,
set.preimage_const],
simp_rw [set.union_inter_distrib_right, set.compl_inter_self s, set.union_empty],
end
lemma mem_map_indicator_ae_iff_of_zero_nmem [has_zero β] {t : set β} (ht : (0 : β) ∉ t) :
t ∈ filter.map (s.indicator f) μ.ae ↔ μ ((f ⁻¹' t)ᶜ ∪ sᶜ) = 0 :=
begin
rw [mem_map, mem_ae_iff, set.indicator_preimage, set.ite, set.compl_union, set.compl_inter],
change μ (((f ⁻¹' t)ᶜ ∪ sᶜ) ∩ ((λ x, (0 : β)) ⁻¹' t \ s)ᶜ) = 0 ↔ μ ((f ⁻¹' t)ᶜ ∪ sᶜ) = 0,
simp only [ht, if_false, set.compl_empty, set.empty_diff, set.inter_univ, set.preimage_const],
end
lemma map_restrict_ae_le_map_indicator_ae [has_zero β] (hs : measurable_set s) :
filter.map f (μ.restrict s).ae ≤ filter.map (s.indicator f) μ.ae :=
begin
intro t,
by_cases ht : (0 : β) ∈ t,
{ rw mem_map_indicator_ae_iff_mem_map_restrict_ae_of_zero_mem ht hs, exact id, },
rw [mem_map_indicator_ae_iff_of_zero_nmem ht, mem_map_restrict_ae_iff hs],
exact λ h, measure_mono_null ((set.inter_subset_left _ _).trans (set.subset_union_left _ _)) h,
end
variables [has_zero β]
lemma indicator_ae_eq_restrict (hs : measurable_set s) : indicator s f =ᵐ[μ.restrict s] f :=
piecewise_ae_eq_restrict hs
lemma indicator_ae_eq_restrict_compl (hs : measurable_set s) : indicator s f =ᵐ[μ.restrict sᶜ] 0 :=
piecewise_ae_eq_restrict_compl hs
lemma indicator_ae_eq_of_restrict_compl_ae_eq_zero (hs : measurable_set s)
(hf : f =ᵐ[μ.restrict sᶜ] 0) :
s.indicator f =ᵐ[μ] f :=
begin
rw [filter.eventually_eq, ae_restrict_iff' hs.compl] at hf,
filter_upwards [hf] with x hx,
by_cases hxs : x ∈ s,
{ simp only [hxs, set.indicator_of_mem], },
{ simp only [hx hxs, pi.zero_apply, set.indicator_apply_eq_zero, eq_self_iff_true,
implies_true_iff], },
end
lemma indicator_ae_eq_zero_of_restrict_ae_eq_zero (hs : measurable_set s)
(hf : f =ᵐ[μ.restrict s] 0) :
s.indicator f =ᵐ[μ] 0 :=
begin
rw [filter.eventually_eq, ae_restrict_iff' hs] at hf,
filter_upwards [hf] with x hx,
by_cases hxs : x ∈ s,
{ simp only [hxs, hx hxs, set.indicator_of_mem], },
{ simp [hx, hxs], },
end
lemma indicator_ae_eq_of_ae_eq_set (hst : s =ᵐ[μ] t) : s.indicator f =ᵐ[μ] t.indicator f :=
piecewise_ae_eq_of_ae_eq_set hst
lemma indicator_meas_zero (hs : μ s = 0) : indicator s f =ᵐ[μ] 0 :=
(indicator_empty' f) ▸ indicator_ae_eq_of_ae_eq_set (ae_eq_empty.2 hs)
lemma ae_eq_restrict_iff_indicator_ae_eq {g : α → β} (hs : measurable_set s) :
f =ᵐ[μ.restrict s] g ↔ s.indicator f =ᵐ[μ] s.indicator g :=
begin
rw [filter.eventually_eq, ae_restrict_iff' hs],
refine ⟨λ h, _, λ h, _⟩; filter_upwards [h] with x hx,
{ by_cases hxs : x ∈ s,
{ simp [hxs, hx hxs], },
{ simp [hxs], }, },
{ intros hxs,
simpa [hxs] using hx, },
end
end indicator_function
|
1577484e605381c3c5c2e7ecea42dd732466714b | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/data/vector2.lean | 7b8e39e30b694bd06cc03b69d377b803cd886014 | [
"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 | 16,943 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import data.vector
import data.list.nodup
import data.list.of_fn
import control.applicative
/-!
# Additional theorems about the `vector` type
This file introduces the infix notation `::ᵥ` for `vector.cons`.
-/
universes u
variables {n : ℕ}
namespace vector
variables {α : Type*}
infixr `::ᵥ`:67 := vector.cons
attribute [simp] head_cons tail_cons
instance [inhabited α] : inhabited (vector α n) :=
⟨of_fn (λ _, default α)⟩
theorem to_list_injective : function.injective (@to_list α n) :=
subtype.val_injective
/-- Two `v w : vector α n` are equal iff they are equal at every single index. -/
@[ext] theorem ext : ∀ {v w : vector α n}
(h : ∀ m : fin n, vector.nth v m = vector.nth w m), v = w
| ⟨v, hv⟩ ⟨w, hw⟩ h := subtype.eq (list.ext_le (by rw [hv, hw])
(λ m hm hn, h ⟨m, hv ▸ hm⟩))
/-- The empty `vector` is a `subsingleton`. -/
instance zero_subsingleton : subsingleton (vector α 0) :=
⟨λ _ _, vector.ext (λ m, fin.elim0 m)⟩
@[simp] theorem cons_val (a : α) : ∀ (v : vector α n), (a ::ᵥ v).val = a :: v.val
| ⟨_, _⟩ := rfl
@[simp] theorem cons_head (a : α) : ∀ (v : vector α n), (a ::ᵥ v).head = a
| ⟨_, _⟩ := rfl
@[simp] theorem cons_tail (a : α) : ∀ (v : vector α n), (a ::ᵥ v).tail = v
| ⟨_, _⟩ := rfl
@[simp] theorem to_list_of_fn : ∀ {n} (f : fin n → α), to_list (of_fn f) = list.of_fn f
| 0 f := rfl
| (n+1) f := by rw [of_fn, list.of_fn_succ, to_list_cons, to_list_of_fn]
@[simp] theorem mk_to_list :
∀ (v : vector α n) h, (⟨to_list v, h⟩ : vector α n) = v
| ⟨l, h₁⟩ h₂ := rfl
@[simp] lemma to_list_map {β : Type*} (v : vector α n) (f : α → β) : (v.map f).to_list =
v.to_list.map f := by cases v; refl
theorem nth_eq_nth_le : ∀ (v : vector α n) (i),
nth v i = v.to_list.nth_le i.1 (by rw to_list_length; exact i.2)
| ⟨l, h⟩ i := rfl
@[simp] lemma nth_map {β : Type*} (v : vector α n) (f : α → β) (i : fin n) :
(v.map f).nth i = f (v.nth i) :=
by simp [nth_eq_nth_le]
@[simp] theorem nth_of_fn {n} (f : fin n → α) (i) : nth (of_fn f) i = f i :=
by rw [nth_eq_nth_le, ← list.nth_le_of_fn f];
congr; apply to_list_of_fn
@[simp] theorem of_fn_nth (v : vector α n) : of_fn (nth v) = v :=
begin
rcases v with ⟨l, rfl⟩,
apply to_list_injective,
change nth ⟨l, eq.refl _⟩ with λ i, nth ⟨l, rfl⟩ i,
simpa only [to_list_of_fn] using list.of_fn_nth_le _
end
@[simp] theorem nth_tail : ∀ (v : vector α n.succ) (i : fin n),
nth (tail v) i = nth v i.succ
| ⟨a::l, e⟩ ⟨i, h⟩ := by simp [nth_eq_nth_le]; refl
@[simp] theorem tail_val : ∀ (v : vector α n.succ), v.tail.val = v.val.tail
| ⟨a::l, e⟩ := rfl
/-- The `tail` of a `nil` vector is `nil`. -/
@[simp] lemma tail_nil : (@nil α).tail = nil := rfl
/-- The `tail` of a vector made up of one element is `nil`. -/
@[simp] lemma singleton_tail (v : vector α 1) : v.tail = vector.nil :=
by simp only [←cons_head_tail, eq_iff_true_of_subsingleton]
@[simp] theorem tail_of_fn {n : ℕ} (f : fin n.succ → α) :
tail (of_fn f) = of_fn (λ i, f i.succ) :=
(of_fn_nth _).symm.trans $ by congr; funext i; simp
/-- The list that makes up a `vector` made up of a single element,
retrieved via `to_list`, is equal to the list of that single element. -/
@[simp] lemma to_list_singleton (v : vector α 1) : v.to_list = [v.head] :=
begin
rw ←v.cons_head_tail,
simp only [to_list_cons, to_list_nil, cons_head, eq_self_iff_true,
and_self, singleton_tail]
end
/-- Mapping under `id` does not change a vector. -/
@[simp] lemma map_id {n : ℕ} (v : vector α n) : vector.map id v = v :=
vector.eq _ _ (by simp only [list.map_id, vector.to_list_map])
lemma mem_iff_nth {a : α} {v : vector α n} : a ∈ v.to_list ↔ ∃ i, v.nth i = a :=
by simp only [list.mem_iff_nth_le, fin.exists_iff, vector.nth_eq_nth_le];
exact ⟨λ ⟨i, hi, h⟩, ⟨i, by rwa to_list_length at hi, h⟩,
λ ⟨i, hi, h⟩, ⟨i, by rwa to_list_length, h⟩⟩
lemma nodup_iff_nth_inj {v : vector α n} : v.to_list.nodup ↔ function.injective v.nth :=
begin
cases v with l hl,
subst hl,
simp only [list.nodup_iff_nth_le_inj],
split,
{ intros h i j hij,
cases i, cases j, simp [nth_eq_nth_le] at *, tauto },
{ intros h i j hi hj hij,
have := @h ⟨i, hi⟩ ⟨j, hj⟩, simp [nth_eq_nth_le] at *, tauto }
end
@[simp] lemma nth_mem (i : fin n) (v : vector α n) : v.nth i ∈ v.to_list :=
by rw [nth_eq_nth_le]; exact list.nth_le_mem _ _ _
theorem head'_to_list : ∀ (v : vector α n.succ),
(to_list v).head' = some (head v)
| ⟨a::l, e⟩ := rfl
def reverse (v : vector α n) : vector α n :=
⟨v.to_list.reverse, by simp⟩
/-- The `list` of a vector after a `reverse`, retrieved by `to_list` is equal
to the `list.reverse` after retrieving a vector's `to_list`. -/
lemma to_list_reverse {v : vector α n} : v.reverse.to_list = v.to_list.reverse := rfl
@[simp] theorem nth_zero : ∀ (v : vector α n.succ), nth v 0 = head v
| ⟨a::l, e⟩ := rfl
@[simp] theorem head_of_fn
{n : ℕ} (f : fin n.succ → α) : head (of_fn f) = f 0 :=
by rw [← nth_zero, nth_of_fn]
@[simp] theorem nth_cons_zero
(a : α) (v : vector α n) : nth (a ::ᵥ v) 0 = a :=
by simp [nth_zero]
/-- Accessing the `nth` element of a vector made up
of one element `x : α` is `x` itself. -/
@[simp] lemma nth_cons_nil {ix : fin 1}
(x : α) : nth (x ::ᵥ nil) ix = x :=
by convert nth_cons_zero x nil
@[simp] theorem nth_cons_succ
(a : α) (v : vector α n) (i : fin n) : nth (a ::ᵥ v) i.succ = nth v i :=
by rw [← nth_tail, tail_cons]
/-- The last element of a `vector`, given that the vector is at least one element. -/
def last (v : vector α (n + 1)) : α := v.nth (fin.last n)
/-- The last element of a `vector`, given that the vector is at least one element. -/
lemma last_def {v : vector α (n + 1)} : v.last = v.nth (fin.last n) := rfl
/-- The `last` element of a vector is the `head` of the `reverse` vector. -/
lemma reverse_nth_zero {v : vector α (n + 1)} : v.reverse.head = v.last :=
begin
have : 0 = v.to_list.length - 1 - n,
{ simp only [nat.add_succ_sub_one, add_zero, to_list_length, nat.sub_self,
list.length_reverse] },
rw [←nth_zero, last_def, nth_eq_nth_le, nth_eq_nth_le],
simp_rw [to_list_reverse, fin.val_eq_coe, fin.coe_last, fin.coe_zero, this],
rw list.nth_le_reverse,
end
section scan
variables {β : Type*}
variables (f : β → α → β) (b : β)
variables (v : vector α n)
/--
Construct a `vector β (n + 1)` from a `vector α n` by scanning `f : β → α → β`
from the "left", that is, from 0 to `fin.last n`, using `b : β` as the starting value.
-/
def scanl : vector β (n + 1) :=
⟨list.scanl f b v.to_list, by rw [list.length_scanl, to_list_length]⟩
/-- Providing an empty vector to `scanl` gives the starting value `b : β`. -/
@[simp] lemma scanl_nil : scanl f b nil = b ::ᵥ nil := rfl
/--
The recursive step of `scanl` splits a vector `x ::ᵥ v : vector α (n + 1)`
into the provided starting value `b : β` and the recursed `scanl`
`f b x : β` as the starting value.
This lemma is the `cons` version of `scanl_nth`.
-/
@[simp] lemma scanl_cons (x : α) : scanl f b (x ::ᵥ v) = b ::ᵥ scanl f (f b x) v :=
by simpa only [scanl, to_list_cons]
/--
The underlying `list` of a `vector` after a `scanl` is the `list.scanl`
of the underlying `list` of the original `vector`.
-/
@[simp] lemma scanl_val : ∀ {v : vector α n}, (scanl f b v).val = list.scanl f b v.val
| ⟨l, hl⟩ := rfl
/--
The `to_list` of a `vector` after a `scanl` is the `list.scanl`
of the `to_list` of the original `vector`.
-/
@[simp] lemma to_list_scanl : (scanl f b v).to_list = list.scanl f b v.to_list := rfl
/--
The recursive step of `scanl` splits a vector made up of a single element
`x ::ᵥ nil : vector α 1` into a `vector` of the provided starting value `b : β`
and the mapped `f b x : β` as the last value.
-/
@[simp] lemma scanl_singleton (v : vector α 1) : scanl f b v = b ::ᵥ f b v.head ::ᵥ nil :=
begin
rw [←cons_head_tail v],
simp only [scanl_cons, scanl_nil, cons_head, singleton_tail]
end
/--
The first element of `scanl` of a vector `v : vector α n`,
retrieved via `head`, is the starting value `b : β`.
-/
@[simp] lemma scanl_head : (scanl f b v).head = b :=
begin
cases n,
{ have : v = nil := by simp only [eq_iff_true_of_subsingleton],
simp only [this, scanl_nil, cons_head] },
{ rw ←cons_head_tail v,
simp only [←nth_zero, nth_eq_nth_le, to_list_scanl,
to_list_cons, list.scanl, fin.val_zero', list.nth_le] }
end
/--
For an index `i : fin n`, the `nth` element of `scanl` of a
vector `v : vector α n` at `i.succ`, is equal to the application
function `f : β → α → β` of the `i.cast_succ` element of
`scanl f b v` and `nth v i`.
This lemma is the `nth` version of `scanl_cons`.
-/
@[simp] lemma scanl_nth (i : fin n) :
(scanl f b v).nth i.succ = f ((scanl f b v).nth i.cast_succ) (v.nth i) :=
begin
cases n,
{ exact fin_zero_elim i },
induction n with n hn generalizing b,
{ have i0 : i = 0 := by simp only [eq_iff_true_of_subsingleton],
simpa only [scanl_singleton, i0, nth_zero] },
{ rw [←cons_head_tail v, scanl_cons, nth_cons_succ],
refine fin.cases _ _ i,
{ simp only [nth_zero, scanl_head, fin.cast_succ_zero, cons_head] },
{ intro i',
simp only [hn, fin.cast_succ_fin_succ, nth_cons_succ] } }
end
end scan
def m_of_fn {m} [monad m] {α : Type u} : ∀ {n}, (fin n → m α) → m (vector α n)
| 0 f := pure nil
| (n+1) f := do a ← f 0, v ← m_of_fn (λi, f i.succ), pure (a ::ᵥ v)
theorem m_of_fn_pure {m} [monad m] [is_lawful_monad m] {α} :
∀ {n} (f : fin n → α), @m_of_fn m _ _ _ (λ i, pure (f i)) = pure (of_fn f)
| 0 f := rfl
| (n+1) f := by simp [m_of_fn, @m_of_fn_pure n, of_fn]
def mmap {m} [monad m] {α} {β : Type u} (f : α → m β) :
∀ {n}, vector α n → m (vector β n)
| _ ⟨[], rfl⟩ := pure nil
| _ ⟨a::l, rfl⟩ := do h' ← f a, t' ← mmap ⟨l, rfl⟩, pure (h' ::ᵥ t')
@[simp] theorem mmap_nil {m} [monad m] {α β} (f : α → m β) :
mmap f nil = pure nil := rfl
@[simp] theorem mmap_cons {m} [monad m] {α β} (f : α → m β) (a) :
∀ {n} (v : vector α n), mmap f (a ::ᵥ v) =
do h' ← f a, t' ← mmap f v, pure (h' ::ᵥ t')
| _ ⟨l, rfl⟩ := rfl
/-- Define `C v` by induction on `v : vector α (n + 1)`, a vector of
at least one element.
This function has two arguments: `h0` handles the base case on `C nil`,
and `hs` defines the inductive step using `∀ x : α, C v → C (x ::ᵥ v)`. -/
@[elab_as_eliminator] def induction_on
{α : Type*} {n : ℕ}
{C : Π {n : ℕ}, vector α n → Sort*}
(v : vector α (n + 1))
(h0 : C nil)
(hs : ∀ {n : ℕ} {x : α} {w : vector α n}, C w → C (x ::ᵥ w)) :
C v :=
begin
induction n with n hn,
{ rw ←v.cons_head_tail,
convert hs h0 },
{ rw ←v.cons_head_tail,
apply hs,
apply hn }
end
def to_array : vector α n → array n α
| ⟨xs, h⟩ := cast (by rw h) xs.to_array
section insert_nth
variable {a : α}
def insert_nth (a : α) (i : fin (n+1)) (v : vector α n) : vector α (n+1) :=
⟨v.1.insert_nth i a,
begin
rw [list.length_insert_nth, v.2],
rw [v.2, ← nat.succ_le_succ_iff],
exact i.2
end⟩
lemma insert_nth_val {i : fin (n+1)} {v : vector α n} :
(v.insert_nth a i).val = v.val.insert_nth i.1 a :=
rfl
@[simp] lemma remove_nth_val {i : fin n} :
∀{v : vector α n}, (remove_nth i v).val = v.val.remove_nth i
| ⟨l, hl⟩ := rfl
lemma remove_nth_insert_nth {v : vector α n} {i : fin (n+1)} : remove_nth i (insert_nth a i v) = v :=
subtype.eq $ list.remove_nth_insert_nth i.1 v.1
lemma remove_nth_insert_nth_ne {v : vector α (n+1)} :
∀{i j : fin (n+2)} (h : i ≠ j),
remove_nth i (insert_nth a j v) = insert_nth a (i.pred_above j h.symm) (remove_nth (j.pred_above i h) v)
| ⟨i, hi⟩ ⟨j, hj⟩ ne :=
begin
have : i ≠ j := fin.vne_of_ne ne,
refine subtype.eq _,
dsimp [insert_nth, remove_nth, fin.pred_above, fin.cast_lt, -subtype.val_eq_coe],
rcases lt_trichotomy i j with h | h | h,
{ have h_nji : ¬ j < i := lt_asymm h,
have j_pos : 0 < j := lt_of_le_of_lt (zero_le i) h,
rw [dif_neg], swap, { exact h_nji },
rw [dif_pos], swap, { exact h },
rw [fin.coe_pred, fin.coe_mk, remove_nth_val, fin.coe_mk],
rw [list.insert_nth_remove_nth_of_ge, nat.sub_add_cancel j_pos],
{ rw [v.2], exact lt_of_lt_of_le h (nat.le_of_succ_le_succ hj) },
{ exact nat.le_sub_right_of_add_le h } },
{ exact (this h).elim },
{ have h_nij : ¬ i < j := lt_asymm h,
have i_pos : 0 < i := lt_of_le_of_lt (zero_le j) h,
rw [dif_pos], swap, { exact h },
rw [dif_neg], swap, { exact h_nij },
rw [fin.coe_mk, remove_nth_val, fin.coe_pred, fin.coe_mk],
rw [list.insert_nth_remove_nth_of_le, nat.sub_add_cancel i_pos],
{ show i - 1 + 1 ≤ v.val.length,
rw [v.2, nat.sub_add_cancel i_pos],
exact nat.le_of_lt_succ hi },
{ exact nat.le_sub_right_of_add_le h } }
end
lemma insert_nth_comm (a b : α) (i j : fin (n+1)) (h : i ≤ j) :
∀(v : vector α n), (v.insert_nth a i).insert_nth b j.succ = (v.insert_nth b j).insert_nth a i.cast_succ
| ⟨l, hl⟩ :=
begin
refine subtype.eq _,
simp only [insert_nth_val, fin.coe_succ, fin.cast_succ, fin.val_eq_coe, fin.coe_cast_add],
apply list.insert_nth_comm,
{ assumption },
{ rw hl, exact nat.le_of_succ_le_succ j.2 }
end
end insert_nth
section update_nth
/-- `update_nth v n a` replaces the `n`th element of `v` with `a` -/
def update_nth (v : vector α n) (i : fin n) (a : α) : vector α n :=
⟨v.1.update_nth i.1 a, by rw [list.update_nth_length, v.2]⟩
@[simp] lemma nth_update_nth_same (v : vector α n) (i : fin n) (a : α) :
(v.update_nth i a).nth i = a :=
by cases v; cases i; simp [vector.update_nth, vector.nth_eq_nth_le]
lemma nth_update_nth_of_ne {v : vector α n} {i j : fin n} (h : i ≠ j) (a : α) :
(v.update_nth i a).nth j = v.nth j :=
by cases v; cases i; cases j; simp [vector.update_nth, vector.nth_eq_nth_le,
list.nth_le_update_nth_of_ne (fin.vne_of_ne h)]
lemma nth_update_nth_eq_if {v : vector α n} {i j : fin n} (a : α) :
(v.update_nth i a).nth j = if i = j then a else v.nth j :=
by split_ifs; try {simp *}; try {rw nth_update_nth_of_ne}; assumption
end update_nth
end vector
namespace vector
section traverse
variables {F G : Type u → Type u}
variables [applicative F] [applicative G]
open applicative functor
open list (cons) nat
private def traverse_aux {α β : Type u} (f : α → F β) :
Π (x : list α), F (vector β x.length)
| [] := pure vector.nil
| (x::xs) := vector.cons <$> f x <*> traverse_aux xs
protected def traverse {α β : Type u} (f : α → F β) : vector α n → F (vector β n)
| ⟨v, Hv⟩ := cast (by rw Hv) $ traverse_aux f v
variables [is_lawful_applicative F] [is_lawful_applicative G]
variables {α β γ : Type u}
@[simp] protected lemma traverse_def
(f : α → F β) (x : α) : ∀ (xs : vector α n),
(x ::ᵥ xs).traverse f = cons <$> f x <*> xs.traverse f :=
by rintro ⟨xs, rfl⟩; refl
protected lemma id_traverse : ∀ (x : vector α n), x.traverse id.mk = x :=
begin
rintro ⟨x, rfl⟩, dsimp [vector.traverse, cast],
induction x with x xs IH, {refl},
simp! [IH], refl
end
open function
protected lemma comp_traverse (f : β → F γ) (g : α → G β) : ∀ (x : vector α n),
vector.traverse (comp.mk ∘ functor.map f ∘ g) x =
comp.mk (vector.traverse f <$> vector.traverse g x) :=
by rintro ⟨x, rfl⟩; dsimp [vector.traverse, cast];
induction x with x xs; simp! [cast, *] with functor_norm;
[refl, simp [(∘)]]
protected lemma traverse_eq_map_id {α β} (f : α → β) : ∀ (x : vector α n),
x.traverse (id.mk ∘ f) = id.mk (map f x) :=
by rintro ⟨x, rfl⟩; simp!;
induction x; simp! * with functor_norm; refl
variable (η : applicative_transformation F G)
protected lemma naturality {α β : Type*}
(f : α → F β) : ∀ (x : vector α n),
η (x.traverse f) = x.traverse (@η _ ∘ f) :=
by rintro ⟨x, rfl⟩; simp! [cast];
induction x with x xs IH; simp! * with functor_norm
end traverse
instance : traversable.{u} (flip vector n) :=
{ traverse := @vector.traverse n,
map := λ α β, @vector.map.{u u} α β n }
instance : is_lawful_traversable.{u} (flip vector n) :=
{ id_traverse := @vector.id_traverse n,
comp_traverse := @vector.comp_traverse n,
traverse_eq_map_id := @vector.traverse_eq_map_id n,
naturality := @vector.naturality n,
id_map := by intros; cases x; simp! [(<$>)],
comp_map := by intros; cases x; simp! [(<$>)] }
end vector
|
4bf6ecb7967438d3fed26176d3d87010f9f005b6 | dc253be9829b840f15d96d986e0c13520b085033 | /colimit/sequence.hlean | 8baf9e6cceba1624840ede75baebdb6438ce3a95 | [
"Apache-2.0"
] | permissive | cmu-phil/Spectral | 4ce68e5c1ef2a812ffda5260e9f09f41b85ae0ea | 3b078f5f1de251637decf04bd3fc8aa01930a6b3 | refs/heads/master | 1,685,119,195,535 | 1,684,169,772,000 | 1,684,169,772,000 | 46,450,197 | 42 | 13 | null | 1,505,516,767,000 | 1,447,883,921,000 | Lean | UTF-8 | Lean | false | false | 9,492 | hlean | /-
Copyright (c) 2015 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn, Egbert Rijke
-/
import ..move_to_lib types.fin types.trunc
open nat eq equiv sigma sigma.ops is_equiv is_trunc trunc prod fiber function is_conn
namespace seq_colim
definition seq_diagram [reducible] (A : ℕ → Type) : Type := Π⦃n⦄, A n → A (succ n)
structure Seq_diagram : Type :=
(carrier : ℕ → Type)
(struct : seq_diagram carrier)
definition is_equiseq [reducible] {A : ℕ → Type} (f : seq_diagram A) : Type :=
forall (n : ℕ), is_equiv (@f n)
structure Equi_seq : Type :=
(carrier : ℕ → Type)
(maps : seq_diagram carrier)
(prop : is_equiseq maps)
protected abbreviation Mk [constructor] := Seq_diagram.mk
attribute Seq_diagram.carrier [coercion]
attribute Seq_diagram.struct [coercion]
variables {A A' : ℕ → Type} (f : seq_diagram A) (f' : seq_diagram A') {n m k : ℕ}
include f
definition lrep {n m : ℕ} (H : n ≤ m) : A n → A m :=
begin
induction H with m H fs,
{ exact id },
{ exact @f m ∘ fs }
end
definition lrep_irrel_pathover {n m m' : ℕ} (H₁ : n ≤ m) (H₂ : n ≤ m') (p : m = m') (a : A n) :
lrep f H₁ a =[p] lrep f H₂ a :=
apo (λm H, lrep f H a) !is_prop.elimo
definition lrep_irrel {n m : ℕ} (H₁ H₂ : n ≤ m) (a : A n) : lrep f H₁ a = lrep f H₂ a :=
ap (λH, lrep f H a) !is_prop.elim
definition lrep_eq_transport {n m : ℕ} (H : n ≤ m) (p : n = m) (a : A n) : lrep f H a = transport A p a :=
begin induction p, exact lrep_irrel f H (nat.le_refl n) a end
definition lrep_irrel2 {n m : ℕ} (H₁ H₂ : n ≤ m) (a : A n) :
lrep_irrel f (le.step H₁) (le.step H₂) a = ap (@f m) (lrep_irrel f H₁ H₂ a) :=
begin
have H₁ = H₂, from !is_prop.elim, induction this,
refine ap02 _ !is_prop_elim_self ⬝ _ ⬝ ap02 _(ap02 _ !is_prop_elim_self⁻¹),
reflexivity
end
definition lrep_eq_lrep_irrel {n m m' : ℕ} (H₁ : n ≤ m) (H₂ : n ≤ m') (a₁ a₂ : A n) (p : m = m') :
(lrep f H₁ a₁ = lrep f H₁ a₂) ≃ (lrep f H₂ a₁ = lrep f H₂ a₂) :=
equiv_apd011 (λm H, lrep f H a₁ = lrep f H a₂) (is_prop.elimo p H₁ H₂)
definition lrep_eq_lrep_irrel_natural {n m m' : ℕ} {H₁ : n ≤ m} (H₂ : n ≤ m') {a₁ a₂ : A n}
(p : m = m') (q : lrep f H₁ a₁ = lrep f H₁ a₂) :
lrep_eq_lrep_irrel f (le.step H₁) (le.step H₂) a₁ a₂ (ap succ p) (ap (@f m) q) =
ap (@f m') (lrep_eq_lrep_irrel f H₁ H₂ a₁ a₂ p q) :=
begin
esimp [lrep_eq_lrep_irrel],
symmetry,
refine fn_tro_eq_tro_fn2 _ (λa₁ a₂, ap (@f _)) q ⬝ _,
refine ap (λx, x ▸o _) (@is_prop.elim _ _ _ _),
apply is_trunc_pathover
end
definition is_equiv_lrep [constructor] [Hf : is_equiseq f] {n m : ℕ} (H : n ≤ m) :
is_equiv (lrep f H) :=
begin
induction H with m H Hlrepf,
{ apply is_equiv_id },
{ exact is_equiv_compose (@f _) (lrep f H) _ _ },
end
local attribute is_equiv_lrep [instance]
definition lrep_back [reducible] [Hf : is_equiseq f] {n m : ℕ} (H : n ≤ m) : A m → A n :=
(lrep f H)⁻¹ᶠ
section generalized_lrep
/- lreplace le_of_succ_le with this -/
definition lrep_f {n m : ℕ} (H : succ n ≤ m) (a : A n) :
lrep f H (f a) = lrep f (le_of_succ_le H) a :=
begin
induction H with m H p,
{ reflexivity },
{ exact ap (@f m) p }
end
definition lrep_lrep {n m k : ℕ} (H1 : n ≤ m) (H2 : m ≤ k) (a : A n) :
lrep f H2 (lrep f H1 a) = lrep f (nat.le_trans H1 H2) a :=
begin
induction H2 with k H2 p,
{ reflexivity },
{ exact ap (@f k) p }
end
definition f_lrep {n m : ℕ} (H : n ≤ m) (a : A n) : f (lrep f H a) = lrep f (le.step H) a := idp
definition rep (m : ℕ) (a : A n) : A (n + m) :=
lrep f (le_add_right n m) a
definition rep0 (m : ℕ) (a : A 0) : A m :=
lrep f (zero_le m) a
definition rep_pathover_rep0 {n : ℕ} (a : A 0) : rep f n a =[nat.zero_add n] rep0 f n a :=
!lrep_irrel_pathover
definition rep_f (k : ℕ) (a : A n) :
pathover A (rep f k (f a)) (succ_add n k) (rep f (succ k) a) :=
begin
induction k with k IH,
{ constructor },
{ unfold [succ_add], apply pathover_ap, exact apo f IH}
end
definition rep_rep (k l : ℕ) (a : A n) :
pathover A (rep f k (rep f l a)) (nat.add_assoc n l k) (rep f (l + k) a) :=
begin
induction k with k IH,
{ constructor},
{ apply pathover_ap, exact apo f IH}
end
variables {f f'}
definition is_trunc_fun_lrep (k : ℕ₋₂) (H : n ≤ m) (H2 : Πn, is_trunc_fun k (@f n)) :
is_trunc_fun k (lrep f H) :=
begin induction H with m H IH, apply is_trunc_fun_id, exact is_trunc_fun_compose k (H2 m) IH end
definition is_conn_fun_lrep (k : ℕ₋₂) (H : n ≤ m) (H2 : Πn, is_conn_fun k (@f n)) :
is_conn_fun k (lrep f H) :=
begin induction H with m H IH, apply is_conn_fun_id, exact is_conn_fun_compose k (H2 m) IH end
definition lrep_natural (τ : Π⦃n⦄, A n → A' n) (p : Π⦃n⦄ (a : A n), τ (f a) = f' (τ a))
{n m : ℕ} (H : n ≤ m) (a : A n) : τ (lrep f H a) = lrep f' H (τ a) :=
begin
induction H with m H IH, reflexivity, exact p (lrep f H a) ⬝ ap (@f' m) IH
end
definition rep_natural (τ : Π⦃n⦄, A n → A' n) (p : Π⦃n⦄ (a : A n), τ (f a) = f' (τ a))
{n : ℕ} (k : ℕ) (a : A n) : τ (rep f k a) = rep f' k (τ a) :=
lrep_natural τ p _ a
definition rep0_natural (τ : Π⦃n⦄, A n → A' n) (p : Π⦃n⦄ (a : A n), τ (f a) = f' (τ a))
(k : ℕ) (a : A 0) : τ (rep0 f k a) = rep0 f' k (τ a) :=
lrep_natural τ p _ a
variables (f f')
end generalized_lrep
section shift
definition shift_diag [unfold_full] : seq_diagram (λn, A (succ n)) :=
λn a, f a
definition kshift_diag [unfold_full] (k : ℕ) : seq_diagram (λn, A (k + n)) :=
λn a, f a
definition kshift_diag' [unfold_full] (k : ℕ) : seq_diagram (λn, A (n + k)) :=
λn a, transport A (succ_add n k)⁻¹ (f a)
definition lrep_kshift_diag {n m k : ℕ} (H : m ≤ k) (a : A (n + m)) :
lrep (kshift_diag f n) H a = lrep f (nat.add_le_add_left2 H n) a :=
by induction H with k H p; reflexivity; exact ap (@f _) p
end shift
section constructions
omit f
definition constant_seq (X : Type) : seq_diagram (λ n, X) :=
λ n x, x
definition seq_diagram_arrow_left [unfold_full] (X : Type) : seq_diagram (λn, X → A n) :=
λn g x, f (g x)
definition seq_diagram_prod [unfold_full] : seq_diagram (λn, A n × A' n) :=
λn, prod_functor (@f n) (@f' n)
open fin
definition seq_diagram_fin [unfold_full] : seq_diagram fin :=
lift_succ
definition id0_seq [unfold_full] (a₁ a₂ : A 0) : ℕ → Type :=
λ k, rep0 f k a₁ = rep0 f k a₂
definition id0_seq_diagram [unfold_full] (a₁ a₂ : A 0) : seq_diagram (id0_seq f a₁ a₂) :=
λ (k : ℕ) (p : rep0 f k a₁ = rep0 f k a₂), ap (@f k) p
definition id_seq [unfold_full] (n : ℕ) (a₁ a₂ : A n) : ℕ → Type :=
λ k, rep f k a₁ = rep f k a₂
definition id_seq_diagram [unfold_full] (n : ℕ) (a₁ a₂ : A n) : seq_diagram (id_seq f n a₁ a₂) :=
λ (k : ℕ) (p : rep f k a₁ = rep f k a₂), ap (@f (n + k)) p
definition trunc_diagram [unfold_full] (k : ℕ₋₂) (f : seq_diagram A) :
seq_diagram (λn, trunc k (A n)) :=
λn, trunc_functor k (@f n)
end constructions
section over
variable {A}
variable (P : Π⦃n⦄, A n → Type)
definition seq_diagram_over : Type := Π⦃n⦄ {a : A n}, P a → P (f a)
definition weakened_sequence [unfold_full] : seq_diagram_over f (λn a, A' n) :=
λn a a', f' a'
definition id0_seq_diagram_over [unfold_full] (a₀ : A 0) :
seq_diagram_over f (λn a, rep0 f n a₀ = a) :=
λn a p, ap (@f n) p
variable (g : seq_diagram_over f P)
variables {f P}
definition seq_diagram_of_over [unfold_full] {n : ℕ} (a : A n) :
seq_diagram (λk, P (rep f k a)) :=
λk p, g p
definition seq_diagram_sigma [unfold 6] : seq_diagram (λn, Σ(x : A n), P x) :=
λn v, ⟨f v.1, g v.2⟩
variables (f P)
theorem rep_f_equiv [constructor] (a : A n) (k : ℕ) :
P (lrep f (le_add_right (succ n) k) (f a)) ≃ P (lrep f (le_add_right n (succ k)) a) :=
equiv_apd011 P (rep_f f k a)
theorem rep_rep_equiv [constructor] (a : A n) (k l : ℕ) :
P (rep f (l + k) a) ≃ P (rep f k (rep f l a)) :=
(equiv_apd011 P (rep_rep f k l a))⁻¹ᵉ
end over
omit f
definition seq_diagram_pi {X : Type} {A : X → ℕ → Type} (g : Π⦃x n⦄, A x n → A x (succ n)) :
seq_diagram (λn, Πx, A x n) :=
λn f x, g (f x)
variables {f f'}
definition seq_diagram_over_fiber (g : Π⦃n⦄, A' n → A n)
(p : Π⦃n⦄ (a : A' n), g (f' a) = f (g a)) : seq_diagram_over f (λn, fiber (@g n)) :=
λk a, fiber_functor (@f' k) (@f k) (@p k) idp
definition seq_diagram_fiber (g : Π⦃n⦄, A' n → A n) (p : Π⦃n⦄ (a : A' n), g (f' a) = f (g a))
{n : ℕ} (a : A n) : seq_diagram (λk, fiber (@g (n + k)) (rep f k a)) :=
seq_diagram_of_over (seq_diagram_over_fiber g p) a
definition seq_diagram_fiber0 (g : Π⦃n⦄, A' n → A n) (p : Π⦃n⦄ (a : A' n), g (f' a) = f (g a))
(a : A 0) : seq_diagram (λk, fiber (@g k) (rep0 f k a)) :=
λk, fiber_functor (@f' k) (@f k) (@p k) idp
end seq_colim
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.