path
stringlengths
11
71
content
stringlengths
75
124k
Control\Bitraversable\Lemmas.lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import Mathlib.Control.Bitraversable.Basic /-! # Bitraversable Lemmas ## Main definitions * tfst - traverse on first functor argument * tsnd - traverse on second functor argument ## Lemmas Combination of * bitraverse * tfst * tsnd with the applicatives `id` and `comp` ## References * Hackage: <https://hackage.haskell.org/package/base-4.12.0.0/docs/Data-Bitraversable.html> ## Tags traversable bitraversable functor bifunctor applicative -/ universe u variable {t : Type u → Type u → Type u} [Bitraversable t] variable {β : Type u} namespace Bitraversable open Functor LawfulApplicative variable {F G : Type u → Type u} [Applicative F] [Applicative G] /-- traverse on the first functor argument -/ abbrev tfst {α α'} (f : α → F α') : t α β → F (t α' β) := bitraverse f pure /-- traverse on the second functor argument -/ abbrev tsnd {α α'} (f : α → F α') : t β α → F (t β α') := bitraverse pure f variable [LawfulBitraversable t] [LawfulApplicative F] [LawfulApplicative G] @[higher_order tfst_id] theorem id_tfst : ∀ {α β} (x : t α β), tfst (F := Id) pure x = pure x := id_bitraverse @[higher_order tsnd_id] theorem id_tsnd : ∀ {α β} (x : t α β), tsnd (F := Id) pure x = pure x := id_bitraverse @[higher_order tfst_comp_tfst] theorem comp_tfst {α₀ α₁ α₂ β} (f : α₀ → F α₁) (f' : α₁ → G α₂) (x : t α₀ β) : Comp.mk (tfst f' <$> tfst f x) = tfst (Comp.mk ∘ map f' ∘ f) x := by rw [← comp_bitraverse] simp only [Function.comp, tfst, map_pure, Pure.pure] @[higher_order tfst_comp_tsnd] theorem tfst_tsnd {α₀ α₁ β₀ β₁} (f : α₀ → F α₁) (f' : β₀ → G β₁) (x : t α₀ β₀) : Comp.mk (tfst f <$> tsnd f' x) = bitraverse (Comp.mk ∘ pure ∘ f) (Comp.mk ∘ map pure ∘ f') x := by rw [← comp_bitraverse] simp only [Function.comp, map_pure] @[higher_order tsnd_comp_tfst] theorem tsnd_tfst {α₀ α₁ β₀ β₁} (f : α₀ → F α₁) (f' : β₀ → G β₁) (x : t α₀ β₀) : Comp.mk (tsnd f' <$> tfst f x) = bitraverse (Comp.mk ∘ map pure ∘ f) (Comp.mk ∘ pure ∘ f') x := by rw [← comp_bitraverse] simp only [Function.comp, map_pure] @[higher_order tsnd_comp_tsnd] theorem comp_tsnd {α β₀ β₁ β₂} (g : β₀ → F β₁) (g' : β₁ → G β₂) (x : t α β₀) : Comp.mk (tsnd g' <$> tsnd g x) = tsnd (Comp.mk ∘ map g' ∘ g) x := by rw [← comp_bitraverse] simp only [Function.comp, map_pure] rfl open Bifunctor -- Porting note: This private theorem wasn't needed -- private theorem pure_eq_id_mk_comp_id {α} : pure = id.mk ∘ @id α := rfl open Function @[higher_order] theorem tfst_eq_fst_id {α α' β} (f : α → α') (x : t α β) : tfst (F := Id) (pure ∘ f) x = pure (fst f x) := by apply bitraverse_eq_bimap_id @[higher_order] theorem tsnd_eq_snd_id {α β β'} (f : β → β') (x : t α β) : tsnd (F := Id) (pure ∘ f) x = pure (snd f x) := by apply bitraverse_eq_bimap_id attribute [functor_norm] comp_bitraverse comp_tsnd comp_tfst tsnd_comp_tsnd tsnd_comp_tfst tfst_comp_tsnd tfst_comp_tfst bitraverse_comp bitraverse_id_id tfst_id tsnd_id end Bitraversable
Control\EquivFunctor\Instances.lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import Mathlib.Data.Fintype.Basic import Mathlib.Control.EquivFunctor /-! # `EquivFunctor` instances We derive some `EquivFunctor` instances, to enable `equiv_rw` to rewrite under these functions. -/ open Equiv instance EquivFunctorUnique : EquivFunctor Unique where map e := Equiv.uniqueCongr e map_refl' α := by simp [eq_iff_true_of_subsingleton] map_trans' := by simp [eq_iff_true_of_subsingleton] instance EquivFunctorPerm : EquivFunctor Perm where map e p := (e.symm.trans p).trans e map_refl' α := by ext; simp map_trans' _ _ := by ext; simp -- There is a classical instance of `LawfulFunctor Finset` available, -- but we provide this computable alternative separately. instance EquivFunctorFinset : EquivFunctor Finset where map e s := s.map e.toEmbedding map_refl' α := by ext; simp map_trans' k h := by ext _ a; simp; constructor <;> intro h' · let ⟨a, ha₁, ha₂⟩ := h' rw [← ha₂]; simp; apply ha₁ · exists (Equiv.symm k) ((Equiv.symm h) a) simp [h'] instance EquivFunctorFintype : EquivFunctor Fintype where map e s := Fintype.ofBijective e e.bijective map_refl' α := by ext; simp [eq_iff_true_of_subsingleton] map_trans' := by simp [eq_iff_true_of_subsingleton]
Control\Functor\Multivariate.lean
/- Copyright (c) 2018 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Mario Carneiro, Simon Hudon -/ import Mathlib.Data.Fin.Fin2 import Mathlib.Data.TypeVec import Mathlib.Logic.Equiv.Defs /-! # Functors between the category of tuples of types, and the category Type Features: * `MvFunctor n` : the type class of multivariate functors * `f <$$> x` : notation for map -/ universe u v w open MvFunctor /-- Multivariate functors, i.e. functor between the category of type vectors and the category of Type -/ class MvFunctor {n : ℕ} (F : TypeVec n → Type*) where /-- Multivariate map, if `f : α ⟹ β` and `x : F α` then `f <$$> x : F β`. -/ map : ∀ {α β : TypeVec n}, α ⟹ β → F α → F β /-- Multivariate map, if `f : α ⟹ β` and `x : F α` then `f <$$> x : F β` -/ scoped[MvFunctor] infixr:100 " <$$> " => MvFunctor.map variable {n : ℕ} namespace MvFunctor variable {α β γ : TypeVec.{u} n} {F : TypeVec.{u} n → Type v} [MvFunctor F] /-- predicate lifting over multivariate functors -/ def LiftP {α : TypeVec n} (P : ∀ i, α i → Prop) (x : F α) : Prop := ∃ u : F (fun i => Subtype (P i)), (fun i => @Subtype.val _ (P i)) <$$> u = x /-- relational lifting over multivariate functors -/ def LiftR {α : TypeVec n} (R : ∀ {i}, α i → α i → Prop) (x y : F α) : Prop := ∃ u : F (fun i => { p : α i × α i // R p.fst p.snd }), (fun i (t : { p : α i × α i // R p.fst p.snd }) => t.val.fst) <$$> u = x ∧ (fun i (t : { p : α i × α i // R p.fst p.snd }) => t.val.snd) <$$> u = y /-- given `x : F α` and a projection `i` of type vector `α`, `supp x i` is the set of `α.i` contained in `x` -/ def supp {α : TypeVec n} (x : F α) (i : Fin2 n) : Set (α i) := { y : α i | ∀ ⦃P⦄, LiftP P x → P i y } theorem of_mem_supp {α : TypeVec n} {x : F α} {P : ∀ ⦃i⦄, α i → Prop} (h : LiftP P x) (i : Fin2 n) : ∀ y ∈ supp x i, P y := fun _y hy => hy h end MvFunctor /-- laws for `MvFunctor` -/ class LawfulMvFunctor {n : ℕ} (F : TypeVec n → Type*) [MvFunctor F] : Prop where /-- `map` preserved identities, i.e., maps identity on `α` to identity on `F α` -/ id_map : ∀ {α : TypeVec n} (x : F α), TypeVec.id <$$> x = x /-- `map` preserves compositions -/ comp_map : ∀ {α β γ : TypeVec n} (g : α ⟹ β) (h : β ⟹ γ) (x : F α), (h ⊚ g) <$$> x = h <$$> g <$$> x open Nat TypeVec namespace MvFunctor export LawfulMvFunctor (comp_map) open LawfulMvFunctor variable {α β γ : TypeVec.{u} n} variable {F : TypeVec.{u} n → Type v} [MvFunctor F] variable (P : α ⟹ «repeat» n Prop) (R : α ⊗ α ⟹ «repeat» n Prop) /-- adapt `MvFunctor.LiftP` to accept predicates as arrows -/ def LiftP' : F α → Prop := MvFunctor.LiftP fun i x => ofRepeat <| P i x /-- adapt `MvFunctor.LiftR` to accept relations as arrows -/ def LiftR' : F α → F α → Prop := MvFunctor.LiftR @fun i x y => ofRepeat <| R i <| TypeVec.prod.mk _ x y variable [LawfulMvFunctor F] @[simp] theorem id_map (x : F α) : TypeVec.id <$$> x = x := LawfulMvFunctor.id_map x @[simp] theorem id_map' (x : F α) : (fun _i a => a) <$$> x = x := id_map x theorem map_map (g : α ⟹ β) (h : β ⟹ γ) (x : F α) : h <$$> g <$$> x = (h ⊚ g) <$$> x := Eq.symm <| comp_map _ _ _ section LiftP' variable (F) theorem exists_iff_exists_of_mono {P : F α → Prop} {q : F β → Prop} (f : α ⟹ β) (g : β ⟹ α) (h₀ : f ⊚ g = TypeVec.id) (h₁ : ∀ u : F α, P u ↔ q (f <$$> u)) : (∃ u : F α, P u) ↔ ∃ u : F β, q u := by constructor <;> rintro ⟨u, h₂⟩ · refine ⟨f <$$> u, ?_⟩ apply (h₁ u).mp h₂ · refine ⟨g <$$> u, ?_⟩ rw [h₁] simp only [MvFunctor.map_map, h₀, LawfulMvFunctor.id_map, h₂] variable {F} theorem LiftP_def (x : F α) : LiftP' P x ↔ ∃ u : F (Subtype_ P), subtypeVal P <$$> u = x := exists_iff_exists_of_mono F _ _ (toSubtype_of_subtype P) (by simp [MvFunctor.map_map]) theorem LiftR_def (x y : F α) : LiftR' R x y ↔ ∃ u : F (Subtype_ R), (TypeVec.prod.fst ⊚ subtypeVal R) <$$> u = x ∧ (TypeVec.prod.snd ⊚ subtypeVal R) <$$> u = y := exists_iff_exists_of_mono _ _ _ (toSubtype'_of_subtype' R) (by simp only [map_map, comp_assoc, subtypeVal_toSubtype'] simp (config := { unfoldPartialApp := true }) [comp]) end LiftP' end MvFunctor open Nat namespace MvFunctor open TypeVec section LiftPLastPredIff variable {F : TypeVec.{u} (n + 1) → Type*} [MvFunctor F] [LawfulMvFunctor F] {α : TypeVec.{u} n} open MvFunctor variable {β : Type u} variable (pp : β → Prop) private def f : ∀ n α, (fun i : Fin2 (n + 1) => { p_1 // ofRepeat (PredLast' α pp i p_1) }) ⟹ fun i : Fin2 (n + 1) => { p_1 : (α ::: β) i // PredLast α pp p_1 } | _, α, Fin2.fs i, x => ⟨x.val, cast (by simp only [PredLast]; erw [const_iff_true]) x.property⟩ | _, α, Fin2.fz, x => ⟨x.val, x.property⟩ private def g : ∀ n α, (fun i : Fin2 (n + 1) => { p_1 : (α ::: β) i // PredLast α pp p_1 }) ⟹ fun i : Fin2 (n + 1) => { p_1 // ofRepeat (PredLast' α pp i p_1) } | _, α, Fin2.fs i, x => ⟨x.val, cast (by simp only [PredLast]; erw [const_iff_true]) x.property⟩ | _, α, Fin2.fz, x => ⟨x.val, x.property⟩ theorem LiftP_PredLast_iff {β} (P : β → Prop) (x : F (α ::: β)) : LiftP' (PredLast' _ P) x ↔ LiftP (PredLast _ P) x := by dsimp only [LiftP, LiftP'] apply exists_iff_exists_of_mono F (f _ n α) (g _ n α) · ext i ⟨x, _⟩ cases i <;> rfl · intros rw [MvFunctor.map_map] dsimp (config := { unfoldPartialApp := true }) [(· ⊚ ·)] suffices (fun i => Subtype.val) = (fun i x => (MvFunctor.f P n α i x).val) by rw [this] ext i ⟨x, _⟩ cases i <;> rfl open Function variable (rr : β → β → Prop) private def f' : ∀ n α, (fun i : Fin2 (n + 1) => { p_1 : _ × _ // ofRepeat (RelLast' α rr i (TypeVec.prod.mk _ p_1.fst p_1.snd)) }) ⟹ fun i : Fin2 (n + 1) => { p_1 : (α ::: β) i × _ // RelLast α rr p_1.fst p_1.snd } | _, α, Fin2.fs i, x => ⟨x.val, cast (by simp only [RelLast]; erw [repeatEq_iff_eq]) x.property⟩ | _, α, Fin2.fz, x => ⟨x.val, x.property⟩ private def g' : ∀ n α, (fun i : Fin2 (n + 1) => { p_1 : (α ::: β) i × _ // RelLast α rr p_1.fst p_1.snd }) ⟹ fun i : Fin2 (n + 1) => { p_1 : _ × _ // ofRepeat (RelLast' α rr i (TypeVec.prod.mk _ p_1.1 p_1.2)) } | _, α, Fin2.fs i, x => ⟨x.val, cast (by simp only [RelLast]; erw [repeatEq_iff_eq]) x.property⟩ | _, α, Fin2.fz, x => ⟨x.val, x.property⟩ theorem LiftR_RelLast_iff (x y : F (α ::: β)) : LiftR' (RelLast' _ rr) x y ↔ LiftR (RelLast (i := _) _ rr) x y := by dsimp only [LiftR, LiftR'] apply exists_iff_exists_of_mono F (f' rr _ _) (g' rr _ _) · ext i ⟨x, _⟩ : 2 cases i <;> rfl · intros simp (config := { unfoldPartialApp := true }) only [map_map, TypeVec.comp] -- Porting note: proof was -- rw [MvFunctor.map_map, MvFunctor.map_map, (· ⊚ ·), (· ⊚ ·)] -- congr <;> ext i ⟨x, _⟩ <;> cases i <;> rfl suffices (fun i t => t.val.fst) = ((fun i x => (MvFunctor.f' rr n α i x).val.fst)) ∧ (fun i t => t.val.snd) = ((fun i x => (MvFunctor.f' rr n α i x).val.snd)) by rw [this.1, this.2] constructor <;> ext i ⟨x, _⟩ <;> cases i <;> rfl end LiftPLastPredIff /-- Any type function that is (extensionally) equivalent to a functor, is itself a functor -/ def ofEquiv {F F' : TypeVec.{u} n → Type*} [MvFunctor F'] (eqv : ∀ α, F α ≃ F' α) : MvFunctor F where map f x := (eqv _).symm <| f <$$> eqv _ x end MvFunctor
Control\Monad\Basic.lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import Mathlib.Logic.Equiv.Defs /-! # Monad ## Attributes * ext * functor_norm * monad_norm ## Implementation Details Set of rewrite rules and automation for monads in general and `ReaderT`, `StateT`, `ExceptT` and `OptionT` in particular. The rewrite rules for monads are carefully chosen so that `simp with functor_norm` will not introduce monadic vocabulary in a context where applicatives would do just fine but will handle monadic notation already present in an expression. In a context where monadic reasoning is desired `simp with monad_norm` will translate functor and applicative notation into monad notation and use regular `functor_norm` rules as well. ## Tags functor, applicative, monad, simp -/ universe u v variable {α β σ : Type u} attribute [ext] ReaderT.ext StateT.ext ExceptT.ext @[monad_norm] theorem map_eq_bind_pure_comp (m : Type u → Type v) [Monad m] [LawfulMonad m] (f : α → β) (x : m α) : f <$> x = x >>= pure ∘ f := (bind_pure_comp f x).symm /-- run a `StateT` program and discard the final state -/ def StateT.eval {m : Type u → Type v} [Functor m] (cmd : StateT σ m α) (s : σ) : m α := Prod.fst <$> cmd.run s universe u₀ u₁ v₀ v₁ /-- reduce the equivalence between two state monads to the equivalence between their respective function spaces -/ def StateT.equiv {σ₁ α₁ : Type u₀} {σ₂ α₂ : Type u₁} {m₁ : Type u₀ → Type v₀} {m₂ : Type u₁ → Type v₁} (F : (σ₁ → m₁ (α₁ × σ₁)) ≃ (σ₂ → m₂ (α₂ × σ₂))) : StateT σ₁ m₁ α₁ ≃ StateT σ₂ m₂ α₂ := F /-- reduce the equivalence between two reader monads to the equivalence between their respective function spaces -/ def ReaderT.equiv {ρ₁ α₁ : Type u₀} {ρ₂ α₂ : Type u₁} {m₁ : Type u₀ → Type v₀} {m₂ : Type u₁ → Type v₁} (F : (ρ₁ → m₁ α₁) ≃ (ρ₂ → m₂ α₂)) : ReaderT ρ₁ m₁ α₁ ≃ ReaderT ρ₂ m₂ α₂ := F
Control\Monad\Cont.lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import Mathlib.Control.Monad.Basic import Mathlib.Control.Monad.Writer import Mathlib.Control.Lawful import Batteries.Tactic.Congr /-! # Continuation Monad Monad encapsulating continuation passing programming style, similar to Haskell's `Cont`, `ContT` and `MonadCont`: <http://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Cont.html> -/ universe u v w u₀ u₁ v₀ v₁ structure MonadCont.Label (α : Type w) (m : Type u → Type v) (β : Type u) where apply : α → m β def MonadCont.goto {α β} {m : Type u → Type v} (f : MonadCont.Label α m β) (x : α) := f.apply x class MonadCont (m : Type u → Type v) where callCC : ∀ {α β}, (MonadCont.Label α m β → m α) → m α open MonadCont class LawfulMonadCont (m : Type u → Type v) [Monad m] [MonadCont m] extends LawfulMonad m : Prop where callCC_bind_right {α ω γ} (cmd : m α) (next : Label ω m γ → α → m ω) : (callCC fun f => cmd >>= next f) = cmd >>= fun x => callCC fun f => next f x callCC_bind_left {α} (β) (x : α) (dead : Label α m β → β → m α) : (callCC fun f : Label α m β => goto f x >>= dead f) = pure x callCC_dummy {α β} (dummy : m α) : (callCC fun _ : Label α m β => dummy) = dummy export LawfulMonadCont (callCC_bind_right callCC_bind_left callCC_dummy) def ContT (r : Type u) (m : Type u → Type v) (α : Type w) := (α → m r) → m r abbrev Cont (r : Type u) (α : Type w) := ContT r id α namespace ContT export MonadCont (Label goto) variable {r : Type u} {m : Type u → Type v} {α β γ ω : Type w} def run : ContT r m α → (α → m r) → m r := id def map (f : m r → m r) (x : ContT r m α) : ContT r m α := f ∘ x theorem run_contT_map_contT (f : m r → m r) (x : ContT r m α) : run (map f x) = f ∘ run x := rfl def withContT (f : (β → m r) → α → m r) (x : ContT r m α) : ContT r m β := fun g => x <| f g theorem run_withContT (f : (β → m r) → α → m r) (x : ContT r m α) : run (withContT f x) = run x ∘ f := rfl @[ext] protected theorem ext {x y : ContT r m α} (h : ∀ f, x.run f = y.run f) : x = y := by unfold ContT; ext; apply h instance : Monad (ContT r m) where pure x f := f x bind x f g := x fun i => f i g instance : LawfulMonad (ContT r m) := LawfulMonad.mk' (id_map := by intros; rfl) (pure_bind := by intros; ext; rfl) (bind_assoc := by intros; ext; rfl) def monadLift [Monad m] {α} : m α → ContT r m α := fun x f => x >>= f instance [Monad m] : MonadLift m (ContT r m) where monadLift := ContT.monadLift theorem monadLift_bind [Monad m] [LawfulMonad m] {α β} (x : m α) (f : α → m β) : (monadLift (x >>= f) : ContT r m β) = monadLift x >>= monadLift ∘ f := by ext simp only [monadLift, MonadLift.monadLift, (· ∘ ·), (· >>= ·), bind_assoc, id, run, ContT.monadLift] instance : MonadCont (ContT r m) where callCC f g := f ⟨fun x _ => g x⟩ g instance : LawfulMonadCont (ContT r m) where callCC_bind_right := by intros; ext; rfl callCC_bind_left := by intros; ext; rfl callCC_dummy := by intros; ext; rfl instance (ε) [MonadExcept ε m] : MonadExcept ε (ContT r m) where throw e _ := throw e tryCatch act h f := tryCatch (act f) fun e => h e f end ContT variable {m : Type u → Type v} section variable [Monad m] def ExceptT.mkLabel {α β ε} : Label (Except.{u, u} ε α) m β → Label α (ExceptT ε m) β | ⟨f⟩ => ⟨fun a => monadLift <| f (Except.ok a)⟩ theorem ExceptT.goto_mkLabel {α β ε : Type _} (x : Label (Except.{u, u} ε α) m β) (i : α) : goto (ExceptT.mkLabel x) i = ExceptT.mk (Except.ok <$> goto x (Except.ok i)) := by cases x; rfl nonrec def ExceptT.callCC {ε} [MonadCont m] {α β : Type _} (f : Label α (ExceptT ε m) β → ExceptT ε m α) : ExceptT ε m α := ExceptT.mk (callCC fun x : Label _ m β => ExceptT.run <| f (ExceptT.mkLabel x)) instance {ε} [MonadCont m] : MonadCont (ExceptT ε m) where callCC := ExceptT.callCC instance {ε} [MonadCont m] [LawfulMonadCont m] : LawfulMonadCont (ExceptT ε m) where callCC_bind_right := by intros; simp only [callCC, ExceptT.callCC, ExceptT.run_bind, callCC_bind_right]; ext dsimp congr with ⟨⟩ <;> simp [ExceptT.bindCont, @callCC_dummy m _] callCC_bind_left := by intros simp only [callCC, ExceptT.callCC, ExceptT.goto_mkLabel, map_eq_bind_pure_comp, Function.comp, ExceptT.run_bind, ExceptT.run_mk, bind_assoc, pure_bind, @callCC_bind_left m _] ext; rfl callCC_dummy := by intros; simp only [callCC, ExceptT.callCC, @callCC_dummy m _]; ext; rfl def OptionT.mkLabel {α β} : Label (Option.{u} α) m β → Label α (OptionT m) β | ⟨f⟩ => ⟨fun a => monadLift <| f (some a)⟩ theorem OptionT.goto_mkLabel {α β : Type _} (x : Label (Option.{u} α) m β) (i : α) : goto (OptionT.mkLabel x) i = OptionT.mk (goto x (some i) >>= fun a => pure (some a)) := rfl nonrec def OptionT.callCC [MonadCont m] {α β : Type _} (f : Label α (OptionT m) β → OptionT m α) : OptionT m α := OptionT.mk (callCC fun x : Label _ m β => OptionT.run <| f (OptionT.mkLabel x) : m (Option α)) instance [MonadCont m] : MonadCont (OptionT m) where callCC := OptionT.callCC instance [MonadCont m] [LawfulMonadCont m] : LawfulMonadCont (OptionT m) where callCC_bind_right := by intros; simp only [callCC, OptionT.callCC, OptionT.run_bind, callCC_bind_right]; ext dsimp congr with ⟨⟩ <;> simp [@callCC_dummy m _] callCC_bind_left := by intros simp only [callCC, OptionT.callCC, OptionT.goto_mkLabel, OptionT.run_bind, OptionT.run_mk, bind_assoc, pure_bind, @callCC_bind_left m _] ext; rfl callCC_dummy := by intros; simp only [callCC, OptionT.callCC, @callCC_dummy m _]; ext; rfl /- Porting note: In Lean 3, `One ω` is required for `MonadLift (WriterT ω m)`. In Lean 4, `EmptyCollection ω` or `Monoid ω` is required. So we give definitions for the both instances. -/ def WriterT.mkLabel {α β ω} [EmptyCollection ω] : Label (α × ω) m β → Label α (WriterT ω m) β | ⟨f⟩ => ⟨fun a => monadLift <| f (a, ∅)⟩ def WriterT.mkLabel' {α β ω} [Monoid ω] : Label (α × ω) m β → Label α (WriterT ω m) β | ⟨f⟩ => ⟨fun a => monadLift <| f (a, 1)⟩ theorem WriterT.goto_mkLabel {α β ω : Type _} [EmptyCollection ω] (x : Label (α × ω) m β) (i : α) : goto (WriterT.mkLabel x) i = monadLift (goto x (i, ∅)) := by cases x; rfl theorem WriterT.goto_mkLabel' {α β ω : Type _} [Monoid ω] (x : Label (α × ω) m β) (i : α) : goto (WriterT.mkLabel' x) i = monadLift (goto x (i, 1)) := by cases x; rfl nonrec def WriterT.callCC [MonadCont m] {α β ω : Type _} [EmptyCollection ω] (f : Label α (WriterT ω m) β → WriterT ω m α) : WriterT ω m α := WriterT.mk <| callCC (WriterT.run ∘ f ∘ WriterT.mkLabel : Label (α × ω) m β → m (α × ω)) def WriterT.callCC' [MonadCont m] {α β ω : Type _} [Monoid ω] (f : Label α (WriterT ω m) β → WriterT ω m α) : WriterT ω m α := WriterT.mk <| MonadCont.callCC (WriterT.run ∘ f ∘ WriterT.mkLabel' : Label (α × ω) m β → m (α × ω)) end instance (ω) [Monad m] [EmptyCollection ω] [MonadCont m] : MonadCont (WriterT ω m) where callCC := WriterT.callCC instance (ω) [Monad m] [Monoid ω] [MonadCont m] : MonadCont (WriterT ω m) where callCC := WriterT.callCC' def StateT.mkLabel {α β σ : Type u} : Label (α × σ) m (β × σ) → Label α (StateT σ m) β | ⟨f⟩ => ⟨fun a => StateT.mk (fun s => f (a, s))⟩ theorem StateT.goto_mkLabel {α β σ : Type u} (x : Label (α × σ) m (β × σ)) (i : α) : goto (StateT.mkLabel x) i = StateT.mk (fun s => goto x (i, s)) := by cases x; rfl nonrec def StateT.callCC {σ} [MonadCont m] {α β : Type _} (f : Label α (StateT σ m) β → StateT σ m α) : StateT σ m α := StateT.mk (fun r => callCC fun f' => (f <| StateT.mkLabel f').run r) instance {σ} [MonadCont m] : MonadCont (StateT σ m) where callCC := StateT.callCC instance {σ} [Monad m] [MonadCont m] [LawfulMonadCont m] : LawfulMonadCont (StateT σ m) where callCC_bind_right := by intros simp only [callCC, StateT.callCC, StateT.run_bind, callCC_bind_right]; ext; rfl callCC_bind_left := by intros simp only [callCC, StateT.callCC, StateT.goto_mkLabel, StateT.run_bind, StateT.run_mk, callCC_bind_left]; ext; rfl callCC_dummy := by intros simp only [callCC, StateT.callCC, @callCC_dummy m _] ext; rfl def ReaderT.mkLabel {α β} (ρ) : Label α m β → Label α (ReaderT ρ m) β | ⟨f⟩ => ⟨monadLift ∘ f⟩ theorem ReaderT.goto_mkLabel {α ρ β} (x : Label α m β) (i : α) : goto (ReaderT.mkLabel ρ x) i = monadLift (goto x i) := by cases x; rfl nonrec def ReaderT.callCC {ε} [MonadCont m] {α β : Type _} (f : Label α (ReaderT ε m) β → ReaderT ε m α) : ReaderT ε m α := ReaderT.mk (fun r => callCC fun f' => (f <| ReaderT.mkLabel _ f').run r) instance {ρ} [MonadCont m] : MonadCont (ReaderT ρ m) where callCC := ReaderT.callCC instance {ρ} [Monad m] [MonadCont m] [LawfulMonadCont m] : LawfulMonadCont (ReaderT ρ m) where callCC_bind_right := by intros; simp only [callCC, ReaderT.callCC, ReaderT.run_bind, callCC_bind_right]; ext; rfl callCC_bind_left := by intros; simp only [callCC, ReaderT.callCC, ReaderT.goto_mkLabel, ReaderT.run_bind, ReaderT.run_monadLift, monadLift_self, callCC_bind_left] ext; rfl callCC_dummy := by intros; simp only [callCC, ReaderT.callCC, @callCC_dummy m _]; ext; rfl /-- reduce the equivalence between two continuation passing monads to the equivalence between their underlying monad -/ def ContT.equiv {m₁ : Type u₀ → Type v₀} {m₂ : Type u₁ → Type v₁} {α₁ r₁ : Type u₀} {α₂ r₂ : Type u₁} (F : m₁ r₁ ≃ m₂ r₂) (G : α₁ ≃ α₂) : ContT r₁ m₁ α₁ ≃ ContT r₂ m₂ α₂ where toFun f r := F <| f fun x => F.symm <| r <| G x invFun f r := F.symm <| f fun x => F <| r <| G.symm x left_inv f := by funext r; simp right_inv f := by funext r; simp
Control\Monad\Writer.lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, E.W.Ayers -/ import Mathlib.Algebra.Group.Defs import Mathlib.Logic.Equiv.Defs /-! # Writer monads This file introduces monads for managing immutable, appendable state. Common applications are logging monads where the monad logs messages as the computation progresses. ## References - https://hackage.haskell.org/package/mtl-2.2.1/docs/Control-Monad-Writer-Class.html - [Original Mark P Jones article introducing `Writer`](https://web.cecs.pdx.edu/~mpj/pubs/springschool.html) -/ universe u v def WriterT (ω : Type u) (M : Type u → Type v) (α : Type u) : Type v := M (α × ω) abbrev Writer ω := WriterT ω Id class MonadWriter (ω : outParam (Type u)) (M : Type u → Type v) where tell : ω → M PUnit listen {α} : M α → M (α × ω) pass {α} : M (α × (ω → ω)) → M α export MonadWriter (tell listen pass) variable {M : Type u → Type v} {α ω ρ σ : Type u} instance [MonadWriter ω M] : MonadWriter ω (ReaderT ρ M) where tell w := (tell w : M _) listen x r := listen <| x r pass x r := pass <| x r instance [Monad M] [MonadWriter ω M] : MonadWriter ω (StateT σ M) where tell w := (tell w : M _) listen x s := (fun ((a,w), s) ↦ ((a,s), w)) <$> listen (x s) pass x s := pass <| (fun ((a, f), s) ↦ ((a, s), f)) <$> (x s) namespace WriterT @[inline] protected def mk {ω : Type u} (cmd : M (α × ω)) : WriterT ω M α := cmd @[inline] protected def run {ω : Type u} (cmd : WriterT ω M α) : M (α × ω) := cmd @[inline] protected def runThe (ω : Type u) (cmd : WriterT ω M α) : M (α × ω) := cmd @[ext] protected theorem ext {ω : Type u} (x x' : WriterT ω M α) (h : x.run = x'.run) : x = x' := h variable {ω : Type u} {α β : Type u} [Monad M] /-- Creates an instance of `Monad`, with explicitly given `empty` and `append` operations. Previously, this would have used an instance of `[Monoid ω]` as input. In practice, however, `WriterT` is used for logging and creating lists so restricting to monoids with `Mul` and `One` can make `WriterT` cumbersome to use. This is used to derive instances for both `[EmptyCollection ω] [Append ω]` and `[Monoid ω]`. -/ @[reducible, inline] def monad (empty : ω) (append : ω → ω → ω) : Monad (WriterT ω M) where map := fun f (cmd : M _) ↦ WriterT.mk <| (fun (a,w) ↦ (f a, w)) <$> cmd pure := fun a ↦ pure (f := M) (a, empty) bind := fun (cmd : M _) f ↦ WriterT.mk <| cmd >>= fun (a, w₁) ↦ (fun (b, w₂) ↦ (b, append w₁ w₂)) <$> (f a) /-- Lift an `M` to a `WriterT ω M`, using the given `empty` as the monoid unit. -/ @[inline] protected def liftTell (empty : ω) : MonadLift M (WriterT ω M) where monadLift := fun cmd ↦ WriterT.mk <| (fun a ↦ (a, empty)) <$> cmd instance [EmptyCollection ω] [Append ω] : Monad (WriterT ω M) := monad ∅ (· ++ ·) instance [EmptyCollection ω] : MonadLift M (WriterT ω M) := WriterT.liftTell ∅ instance [Monoid ω] : Monad (WriterT ω M) := monad 1 (· * ·) instance [Monoid ω] : MonadLift M (WriterT ω M) := WriterT.liftTell 1 instance [Monoid ω] [LawfulMonad M] : LawfulMonad (WriterT ω M) := LawfulMonad.mk' (bind_pure_comp := by intros; simp [Bind.bind, Functor.map, Pure.pure, WriterT.mk, bind_pure_comp]) (id_map := by intros; simp [Functor.map, WriterT.mk]) (pure_bind := by intros; simp [Bind.bind, Pure.pure, WriterT.mk]) (bind_assoc := by intros; simp [Bind.bind, mul_assoc, WriterT.mk, ← bind_pure_comp]) instance : MonadWriter ω (WriterT ω M) where tell := fun w ↦ WriterT.mk <| pure (⟨⟩, w) listen := fun cmd ↦ WriterT.mk <| (fun (a,w) ↦ ((a,w), w)) <$> cmd pass := fun cmd ↦ WriterT.mk <| (fun ((a,f), w) ↦ (a, f w)) <$> cmd instance {ε : Type*} [MonadExcept ε M] : MonadExcept ε (WriterT ω M) where throw := fun e ↦ WriterT.mk <| throw e tryCatch := fun cmd c ↦ WriterT.mk <| tryCatch cmd fun e ↦ (c e).run instance [MonadLiftT M (WriterT ω M)] : MonadControl M (WriterT ω M) where stM := fun α ↦ α × ω liftWith f := liftM <| f fun x ↦ x.run restoreM := WriterT.mk instance : MonadFunctor M (WriterT ω M) where monadMap := fun k (w : M _) ↦ WriterT.mk <| k w @[inline] protected def adapt {ω' : Type u} {α : Type u} (f : ω → ω') : WriterT ω M α → WriterT ω' M α := fun cmd ↦ WriterT.mk <| Prod.map id f <$> cmd end WriterT /-- Adapt a monad stack, changing the type of its top-most environment. This class is comparable to [Control.Lens.Magnify](https://hackage.haskell.org/package/lens-4.15.4/docs/Control-Lens-Zoom.html#t:Magnify), but does not use lenses (why would it), and is derived automatically for any transformer implementing `MonadFunctor`. -/ class MonadWriterAdapter (ω : outParam (Type u)) (m : Type u → Type v) where adaptWriter {α : Type u} : (ω → ω) → m α → m α export MonadWriterAdapter (adaptWriter) variable {m : Type u → Type*} /-- Transitivity. see Note [lower instance priority] -/ instance (priority := 100) monadWriterAdapterTrans {n : Type u → Type v} [MonadWriterAdapter ω m] [MonadFunctor m n] : MonadWriterAdapter ω n where adaptWriter f := monadMap (fun {α} ↦ (adaptWriter f : m α → m α)) instance [Monad m] : MonadWriterAdapter ω (WriterT ω m) where adaptWriter := WriterT.adapt universe u₀ u₁ v₀ v₁ in /-- reduce the equivalence between two writer monads to the equivalence between their underlying monad -/ def WriterT.equiv {m₁ : Type u₀ → Type v₀} {m₂ : Type u₁ → Type v₁} {α₁ ω₁ : Type u₀} {α₂ ω₂ : Type u₁} (F : (m₁ (α₁ × ω₁)) ≃ (m₂ (α₂ × ω₂))) : WriterT ω₁ m₁ α₁ ≃ WriterT ω₂ m₂ α₂ where toFun (f : m₁ _) := WriterT.mk <| F f invFun (f : m₂ _) := WriterT.mk <| F.symm f left_inv (f : m₁ _) := congr_arg WriterT.mk <| F.left_inv f right_inv (f : m₂ _) := congr_arg WriterT.mk <| F.right_inv f
Control\Traversable\Basic.lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import Mathlib.Data.Option.Defs import Mathlib.Control.Functor import Batteries.Data.List.Basic /-! # Traversable type class Type classes for traversing collections. The concepts and laws are taken from <http://hackage.haskell.org/package/base-4.11.1.0/docs/Data-Traversable.html> Traversable collections are a generalization of functors. Whereas functors (such as `List`) allow us to apply a function to every element, it does not allow functions which external effects encoded in a monad. Consider for instance a functor `invite : email → IO response` that takes an email address, sends an email and waits for a response. If we have a list `guests : List email`, using calling `invite` using `map` gives us the following: `map invite guests : List (IO response)`. It is not what we need. We need something of type `IO (List response)`. Instead of using `map`, we can use `traverse` to send all the invites: `traverse invite guests : IO (List response)`. `traverse` applies `invite` to every element of `guests` and combines all the resulting effects. In the example, the effect is encoded in the monad `IO` but any applicative functor is accepted by `traverse`. For more on how to use traversable, consider the Haskell tutorial: <https://en.wikibooks.org/wiki/Haskell/Traversable> ## Main definitions * `Traversable` type class - exposes the `traverse` function * `sequence` - based on `traverse`, turns a collection of effects into an effect returning a collection * `LawfulTraversable` - laws for a traversable functor * `ApplicativeTransformation` - the notion of a natural transformation for applicative functors ## Tags traversable iterator functor applicative ## References * "Applicative Programming with Effects", by Conor McBride and Ross Paterson, Journal of Functional Programming 18:1 (2008) 1-13, online at <http://www.soi.city.ac.uk/~ross/papers/Applicative.html> * "The Essence of the Iterator Pattern", by Jeremy Gibbons and Bruno Oliveira, in Mathematically-Structured Functional Programming, 2006, online at <http://web.comlab.ox.ac.uk/oucl/work/jeremy.gibbons/publications/#iterator> * "An Investigation of the Laws of Traversals", by Mauro Jaskelioff and Ondrej Rypacek, in Mathematically-Structured Functional Programming, 2012, online at <http://arxiv.org/pdf/1202.2919> -/ open Function hiding comp universe u v w section ApplicativeTransformation variable (F : Type u → Type v) [Applicative F] [LawfulApplicative F] variable (G : Type u → Type w) [Applicative G] [LawfulApplicative G] /-- A transformation between applicative functors. It is a natural transformation such that `app` preserves the `Pure.pure` and `Functor.map` (`<*>`) operations. See `ApplicativeTransformation.preserves_map` for naturality. -/ structure ApplicativeTransformation : Type max (u + 1) v w where /-- The function on objects defined by an `ApplicativeTransformation`. -/ app : ∀ α : Type u, F α → G α /-- An `ApplicativeTransformation` preserves `pure`. -/ preserves_pure' : ∀ {α : Type u} (x : α), app _ (pure x) = pure x /-- An `ApplicativeTransformation` intertwines `seq`. -/ preserves_seq' : ∀ {α β : Type u} (x : F (α → β)) (y : F α), app _ (x <*> y) = app _ x <*> app _ y end ApplicativeTransformation namespace ApplicativeTransformation variable (F : Type u → Type v) [Applicative F] variable (G : Type u → Type w) [Applicative G] instance : CoeFun (ApplicativeTransformation F G) fun _ => ∀ {α}, F α → G α := ⟨fun η ↦ η.app _⟩ variable {F G} -- This cannot be a `simp` lemma, as the RHS is a coercion which contains `η.app`. theorem app_eq_coe (η : ApplicativeTransformation F G) : η.app = η := rfl @[simp] theorem coe_mk (f : ∀ α : Type u, F α → G α) (pp ps) : (ApplicativeTransformation.mk f @pp @ps) = f := rfl protected theorem congr_fun (η η' : ApplicativeTransformation F G) (h : η = η') {α : Type u} (x : F α) : η x = η' x := congrArg (fun η'' : ApplicativeTransformation F G => η'' x) h protected theorem congr_arg (η : ApplicativeTransformation F G) {α : Type u} {x y : F α} (h : x = y) : η x = η y := congrArg (fun z : F α => η z) h theorem coe_inj ⦃η η' : ApplicativeTransformation F G⦄ (h : (η : ∀ α, F α → G α) = η') : η = η' := by cases η cases η' congr @[ext] theorem ext ⦃η η' : ApplicativeTransformation F G⦄ (h : ∀ (α : Type u) (x : F α), η x = η' x) : η = η' := by apply coe_inj ext1 α exact funext (h α) section Preserves variable (η : ApplicativeTransformation F G) @[functor_norm] theorem preserves_pure {α} : ∀ x : α, η (pure x) = pure x := η.preserves_pure' @[functor_norm] theorem preserves_seq {α β : Type u} : ∀ (x : F (α → β)) (y : F α), η (x <*> y) = η x <*> η y := η.preserves_seq' variable [LawfulApplicative F] [LawfulApplicative G] @[functor_norm] theorem preserves_map {α β} (x : α → β) (y : F α) : η (x <$> y) = x <$> η y := by rw [← pure_seq, η.preserves_seq, preserves_pure, pure_seq] theorem preserves_map' {α β} (x : α → β) : @η _ ∘ Functor.map x = Functor.map x ∘ @η _ := by ext y exact preserves_map η x y end Preserves /-- The identity applicative transformation from an applicative functor to itself. -/ def idTransformation : ApplicativeTransformation F F where app α := id preserves_pure' := by simp preserves_seq' x y := by simp instance : Inhabited (ApplicativeTransformation F F) := ⟨idTransformation⟩ universe s t variable {H : Type u → Type s} [Applicative H] /-- The composition of applicative transformations. -/ def comp (η' : ApplicativeTransformation G H) (η : ApplicativeTransformation F G) : ApplicativeTransformation F H where app α x := η' (η x) -- Porting note: something has gone wrong with `simp [functor_norm]`, -- which should suffice for the next two. preserves_pure' x := by simp only [preserves_pure] preserves_seq' x y := by simp only [preserves_seq] @[simp] theorem comp_apply (η' : ApplicativeTransformation G H) (η : ApplicativeTransformation F G) {α : Type u} (x : F α) : η'.comp η x = η' (η x) := rfl -- Porting note: in mathlib3 we also had the assumption `[LawfulApplicative I]` because -- this was assumed theorem comp_assoc {I : Type u → Type t} [Applicative I] (η'' : ApplicativeTransformation H I) (η' : ApplicativeTransformation G H) (η : ApplicativeTransformation F G) : (η''.comp η').comp η = η''.comp (η'.comp η) := rfl @[simp] theorem comp_id (η : ApplicativeTransformation F G) : η.comp idTransformation = η := ext fun _ _ => rfl @[simp] theorem id_comp (η : ApplicativeTransformation F G) : idTransformation.comp η = η := ext fun _ _ => rfl end ApplicativeTransformation open ApplicativeTransformation /-- A traversable functor is a functor along with a way to commute with all applicative functors (see `sequence`). For example, if `t` is the traversable functor `List` and `m` is the applicative functor `IO`, then given a function `f : α → IO β`, the function `Functor.map f` is `List α → List (IO β)`, but `traverse f` is `List α → IO (List β)`. -/ class Traversable (t : Type u → Type u) extends Functor t where /-- The function commuting a traversable functor `t` with an arbitrary applicative functor `m`. -/ traverse : ∀ {m : Type u → Type u} [Applicative m] {α β}, (α → m β) → t α → m (t β) open Functor export Traversable (traverse) section Functions variable {t : Type u → Type u} variable {m : Type u → Type v} [Applicative m] variable {α β : Type u} variable {f : Type u → Type u} [Applicative f] /-- A traversable functor commutes with all applicative functors. -/ def sequence [Traversable t] : t (f α) → f (t α) := traverse id end Functions /-- A traversable functor is lawful if its `traverse` satisfies a number of additional properties. It must send `pure : α → Id α` to `pure`, send the composition of applicative functors to the composition of the `traverse` of each, send each function `f` to `fun x ↦ f <$> x`, and satisfy a naturality condition with respect to applicative transformations. -/ class LawfulTraversable (t : Type u → Type u) [Traversable t] extends LawfulFunctor t : Prop where /-- `traverse` plays well with `pure` of the identity monad-/ id_traverse : ∀ {α} (x : t α), traverse (pure : α → Id α) x = x /-- `traverse` plays well with composition of applicative functors. -/ comp_traverse : ∀ {F G} [Applicative F] [Applicative G] [LawfulApplicative F] [LawfulApplicative G] {α β γ} (f : β → F γ) (g : α → G β) (x : t α), traverse (Functor.Comp.mk ∘ map f ∘ g) x = Comp.mk (map (traverse f) (traverse g x)) /-- An axiom for `traverse` involving `pure : β → Id β`. -/ traverse_eq_map_id : ∀ {α β} (f : α → β) (x : t α), traverse ((pure : β → Id β) ∘ f) x = id.mk (f <$> x) /-- The naturality axiom explaining how lawful traversable functors should play with lawful applicative functors. -/ naturality : ∀ {F G} [Applicative F] [Applicative G] [LawfulApplicative F] [LawfulApplicative G] (η : ApplicativeTransformation F G) {α β} (f : α → F β) (x : t α), η (traverse f x) = traverse (@η _ ∘ f) x instance : Traversable Id := ⟨id⟩ instance : LawfulTraversable Id where id_traverse _ := rfl comp_traverse _ _ _ := rfl traverse_eq_map_id _ _ := rfl naturality _ _ _ _ _ := rfl section variable {F : Type u → Type v} [Applicative F] instance : Traversable Option := ⟨Option.traverse⟩ instance : Traversable List := ⟨List.traverse⟩ end namespace Sum variable {σ : Type u} variable {F : Type u → Type u} variable [Applicative F] /-- Defines a `traverse` function on the second component of a sum type. This is used to give a `Traversable` instance for the functor `σ ⊕ -`. -/ protected def traverse {α β} (f : α → F β) : σ ⊕ α → F (σ ⊕ β) | Sum.inl x => pure (Sum.inl x) | Sum.inr x => Sum.inr <$> f x end Sum instance {σ : Type u} : Traversable.{u} (Sum σ) := ⟨@Sum.traverse _⟩
Control\Traversable\Equiv.lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import Mathlib.Control.Traversable.Lemmas import Mathlib.Logic.Equiv.Defs /-! # Transferring `Traversable` instances along isomorphisms This file allows to transfer `Traversable` instances along isomorphisms. ## Main declarations * `Equiv.map`: Turns functorially a function `α → β` into a function `t' α → t' β` using the functor `t` and the equivalence `Π α, t α ≃ t' α`. * `Equiv.functor`: `Equiv.map` as a functor. * `Equiv.traverse`: Turns traversably a function `α → m β` into a function `t' α → m (t' β)` using the traversable functor `t` and the equivalence `Π α, t α ≃ t' α`. * `Equiv.traversable`: `Equiv.traverse` as a traversable functor. * `Equiv.isLawfulTraversable`: `Equiv.traverse` as a lawful traversable functor. -/ universe u namespace Equiv section Functor -- Porting note: `parameter` doesn't seem to work yet. variable {t t' : Type u → Type u} (eqv : ∀ α, t α ≃ t' α) variable [Functor t] open Functor /-- Given a functor `t`, a function `t' : Type u → Type u`, and equivalences `t α ≃ t' α` for all `α`, then every function `α → β` can be mapped to a function `t' α → t' β` functorially (see `Equiv.functor`). -/ protected def map {α β : Type u} (f : α → β) (x : t' α) : t' β := eqv β <| map f ((eqv α).symm x) /-- The function `Equiv.map` transfers the functoriality of `t` to `t'` using the equivalences `eqv`. -/ protected def functor : Functor t' where map := Equiv.map eqv variable [LawfulFunctor t] protected theorem id_map {α : Type u} (x : t' α) : Equiv.map eqv id x = x := by simp [Equiv.map, id_map] protected theorem comp_map {α β γ : Type u} (g : α → β) (h : β → γ) (x : t' α) : Equiv.map eqv (h ∘ g) x = Equiv.map eqv h (Equiv.map eqv g x) := by simpa [Equiv.map] using comp_map .. protected theorem lawfulFunctor : @LawfulFunctor _ (Equiv.functor eqv) := -- Porting note: why is `_inst` required here? let _inst := Equiv.functor eqv; { map_const := fun {_ _} => rfl id_map := Equiv.id_map eqv comp_map := Equiv.comp_map eqv } protected theorem lawfulFunctor' [F : Functor t'] (h₀ : ∀ {α β} (f : α → β), Functor.map f = Equiv.map eqv f) (h₁ : ∀ {α β} (f : β), Functor.mapConst f = (Equiv.map eqv ∘ Function.const α) f) : LawfulFunctor t' := by have : F = Equiv.functor eqv := by cases F dsimp [Equiv.functor] congr <;> ext <;> dsimp only <;> [rw [← h₀]; rw [← h₁]] <;> rfl subst this exact Equiv.lawfulFunctor eqv end Functor section Traversable variable {t t' : Type u → Type u} (eqv : ∀ α, t α ≃ t' α) variable [Traversable t] variable {m : Type u → Type u} [Applicative m] variable {α β : Type u} /-- Like `Equiv.map`, a function `t' : Type u → Type u` can be given the structure of a traversable functor using a traversable functor `t'` and equivalences `t α ≃ t' α` for all α. See `Equiv.traversable`. -/ protected def traverse (f : α → m β) (x : t' α) : m (t' β) := eqv β <$> traverse f ((eqv α).symm x) theorem traverse_def (f : α → m β) (x : t' α) : Equiv.traverse eqv f x = eqv β <$> traverse f ((eqv α).symm x) := rfl /-- The function `Equiv.traverse` transfers a traversable functor instance across the equivalences `eqv`. -/ protected def traversable : Traversable t' where toFunctor := Equiv.functor eqv traverse := Equiv.traverse eqv end Traversable section Equiv variable {t t' : Type u → Type u} (eqv : ∀ α, t α ≃ t' α) -- Is this to do with the fact it lives in `Type (u+1)` not `Prop`? variable [Traversable t] [LawfulTraversable t] variable {F G : Type u → Type u} [Applicative F] [Applicative G] variable [LawfulApplicative F] [LawfulApplicative G] variable (η : ApplicativeTransformation F G) variable {α β γ : Type u} open LawfulTraversable Functor protected theorem id_traverse (x : t' α) : Equiv.traverse eqv (pure : α → Id α) x = x := by rw [Equiv.traverse, id_traverse, Id.map_eq, apply_symm_apply] protected theorem traverse_eq_map_id (f : α → β) (x : t' α) : Equiv.traverse eqv ((pure : β → Id β) ∘ f) x = pure (Equiv.map eqv f x) := by simp only [Equiv.traverse, traverse_eq_map_id, Id.map_eq, Id.pure_eq]; rfl protected theorem comp_traverse (f : β → F γ) (g : α → G β) (x : t' α) : Equiv.traverse eqv (Comp.mk ∘ Functor.map f ∘ g) x = Comp.mk (Equiv.traverse eqv f <$> Equiv.traverse eqv g x) := by rw [traverse_def, comp_traverse, Comp.map_mk] simp only [map_map, Function.comp_def, traverse_def, symm_apply_apply] protected theorem naturality (f : α → F β) (x : t' α) : η (Equiv.traverse eqv f x) = Equiv.traverse eqv (@η _ ∘ f) x := by simp only [Equiv.traverse, functor_norm] /-- The fact that `t` is a lawful traversable functor carries over the equivalences to `t'`, with the traversable functor structure given by `Equiv.traversable`. -/ protected theorem isLawfulTraversable : @LawfulTraversable t' (Equiv.traversable eqv) := -- Porting note: Same `_inst` local variable problem. let _inst := Equiv.traversable eqv; { toLawfulFunctor := Equiv.lawfulFunctor eqv id_traverse := Equiv.id_traverse eqv comp_traverse := Equiv.comp_traverse eqv traverse_eq_map_id := Equiv.traverse_eq_map_id eqv naturality := Equiv.naturality eqv } /-- If the `Traversable t'` instance has the properties that `map`, `map_const`, and `traverse` are equal to the ones that come from carrying the traversable functor structure from `t` over the equivalences, then the fact that `t` is a lawful traversable functor carries over as well. -/ protected theorem isLawfulTraversable' [Traversable t'] (h₀ : ∀ {α β} (f : α → β), map f = Equiv.map eqv f) (h₁ : ∀ {α β} (f : β), mapConst f = (Equiv.map eqv ∘ Function.const α) f) (h₂ : ∀ {F : Type u → Type u} [Applicative F], ∀ [LawfulApplicative F] {α β} (f : α → F β), traverse f = Equiv.traverse eqv f) : LawfulTraversable t' where -- we can't use the same approach as for `lawful_functor'` because -- h₂ needs a `LawfulApplicative` assumption toLawfulFunctor := Equiv.lawfulFunctor' eqv @h₀ @h₁ id_traverse _ := by rw [h₂, Equiv.id_traverse] comp_traverse _ _ _ := by rw [h₂, Equiv.comp_traverse, h₂]; congr; rw [h₂] traverse_eq_map_id _ _ := by rw [h₂, Equiv.traverse_eq_map_id, h₀]; rfl naturality _ _ _ _ _ := by rw [h₂, Equiv.naturality, h₂] end Equiv end Equiv
Control\Traversable\Instances.lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import Mathlib.Control.Applicative import Mathlib.Control.Traversable.Basic import Mathlib.Data.List.Forall2 import Mathlib.Data.Set.Functor /-! # LawfulTraversable instances This file provides instances of `LawfulTraversable` for types from the core library: `Option`, `List` and `Sum`. -/ universe u v section Option open Functor variable {F G : Type u → Type u} variable [Applicative F] [Applicative G] variable [LawfulApplicative G] theorem Option.id_traverse {α} (x : Option α) : Option.traverse (pure : α → Id α) x = x := by cases x <;> rfl theorem Option.comp_traverse {α β γ} (f : β → F γ) (g : α → G β) (x : Option α) : Option.traverse (Comp.mk ∘ (f <$> ·) ∘ g) x = Comp.mk (Option.traverse f <$> Option.traverse g x) := by cases x <;> simp! [functor_norm] <;> rfl theorem Option.traverse_eq_map_id {α β} (f : α → β) (x : Option α) : Option.traverse ((pure : _ → Id _) ∘ f) x = (pure : _ → Id _) (f <$> x) := by cases x <;> rfl variable (η : ApplicativeTransformation F G) theorem Option.naturality [LawfulApplicative F] {α β} (f : α → F β) (x : Option α) : η (Option.traverse f x) = Option.traverse (@η _ ∘ f) x := by -- Porting note: added `ApplicativeTransformation` theorems cases' x with x <;> simp! [*, functor_norm, ApplicativeTransformation.preserves_map, ApplicativeTransformation.preserves_seq, ApplicativeTransformation.preserves_pure] end Option instance : LawfulTraversable Option := { show LawfulMonad Option from inferInstance with id_traverse := Option.id_traverse comp_traverse := Option.comp_traverse traverse_eq_map_id := Option.traverse_eq_map_id naturality := fun η _ _ f x => Option.naturality η f x } namespace List variable {F G : Type u → Type u} variable [Applicative F] [Applicative G] section variable [LawfulApplicative G] open Applicative Functor List protected theorem id_traverse {α} (xs : List α) : List.traverse (pure : α → Id α) xs = xs := by induction xs <;> simp! [*, List.traverse, functor_norm]; rfl protected theorem comp_traverse {α β γ} (f : β → F γ) (g : α → G β) (x : List α) : List.traverse (Comp.mk ∘ (f <$> ·) ∘ g) x = Comp.mk (List.traverse f <$> List.traverse g x) := by induction x <;> simp! [*, functor_norm] <;> rfl protected theorem traverse_eq_map_id {α β} (f : α → β) (x : List α) : List.traverse ((pure : _ → Id _) ∘ f) x = (pure : _ → Id _) (f <$> x) := by induction x <;> simp! [*, functor_norm]; rfl variable [LawfulApplicative F] (η : ApplicativeTransformation F G) protected theorem naturality {α β} (f : α → F β) (x : List α) : η (List.traverse f x) = List.traverse (@η _ ∘ f) x := by -- Porting note: added `ApplicativeTransformation` theorems induction x <;> simp! [*, functor_norm, ApplicativeTransformation.preserves_map, ApplicativeTransformation.preserves_seq, ApplicativeTransformation.preserves_pure] instance : LawfulTraversable.{u} List := { show LawfulMonad List from inferInstance with id_traverse := List.id_traverse comp_traverse := List.comp_traverse traverse_eq_map_id := List.traverse_eq_map_id naturality := List.naturality } end section Traverse variable {α' β' : Type u} (f : α' → F β') @[simp] theorem traverse_nil : traverse f ([] : List α') = (pure [] : F (List β')) := rfl @[simp] theorem traverse_cons (a : α') (l : List α') : traverse f (a :: l) = (· :: ·) <$> f a <*> traverse f l := rfl variable [LawfulApplicative F] @[simp] theorem traverse_append : ∀ as bs : List α', traverse f (as ++ bs) = (· ++ ·) <$> traverse f as <*> traverse f bs | [], bs => by simp [functor_norm] | a :: as, bs => by simp [traverse_append as bs, functor_norm]; congr theorem mem_traverse {f : α' → Set β'} : ∀ (l : List α') (n : List β'), n ∈ traverse f l ↔ Forall₂ (fun b a => b ∈ f a) n l | [], [] => by simp | a :: as, [] => by simp | [], b :: bs => by simp | a :: as, b :: bs => by simp [mem_traverse as bs] end Traverse end List namespace Sum section Traverse variable {σ : Type u} variable {F G : Type u → Type u} variable [Applicative F] [Applicative G] open Applicative Functor protected theorem traverse_map {α β γ : Type u} (g : α → β) (f : β → G γ) (x : σ ⊕ α) : Sum.traverse f (g <$> x) = Sum.traverse (f ∘ g) x := by cases x <;> simp [Sum.traverse, id_map, functor_norm] <;> rfl protected theorem id_traverse {σ α} (x : σ ⊕ α) : Sum.traverse (pure : α → Id α) x = x := by cases x <;> rfl variable [LawfulApplicative G] protected theorem comp_traverse {α β γ : Type u} (f : β → F γ) (g : α → G β) (x : σ ⊕ α) : Sum.traverse (Comp.mk ∘ (f <$> ·) ∘ g) x = Comp.mk.{u} (Sum.traverse f <$> Sum.traverse g x) := by cases x <;> simp! [Sum.traverse, map_id, functor_norm] <;> rfl protected theorem traverse_eq_map_id {α β} (f : α → β) (x : σ ⊕ α) : Sum.traverse ((pure : _ → Id _) ∘ f) x = (pure : _ → Id _) (f <$> x) := by induction x <;> simp! [*, functor_norm] <;> rfl protected theorem map_traverse {α β γ} (g : α → G β) (f : β → γ) (x : σ ⊕ α) : (f <$> ·) <$> Sum.traverse g x = Sum.traverse (f <$> g ·) x := by cases x <;> simp [Sum.traverse, id_map, functor_norm] <;> congr variable [LawfulApplicative F] (η : ApplicativeTransformation F G) protected theorem naturality {α β} (f : α → F β) (x : σ ⊕ α) : η (Sum.traverse f x) = Sum.traverse (@η _ ∘ f) x := by -- Porting note: added `ApplicativeTransformation` theorems cases x <;> simp! [Sum.traverse, functor_norm, ApplicativeTransformation.preserves_map, ApplicativeTransformation.preserves_seq, ApplicativeTransformation.preserves_pure] end Traverse instance {σ : Type u} : LawfulTraversable.{u} (Sum σ) := { show LawfulMonad (Sum σ) from inferInstance with id_traverse := Sum.id_traverse comp_traverse := Sum.comp_traverse traverse_eq_map_id := Sum.traverse_eq_map_id naturality := Sum.naturality } end Sum
Control\Traversable\Lemmas.lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import Mathlib.Control.Applicative import Mathlib.Control.Traversable.Basic /-! # Traversing collections This file proves basic properties of traversable and applicative functors and defines `PureTransformation F`, the natural applicative transformation from the identity functor to `F`. ## References Inspired by [The Essence of the Iterator Pattern][gibbons2009]. -/ universe u open LawfulTraversable open Function hiding comp open Functor attribute [functor_norm] LawfulTraversable.naturality attribute [simp] LawfulTraversable.id_traverse namespace Traversable variable {t : Type u → Type u} variable [Traversable t] [LawfulTraversable t] variable (F G : Type u → Type u) variable [Applicative F] [LawfulApplicative F] variable [Applicative G] [LawfulApplicative G] variable {α β γ : Type u} variable (g : α → F β) variable (h : β → G γ) variable (f : β → γ) /-- The natural applicative transformation from the identity functor to `F`, defined by `pure : Π {α}, α → F α`. -/ def PureTransformation : ApplicativeTransformation Id F where app := @pure F _ preserves_pure' x := rfl preserves_seq' f x := by simp only [map_pure, seq_pure] rfl @[simp] theorem pureTransformation_apply {α} (x : id α) : PureTransformation F x = pure x := rfl variable {F G} (x : t β) -- Porting note: need to specify `m/F/G := Id` because `id` no longer has a `Monad` instance theorem map_eq_traverse_id : map (f := t) f = traverse (m := Id) (pure ∘ f) := funext fun y => (traverse_eq_map_id f y).symm theorem map_traverse (x : t α) : map f <$> traverse g x = traverse (map f ∘ g) x := by rw [map_eq_traverse_id f] refine (comp_traverse (pure ∘ f) g x).symm.trans ?_ congr; apply Comp.applicative_comp_id theorem traverse_map (f : β → F γ) (g : α → β) (x : t α) : traverse f (g <$> x) = traverse (f ∘ g) x := by rw [@map_eq_traverse_id t _ _ _ _ g] refine (comp_traverse (G := Id) f (pure ∘ g) x).symm.trans ?_ congr; apply Comp.applicative_id_comp theorem pure_traverse (x : t α) : traverse pure x = (pure x : F (t α)) := by have : traverse pure x = pure (traverse (m := Id) pure x) := (naturality (PureTransformation F) pure x).symm rwa [id_traverse] at this theorem id_sequence (x : t α) : sequence (f := Id) (pure <$> x) = pure x := by simp [sequence, traverse_map, id_traverse] theorem comp_sequence (x : t (F (G α))) : sequence (Comp.mk <$> x) = Comp.mk (sequence <$> sequence x) := by simp only [sequence, traverse_map, id_comp]; rw [← comp_traverse]; simp [map_id] theorem naturality' (η : ApplicativeTransformation F G) (x : t (F α)) : η (sequence x) = sequence (@η _ <$> x) := by simp [sequence, naturality, traverse_map] @[functor_norm] theorem traverse_id : traverse pure = (pure : t α → Id (t α)) := by ext exact id_traverse _ @[functor_norm] theorem traverse_comp (g : α → F β) (h : β → G γ) : traverse (Comp.mk ∘ map h ∘ g) = (Comp.mk ∘ map (traverse h) ∘ traverse g : t α → Comp F G (t γ)) := by ext exact comp_traverse _ _ _ theorem traverse_eq_map_id' (f : β → γ) : traverse (m := Id) (pure ∘ f) = pure ∘ (map f : t β → t γ) := by ext exact traverse_eq_map_id _ _ -- @[functor_norm] theorem traverse_map' (g : α → β) (h : β → G γ) : traverse (h ∘ g) = (traverse h ∘ map g : t α → G (t γ)) := by ext rw [comp_apply, traverse_map] theorem map_traverse' (g : α → G β) (h : β → γ) : traverse (map h ∘ g) = (map (map h) ∘ traverse g : t α → G (t γ)) := by ext rw [comp_apply, map_traverse] theorem naturality_pf (η : ApplicativeTransformation F G) (f : α → F β) : traverse (@η _ ∘ f) = @η _ ∘ (traverse f : t α → F (t β)) := by ext rw [comp_apply, naturality] end Traversable
Data\BitVec.lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Harun Khan, Alex Keizer -/ import Mathlib.Algebra.Ring.InjSurj import Mathlib.Data.ZMod.Defs /-! # Basic Theorems About Bitvectors This file contains theorems about bitvectors which can only be stated in Mathlib or downstream because they refer to other notions defined in Mathlib. Please do not extend this file further: material about BitVec needed in downstream projects can either be PR'd to Lean, or kept downstream if it also relies on Mathlib. -/ namespace BitVec variable {w v : Nat} /-! ## Injectivity -/ theorem toNat_injective {n : Nat} : Function.Injective (BitVec.toNat : BitVec n → _) | ⟨_, _⟩, ⟨_, _⟩, rfl => rfl theorem toFin_injective {n : Nat} : Function.Injective (toFin : BitVec n → _) | ⟨_, _⟩, ⟨_, _⟩, rfl => rfl /-! ## Scalar Multiplication and Powers Having instance of `SMul ℕ`, `SMul ℤ` and `Pow` are prerequisites for a `CommRing` instance -/ instance : SMul ℕ (BitVec w) := ⟨fun x y => ofFin <| x • y.toFin⟩ instance : SMul ℤ (BitVec w) := ⟨fun x y => ofFin <| x • y.toFin⟩ instance : Pow (BitVec w) ℕ := ⟨fun x n => ofFin <| x.toFin ^ n⟩ lemma toFin_nsmul (n : ℕ) (x : BitVec w) : toFin (n • x) = n • x.toFin := rfl lemma toFin_zsmul (z : ℤ) (x : BitVec w) : toFin (z • x) = z • x.toFin := rfl lemma toFin_pow (x : BitVec w) (n : ℕ) : toFin (x ^ n) = x.toFin ^ n := rfl /-! ## Ring -/ instance : CommSemiring (BitVec w) := toFin_injective.commSemiring _ rfl /- toFin_zero -/ rfl /- toFin_one -/ toFin_add toFin_mul toFin_nsmul toFin_pow (fun _ => rfl) /- toFin_natCast -/ -- The statement in the new API would be: `n#(k.succ) = ((n / 2)#k).concat (n % 2 != 0)` end BitVec
Data\Bracket.lean
/- Copyright (c) 2021 Patrick Lutz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Lutz, Oliver Nash -/ import Mathlib.Tactic.TypeStar /-! # Bracket Notation This file provides notation which can be used for the Lie bracket, for the commutator of two subgroups, and for other similar operations. ## Main Definitions * `Bracket L M` for a binary operation that takes something in `L` and something in `M` and produces something in `M`. Defining an instance of this structure gives access to the notation `⁅ ⁆` ## Notation We introduce the notation `⁅x, y⁆` for the `bracket` of any `Bracket` structure. Note that these are the Unicode "square with quill" brackets rather than the usual square brackets. -/ /-- The `Bracket` class has three intended uses: 1. for certain binary operations on structures, like the product `⁅x, y⁆` of two elements `x`, `y` in a Lie algebra or the commutator of two elements `x` and `y` in a group. 2. for certain actions of one structure on another, like the action `⁅x, m⁆` of an element `x` of a Lie algebra on an element `m` in one of its modules (analogous to `SMul` in the associative setting). 3. for binary operations on substructures, like the commutator `⁅H, K⁆` of two subgroups `H` and `K` of a group. -/ class Bracket (L M : Type*) where /-- `⁅x, y⁆` is the result of a bracket operation on elements `x` and `y`. It is supported by the `Bracket` typeclass. -/ bracket : L → M → M @[inherit_doc] notation "⁅" x ", " y "⁆" => Bracket.bracket x y
Data\Bundle.lean
/- Copyright (c) 2021 Nicolò Cavalleri. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nicolò Cavalleri -/ import Mathlib.Data.Set.Basic /-! # Bundle Basic data structure to implement fiber bundles, vector bundles (maybe fibrations?), etc. This file should contain all possible results that do not involve any topology. We represent a bundle `E` over a base space `B` as a dependent type `E : B → Type*`. We define `Bundle.TotalSpace F E` to be the type of pairs `⟨b, x⟩`, where `b : B` and `x : E b`. This type is isomorphic to `Σ x, E x` and uses an extra argument `F` for reasons explained below. In general, the constructions of fiber bundles we will make will be of this form. ## Main Definitions * `Bundle.TotalSpace` the total space of a bundle. * `Bundle.TotalSpace.proj` the projection from the total space to the base space. * `Bundle.TotalSpace.mk` the constructor for the total space. ## Implementation Notes - We use a custom structure for the total space of a bundle instead of using a type synonym for the canonical disjoint union `Σ x, E x` because the total space usually has a different topology and Lean 4 `simp` fails to apply lemmas about `Σ x, E x` to elements of the total space. - The definition of `Bundle.TotalSpace` has an unused argument `F`. The reason is that in some constructions (e.g., `Bundle.ContinuousLinearMap.vectorBundle`) we need access to the atlas of trivializations of original fiber bundles to construct the topology on the total space of the new fiber bundle. ## References - https://en.wikipedia.org/wiki/Bundle_(mathematics) -/ open Function Set namespace Bundle variable {B F : Type*} (E : B → Type*) /-- `Bundle.TotalSpace F E` is the total space of the bundle. It consists of pairs `(proj : B, snd : E proj)`. -/ @[ext] structure TotalSpace (F : Type*) (E : B → Type*) where /-- `Bundle.TotalSpace.proj` is the canonical projection `Bundle.TotalSpace F E → B` from the total space to the base space. -/ proj : B snd : E proj instance [Inhabited B] [Inhabited (E default)] : Inhabited (TotalSpace F E) := ⟨⟨default, default⟩⟩ variable {E} @[inherit_doc] scoped notation:max "π" F':max E':max => Bundle.TotalSpace.proj (F := F') (E := E') abbrev TotalSpace.mk' (F : Type*) (x : B) (y : E x) : TotalSpace F E := ⟨x, y⟩ theorem TotalSpace.mk_cast {x x' : B} (h : x = x') (b : E x) : .mk' F x' (cast (congr_arg E h) b) = TotalSpace.mk x b := by subst h; rfl @[simp 1001, mfld_simps 1001] theorem TotalSpace.mk_inj {b : B} {y y' : E b} : mk' F b y = mk' F b y' ↔ y = y' := by simp [TotalSpace.ext_iff] theorem TotalSpace.mk_injective (b : B) : Injective (mk b : E b → TotalSpace F E) := fun _ _ ↦ mk_inj.1 instance {x : B} : CoeTC (E x) (TotalSpace F E) := ⟨TotalSpace.mk x⟩ theorem TotalSpace.eta (z : TotalSpace F E) : TotalSpace.mk z.proj z.2 = z := rfl @[simp] theorem TotalSpace.exists {p : TotalSpace F E → Prop} : (∃ x, p x) ↔ ∃ b y, p ⟨b, y⟩ := ⟨fun ⟨x, hx⟩ ↦ ⟨x.1, x.2, hx⟩, fun ⟨b, y, h⟩ ↦ ⟨⟨b, y⟩, h⟩⟩ @[simp] theorem TotalSpace.range_mk (b : B) : range ((↑) : E b → TotalSpace F E) = π F E ⁻¹' {b} := by apply Subset.antisymm · rintro _ ⟨x, rfl⟩ rfl · rintro ⟨_, x⟩ rfl exact ⟨x, rfl⟩ /-- Notation for the direct sum of two bundles over the same base. -/ notation:100 E₁ " ×ᵇ " E₂ => fun x => E₁ x × E₂ x /-- `Bundle.Trivial B F` is the trivial bundle over `B` of fiber `F`. -/ @[reducible, nolint unusedArguments] def Trivial (B : Type*) (F : Type*) : B → Type _ := fun _ => F /-- The trivial bundle, unlike other bundles, has a canonical projection on the fiber. -/ def TotalSpace.trivialSnd (B : Type*) (F : Type*) : TotalSpace F (Bundle.Trivial B F) → F := TotalSpace.snd /-- A trivial bundle is equivalent to the product `B × F`. -/ @[simps (config := { attrs := [`mfld_simps] })] def TotalSpace.toProd (B F : Type*) : (TotalSpace F fun _ : B => F) ≃ B × F where toFun x := (x.1, x.2) invFun x := ⟨x.1, x.2⟩ left_inv := fun ⟨_, _⟩ => rfl right_inv := fun ⟨_, _⟩ => rfl section Pullback variable {B' : Type*} /-- The pullback of a bundle `E` over a base `B` under a map `f : B' → B`, denoted by `Bundle.Pullback f E` or `f *ᵖ E`, is the bundle over `B'` whose fiber over `b'` is `E (f b')`. -/ def Pullback (f : B' → B) (E : B → Type*) : B' → Type _ := fun x => E (f x) @[inherit_doc] notation f " *ᵖ " E:arg => Pullback f E instance {f : B' → B} {x : B'} [Nonempty (E (f x))] : Nonempty ((f *ᵖ E) x) := ‹Nonempty (E (f x))› /-- Natural embedding of the total space of `f *ᵖ E` into `B' × TotalSpace F E`. -/ @[simp] def pullbackTotalSpaceEmbedding (f : B' → B) : TotalSpace F (f *ᵖ E) → B' × TotalSpace F E := fun z => (z.proj, TotalSpace.mk (f z.proj) z.2) /-- The base map `f : B' → B` lifts to a canonical map on the total spaces. -/ @[simps (config := { attrs := [`mfld_simps] })] def Pullback.lift (f : B' → B) : TotalSpace F (f *ᵖ E) → TotalSpace F E := fun z => ⟨f z.proj, z.2⟩ @[simp, mfld_simps] theorem Pullback.lift_mk (f : B' → B) (x : B') (y : E (f x)) : Pullback.lift f (.mk' F x y) = ⟨f x, y⟩ := rfl end Pullback -- Porting note: not needed since Lean unfolds coercion end Bundle
Data\ByteArray.lean
/- Copyright (c) 2021 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ /-! # Main result Introduce main properties of `Up` (well-ordered relation for "upwards" induction on `ℕ`) and of `ByteArray` -/ namespace Nat /-- A well-ordered relation for "upwards" induction on the natural numbers up to some bound `ub`. -/ def Up (ub a i : Nat) := i < a ∧ i < ub theorem Up.next {ub i} (h : i < ub) : Up ub (i+1) i := ⟨Nat.lt_succ_self _, h⟩ theorem Up.WF (ub) : WellFounded (Up ub) := Subrelation.wf (h₂ := (measure (ub - ·)).wf) fun ⟨ia, iu⟩ ↦ Nat.sub_lt_sub_left iu ia /-- A well-ordered relation for "upwards" induction on the natural numbers up to some bound `ub`. -/ def upRel (ub : Nat) : WellFoundedRelation Nat := ⟨Up ub, Up.WF ub⟩ end Nat /-- A terminal byte slice, a suffix of a byte array. -/ structure ByteSliceT := (arr : ByteArray) (off : Nat) namespace ByteSliceT /-- The number of elements in the byte slice. -/ @[inline] def size (self : ByteSliceT) : Nat := self.arr.size - self.off /-- Index into a byte slice. The `getOp` function allows the use of the `buf[i]` notation. -/ @[inline] def getOp (self : ByteSliceT) (idx : Nat) : UInt8 := self.arr.get! (self.off + idx) end ByteSliceT /-- Convert a byte array into a terminal slice. -/ def ByteArray.toSliceT (arr : ByteArray) : ByteSliceT := ⟨arr, 0⟩ /-- A byte slice, given by a backing byte array, and an offset and length. -/ structure ByteSlice := (arr : ByteArray) (off len : Nat) namespace ByteSlice /-- Convert a byte slice into an array, by copying the data if necessary. -/ def toArray : ByteSlice → ByteArray | ⟨arr, off, len⟩ => arr.extract off len /-- Index into a byte slice. The `getOp` function allows the use of the `buf[i]` notation. -/ @[inline] def getOp (self : ByteSlice) (idx : Nat) : UInt8 := self.arr.get! (self.off + idx) universe u v /-- The inner loop of the `forIn` implementation for byte slices. -/ def forIn.loop {m : Type u → Type v} {β : Type u} [Monad m] (f : UInt8 → β → m (ForInStep β)) (arr : ByteArray) (off _end : Nat) (i : Nat) (b : β) : m β := if h : i < _end then do match ← f (arr.get! i) b with | ForInStep.done b => pure b | ForInStep.yield b => have := Nat.Up.next h; loop f arr off _end (i+1) b else pure b termination_by _end - i instance {m : Type u → Type v} : ForIn m ByteSlice UInt8 := ⟨fun ⟨arr, off, len⟩ b f ↦ forIn.loop f arr off (off + len) off b⟩ end ByteSlice /-- Convert a terminal byte slice into a regular byte slice. -/ def ByteSliceT.toSlice : ByteSliceT → ByteSlice | ⟨arr, off⟩ => ⟨arr, off, arr.size - off⟩ /-- Convert a byte array into a byte slice. -/ def ByteArray.toSlice (arr : ByteArray) : ByteSlice := ⟨arr, 0, arr.size⟩ /-- Convert a string of assumed-ASCII characters into a byte array. (If any characters are non-ASCII they will be reduced modulo 256.) -/ def String.toAsciiByteArray (s : String) : ByteArray := let rec loop (p : Pos) (out : ByteArray) : ByteArray := if h : s.atEnd p then out else let c := s.get p have : utf8ByteSize s - (next s p).byteIdx < utf8ByteSize s - p.byteIdx := Nat.sub_lt_sub_left (Nat.lt_of_not_le <| mt decide_eq_true h) (Nat.lt_add_of_pos_right (Char.utf8Size_pos _)) loop (s.next p) (out.push c.toUInt8) termination_by utf8ByteSize s - p.byteIdx loop 0 ByteArray.empty /-- Convert a byte slice into a string. This does not handle non-ASCII characters correctly: every byte will become a unicode character with codepoint < 256. -/ def ByteSlice.toString (bs : ByteSlice) : String := Id.run do let mut s := "" for c in bs do s := s.push (Char.ofUInt8 c) s instance : ToString ByteSlice where toString bs := Id.run do let mut s := "" for c in bs do s := s.push (Char.ofUInt8 c) s
Data\Char.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 Mathlib.Data.Nat.Defs import Mathlib.Order.Defs /-! # More `Char` instances This file provides a `LinearOrder` instance on `Char`. `Char` is the type of Unicode scalar values. Provides an additional definition to truncate a `Char` to `UInt8` and a theorem on conversion to `Nat`. -/ /-- Provides a `LinearOrder` instance on `Char`. `Char` is the type of Unicode scalar values. -/ instance : LinearOrder Char where le_refl := fun _ => @le_refl ℕ _ _ le_trans := fun _ _ _ => @le_trans ℕ _ _ _ _ le_antisymm := fun _ _ h₁ h₂ => Char.eq_of_val_eq <| UInt32.eq_of_val_eq <| Fin.ext <| @le_antisymm ℕ _ _ _ h₁ h₂ lt_iff_le_not_le := fun _ _ => @lt_iff_le_not_le ℕ _ _ _ le_total := fun _ _ => @le_total ℕ _ _ _ min := fun a b => if a ≤ b then a else b max := fun a b => if a ≤ b then b else a decidableLE := inferInstance
Data\Erased.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 Mathlib.Logic.Equiv.Defs /-! # A type for VM-erased data This file defines a type `Erased α` which is classically isomorphic to `α`, but erased in the VM. That is, at runtime every value of `Erased α` is represented as `0`, just like types and proofs. -/ universe u /-- `Erased α` is the same as `α`, except that the elements of `Erased α` are erased in the VM in the same way as types and proofs. This can be used to track data without storing it literally. -/ def Erased (α : Sort u) : Sort max 1 u := Σ's : α → Prop, ∃ a, (fun b => a = b) = s namespace Erased /-- Erase a value. -/ @[inline] def mk {α} (a : α) : Erased α := ⟨fun b => a = b, a, rfl⟩ /-- Extracts the erased value, noncomputably. -/ noncomputable def out {α} : Erased α → α | ⟨_, h⟩ => Classical.choose h /-- Extracts the erased value, if it is a type. Note: `(mk a).OutType` is not definitionally equal to `a`. -/ abbrev OutType (a : Erased (Sort u)) : Sort u := out a /-- Extracts the erased value, if it is a proof. -/ theorem out_proof {p : Prop} (a : Erased p) : p := out a @[simp] theorem out_mk {α} (a : α) : (mk a).out = a := by let h := (mk a).2; show Classical.choose h = a have := Classical.choose_spec h exact cast (congr_fun this a).symm rfl @[simp] theorem mk_out {α} : ∀ a : Erased α, mk (out a) = a | ⟨s, h⟩ => by simp only [mk]; congr; exact Classical.choose_spec h @[ext] theorem out_inj {α} (a b : Erased α) (h : a.out = b.out) : a = b := by simpa using congr_arg mk h /-- Equivalence between `Erased α` and `α`. -/ noncomputable def equiv (α) : Erased α ≃ α := ⟨out, mk, mk_out, out_mk⟩ instance (α : Type u) : Repr (Erased α) := ⟨fun _ _ => "Erased"⟩ instance (α : Type u) : ToString (Erased α) := ⟨fun _ => "Erased"⟩ -- Porting note: Deleted `has_to_format` /-- Computably produce an erased value from a proof of nonemptiness. -/ def choice {α} (h : Nonempty α) : Erased α := mk (Classical.choice h) @[simp] theorem nonempty_iff {α} : Nonempty (Erased α) ↔ Nonempty α := ⟨fun ⟨a⟩ => ⟨a.out⟩, fun ⟨a⟩ => ⟨mk a⟩⟩ instance {α} [h : Nonempty α] : Inhabited (Erased α) := ⟨choice h⟩ /-- `(>>=)` operation on `Erased`. This is a separate definition because `α` and `β` can live in different universes (the universe is fixed in `Monad`). -/ def bind {α β} (a : Erased α) (f : α → Erased β) : Erased β := ⟨fun b => (f a.out).1 b, (f a.out).2⟩ @[simp] theorem bind_eq_out {α β} (a f) : @bind α β a f = f a.out := rfl /-- Collapses two levels of erasure. -/ def join {α} (a : Erased (Erased α)) : Erased α := bind a id @[simp] theorem join_eq_out {α} (a) : @join α a = a.out := bind_eq_out _ _ /-- `(<$>)` operation on `Erased`. This is a separate definition because `α` and `β` can live in different universes (the universe is fixed in `Functor`). -/ def map {α β} (f : α → β) (a : Erased α) : Erased β := bind a (mk ∘ f) @[simp] theorem map_out {α β} {f : α → β} (a : Erased α) : (a.map f).out = f a.out := by simp [map] protected instance Monad : Monad Erased where pure := @mk bind := @bind map := @map @[simp] theorem pure_def {α} : (pure : α → Erased α) = @mk _ := rfl @[simp] theorem bind_def {α β} : ((· >>= ·) : Erased α → (α → Erased β) → Erased β) = @bind _ _ := rfl @[simp] theorem map_def {α β} : ((· <$> ·) : (α → β) → Erased α → Erased β) = @map _ _ := rfl -- Porting note: Old proof `by refine' { .. } <;> intros <;> ext <;> simp` protected instance instLawfulMonad : LawfulMonad Erased := { id_map := by intros; ext; simp map_const := by intros; ext; simp [Functor.mapConst] pure_bind := by intros; ext; simp bind_assoc := by intros; ext; simp bind_pure_comp := by intros; ext; simp bind_map := by intros; ext; simp [Seq.seq] seqLeft_eq := by intros; ext; simp [Seq.seq, Functor.mapConst, SeqLeft.seqLeft] seqRight_eq := by intros; ext; simp [Seq.seq, Functor.mapConst, SeqRight.seqRight] pure_seq := by intros; ext; simp [Seq.seq, Functor.mapConst, SeqRight.seqRight] } end Erased
Data\FinEnum.lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import Mathlib.Data.Fintype.Basic import Mathlib.Data.List.ProdSigma import Mathlib.Data.List.Pi /-! Type class for finitely enumerable types. The property is stronger than `Fintype` in that it assigns each element a rank in a finite enumeration. -/ universe u v open Finset /-- `FinEnum α` means that `α` is finite and can be enumerated in some order, i.e. `α` has an explicit bijection with `Fin n` for some n. -/ class FinEnum (α : Sort*) where /-- `FinEnum.card` is the cardinality of the `FinEnum` -/ card : ℕ /-- `FinEnum.Equiv` states that type `α` is in bijection with `Fin card`, the size of the `FinEnum` -/ equiv : α ≃ Fin card [decEq : DecidableEq α] attribute [instance 100] FinEnum.decEq namespace FinEnum variable {α : Type u} {β : α → Type v} /-- transport a `FinEnum` instance across an equivalence -/ def ofEquiv (α) {β} [FinEnum α] (h : β ≃ α) : FinEnum β where card := card α equiv := h.trans (equiv) decEq := (h.trans (equiv)).decidableEq /-- create a `FinEnum` instance from an exhaustive list without duplicates -/ def ofNodupList [DecidableEq α] (xs : List α) (h : ∀ x : α, x ∈ xs) (h' : List.Nodup xs) : FinEnum α where card := xs.length equiv := ⟨fun x => ⟨xs.indexOf x, by rw [List.indexOf_lt_length]; apply h⟩, xs.get, fun x => by simp, fun i => by ext; simp [List.indexOf_getElem h']⟩ /-- create a `FinEnum` instance from an exhaustive list; duplicates are removed -/ def ofList [DecidableEq α] (xs : List α) (h : ∀ x : α, x ∈ xs) : FinEnum α := ofNodupList xs.dedup (by simp [*]) (List.nodup_dedup _) /-- create an exhaustive list of the values of a given type -/ def toList (α) [FinEnum α] : List α := (List.finRange (card α)).map (equiv).symm open Function @[simp] theorem mem_toList [FinEnum α] (x : α) : x ∈ toList α := by simp [toList]; exists equiv x; simp @[simp] theorem nodup_toList [FinEnum α] : List.Nodup (toList α) := by simp [toList]; apply List.Nodup.map <;> [apply Equiv.injective; apply List.nodup_finRange] /-- create a `FinEnum` instance using a surjection -/ def ofSurjective {β} (f : β → α) [DecidableEq α] [FinEnum β] (h : Surjective f) : FinEnum α := ofList ((toList β).map f) (by intro; simpa using h _) /-- create a `FinEnum` instance using an injection -/ noncomputable def ofInjective {α β} (f : α → β) [DecidableEq α] [FinEnum β] (h : Injective f) : FinEnum α := ofList ((toList β).filterMap (partialInv f)) (by intro x simp only [mem_toList, true_and_iff, List.mem_filterMap] use f x simp only [h, Function.partialInv_left]) instance pempty : FinEnum PEmpty := ofList [] fun x => PEmpty.elim x instance empty : FinEnum Empty := ofList [] fun x => Empty.elim x instance punit : FinEnum PUnit := ofList [PUnit.unit] fun x => by cases x; simp instance prod {β} [FinEnum α] [FinEnum β] : FinEnum (α × β) := ofList (toList α ×ˢ toList β) fun x => by cases x; simp instance sum {β} [FinEnum α] [FinEnum β] : FinEnum (α ⊕ β) := ofList ((toList α).map Sum.inl ++ (toList β).map Sum.inr) fun x => by cases x <;> simp instance fin {n} : FinEnum (Fin n) := ofList (List.finRange _) (by simp) instance Quotient.enum [FinEnum α] (s : Setoid α) [DecidableRel ((· ≈ ·) : α → α → Prop)] : FinEnum (Quotient s) := FinEnum.ofSurjective Quotient.mk'' fun x => Quotient.inductionOn x fun x => ⟨x, rfl⟩ /-- enumerate all finite sets of a given type -/ def Finset.enum [DecidableEq α] : List α → List (Finset α) | [] => [∅] | x :: xs => do let r ← Finset.enum xs [r, {x} ∪ r] @[simp] theorem Finset.mem_enum [DecidableEq α] (s : Finset α) (xs : List α) : s ∈ Finset.enum xs ↔ ∀ x ∈ s, x ∈ xs := by induction' xs with xs_hd generalizing s <;> simp [*, Finset.enum] · simp [Finset.eq_empty_iff_forall_not_mem] · constructor · rintro ⟨a, h, h'⟩ x hx cases' h' with _ h' a b · right apply h subst a exact hx · simp only [h', mem_union, mem_singleton] at hx ⊢ cases' hx with hx hx' · exact Or.inl hx · exact Or.inr (h _ hx') · intro h exists s \ ({xs_hd} : Finset α) simp only [and_imp, mem_sdiff, mem_singleton] simp only [or_iff_not_imp_left] at h exists h by_cases h : xs_hd ∈ s · have : {xs_hd} ⊆ s := by simp only [HasSubset.Subset, *, forall_eq, mem_singleton] simp only [union_sdiff_of_subset this, or_true_iff, Finset.union_sdiff_of_subset, eq_self_iff_true] · left symm simp only [sdiff_eq_self] intro a simp only [and_imp, mem_inter, mem_singleton] rintro h₀ rfl exact (h h₀).elim instance Finset.finEnum [FinEnum α] : FinEnum (Finset α) := ofList (Finset.enum (toList α)) (by intro; simp) instance Subtype.finEnum [FinEnum α] (p : α → Prop) [DecidablePred p] : FinEnum { x // p x } := ofList ((toList α).filterMap fun x => if h : p x then some ⟨_, h⟩ else none) (by rintro ⟨x, h⟩; simpa) instance (β : α → Type v) [FinEnum α] [∀ a, FinEnum (β a)] : FinEnum (Sigma β) := ofList ((toList α).bind fun a => (toList (β a)).map <| Sigma.mk a) (by intro x; cases x; simp) instance PSigma.finEnum [FinEnum α] [∀ a, FinEnum (β a)] : FinEnum (Σ'a, β a) := FinEnum.ofEquiv _ (Equiv.psigmaEquivSigma _) instance PSigma.finEnumPropLeft {α : Prop} {β : α → Type v} [∀ a, FinEnum (β a)] [Decidable α] : FinEnum (Σ'a, β a) := if h : α then ofList ((toList (β h)).map <| PSigma.mk h) fun ⟨a, Ba⟩ => by simp else ofList [] fun ⟨a, Ba⟩ => (h a).elim instance PSigma.finEnumPropRight {β : α → Prop} [FinEnum α] [∀ a, Decidable (β a)] : FinEnum (Σ'a, β a) := FinEnum.ofEquiv { a // β a } ⟨fun ⟨x, y⟩ => ⟨x, y⟩, fun ⟨x, y⟩ => ⟨x, y⟩, fun ⟨_, _⟩ => rfl, fun ⟨_, _⟩ => rfl⟩ instance PSigma.finEnumPropProp {α : Prop} {β : α → Prop} [Decidable α] [∀ a, Decidable (β a)] : FinEnum (Σ'a, β a) := if h : ∃ a, β a then ofList [⟨h.fst, h.snd⟩] (by rintro ⟨⟩; simp) else ofList [] fun a => (h ⟨a.fst, a.snd⟩).elim instance (priority := 100) [FinEnum α] : Fintype α where elems := univ.map (equiv).symm.toEmbedding complete := by intros; simp end FinEnum namespace List variable {α : Type*} [FinEnum α] {β : α → Type*} [∀ a, FinEnum (β a)] open FinEnum theorem mem_pi_toList (xs : List α) (f : ∀ a, a ∈ xs → β a) : f ∈ pi xs fun x => toList (β x) := (mem_pi _ _).mpr fun _ _ ↦ mem_toList _ /-- enumerate all functions whose domain and range are finitely enumerable -/ def Pi.enum (β : α → Type*) [∀ a, FinEnum (β a)] : List (∀ a, β a) := (pi (toList α) fun x => toList (β x)).map (fun f x => f x (mem_toList _)) theorem Pi.mem_enum (f : ∀ a, β a) : f ∈ Pi.enum β := by simpa [Pi.enum] using ⟨fun a _ => f a, mem_pi_toList _ _, rfl⟩ instance Pi.finEnum : FinEnum (∀ a, β a) := ofList (Pi.enum _) fun _ => Pi.mem_enum _ instance pfunFinEnum (p : Prop) [Decidable p] (α : p → Type) [∀ hp, FinEnum (α hp)] : FinEnum (∀ hp : p, α hp) := if hp : p then ofList ((toList (α hp)).map fun x _ => x) (by intro x; simpa using ⟨x hp, rfl⟩) else ofList [fun hp' => (hp hp').elim] (by intro; simp; ext hp'; cases hp hp') end List
Data\Finmap.lean
/- Copyright (c) 2018 Sean Leather. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sean Leather, Mario Carneiro -/ import Mathlib.Data.List.AList import Mathlib.Data.Finset.Sigma import Mathlib.Data.Part /-! # Finite maps over `Multiset` -/ universe u v w open List variable {α : Type u} {β : α → Type v} /-! ### Multisets of sigma types-/ namespace Multiset /-- Multiset of keys of an association multiset. -/ def keys (s : Multiset (Sigma β)) : Multiset α := s.map Sigma.fst @[simp] theorem coe_keys {l : List (Sigma β)} : keys (l : Multiset (Sigma β)) = (l.keys : Multiset α) := rfl -- Porting note: Fixed Nodupkeys -> NodupKeys /-- `NodupKeys s` means that `s` has no duplicate keys. -/ def NodupKeys (s : Multiset (Sigma β)) : Prop := Quot.liftOn s List.NodupKeys fun _ _ p => propext <| perm_nodupKeys p @[simp] theorem coe_nodupKeys {l : List (Sigma β)} : @NodupKeys α β l ↔ l.NodupKeys := Iff.rfl lemma nodup_keys {m : Multiset (Σ a, β a)} : m.keys.Nodup ↔ m.NodupKeys := by rcases m with ⟨l⟩; rfl alias ⟨_, NodupKeys.nodup_keys⟩ := nodup_keys protected lemma NodupKeys.nodup {m : Multiset (Σ a, β a)} (h : m.NodupKeys) : m.Nodup := h.nodup_keys.of_map _ end Multiset /-! ### Finmap -/ /-- `Finmap β` is the type of finite maps over a multiset. It is effectively a quotient of `AList β` by permutation of the underlying list. -/ structure Finmap (β : α → Type v) : Type max u v where /-- The underlying `Multiset` of a `Finmap` -/ entries : Multiset (Sigma β) /-- There are no duplicate keys in `entries` -/ nodupKeys : entries.NodupKeys /-- The quotient map from `AList` to `Finmap`. -/ def AList.toFinmap (s : AList β) : Finmap β := ⟨s.entries, s.nodupKeys⟩ local notation:arg "⟦" a "⟧" => AList.toFinmap a theorem AList.toFinmap_eq {s₁ s₂ : AList β} : toFinmap s₁ = toFinmap s₂ ↔ s₁.entries ~ s₂.entries := by cases s₁ cases s₂ simp [AList.toFinmap] @[simp] theorem AList.toFinmap_entries (s : AList β) : ⟦s⟧.entries = s.entries := rfl /-- Given `l : List (Sigma β)`, create a term of type `Finmap β` by removing entries with duplicate keys. -/ def List.toFinmap [DecidableEq α] (s : List (Sigma β)) : Finmap β := s.toAList.toFinmap namespace Finmap open AList lemma nodup_entries (f : Finmap β) : f.entries.Nodup := f.nodupKeys.nodup /-! ### Lifting from AList -/ /-- Lift a permutation-respecting function on `AList` to `Finmap`. -/ -- @[elab_as_elim] Porting note: we can't add `elab_as_elim` attr in this type def liftOn {γ} (s : Finmap β) (f : AList β → γ) (H : ∀ a b : AList β, a.entries ~ b.entries → f a = f b) : γ := by refine (Quotient.liftOn s.entries (fun (l : List (Sigma β)) => (⟨_, fun nd => f ⟨l, nd⟩⟩ : Part γ)) (fun l₁ l₂ p => Part.ext' (perm_nodupKeys p) ?_) : Part γ).get ?_ · exact fun h1 h2 => H _ _ p · have := s.nodupKeys -- Porting note: `revert` required because `rcases` behaves differently revert this rcases s.entries with ⟨l⟩ exact id @[simp] theorem liftOn_toFinmap {γ} (s : AList β) (f : AList β → γ) (H) : liftOn ⟦s⟧ f H = f s := by cases s rfl /-- Lift a permutation-respecting function on 2 `AList`s to 2 `Finmap`s. -/ -- @[elab_as_elim] Porting note: we can't add `elab_as_elim` attr in this type def liftOn₂ {γ} (s₁ s₂ : Finmap β) (f : AList β → AList β → γ) (H : ∀ a₁ b₁ a₂ b₂ : AList β, a₁.entries ~ a₂.entries → b₁.entries ~ b₂.entries → f a₁ b₁ = f a₂ b₂) : γ := liftOn s₁ (fun l₁ => liftOn s₂ (f l₁) fun b₁ b₂ p => H _ _ _ _ (Perm.refl _) p) fun a₁ a₂ p => by have H' : f a₁ = f a₂ := funext fun _ => H _ _ _ _ p (Perm.refl _) simp only [H'] @[simp] theorem liftOn₂_toFinmap {γ} (s₁ s₂ : AList β) (f : AList β → AList β → γ) (H) : liftOn₂ ⟦s₁⟧ ⟦s₂⟧ f H = f s₁ s₂ := by cases s₁; cases s₂; rfl /-! ### Induction -/ @[elab_as_elim] theorem induction_on {C : Finmap β → Prop} (s : Finmap β) (H : ∀ a : AList β, C ⟦a⟧) : C s := by rcases s with ⟨⟨a⟩, h⟩; exact H ⟨a, h⟩ @[elab_as_elim] theorem induction_on₂ {C : Finmap β → Finmap β → Prop} (s₁ s₂ : Finmap β) (H : ∀ a₁ a₂ : AList β, C ⟦a₁⟧ ⟦a₂⟧) : C s₁ s₂ := induction_on s₁ fun l₁ => induction_on s₂ fun l₂ => H l₁ l₂ @[elab_as_elim] theorem induction_on₃ {C : Finmap β → Finmap β → Finmap β → Prop} (s₁ s₂ s₃ : Finmap β) (H : ∀ a₁ a₂ a₃ : AList β, C ⟦a₁⟧ ⟦a₂⟧ ⟦a₃⟧) : C s₁ s₂ s₃ := induction_on₂ s₁ s₂ fun l₁ l₂ => induction_on s₃ fun l₃ => H l₁ l₂ l₃ /-! ### extensionality -/ @[ext] theorem ext : ∀ {s t : Finmap β}, s.entries = t.entries → s = t | ⟨l₁, h₁⟩, ⟨l₂, _⟩, H => by congr @[simp] theorem ext_iff' {s t : Finmap β} : s.entries = t.entries ↔ s = t := Finmap.ext_iff.symm /-! ### mem -/ /-- The predicate `a ∈ s` means that `s` has a value associated to the key `a`. -/ instance : Membership α (Finmap β) := ⟨fun a s => a ∈ s.entries.keys⟩ theorem mem_def {a : α} {s : Finmap β} : a ∈ s ↔ a ∈ s.entries.keys := Iff.rfl @[simp] theorem mem_toFinmap {a : α} {s : AList β} : a ∈ toFinmap s ↔ a ∈ s := Iff.rfl /-! ### keys -/ /-- The set of keys of a finite map. -/ def keys (s : Finmap β) : Finset α := ⟨s.entries.keys, s.nodupKeys.nodup_keys⟩ @[simp] theorem keys_val (s : AList β) : (keys ⟦s⟧).val = s.keys := rfl @[simp] theorem keys_ext {s₁ s₂ : AList β} : keys ⟦s₁⟧ = keys ⟦s₂⟧ ↔ s₁.keys ~ s₂.keys := by simp [keys, AList.keys] theorem mem_keys {a : α} {s : Finmap β} : a ∈ s.keys ↔ a ∈ s := induction_on s fun _ => AList.mem_keys /-! ### empty -/ /-- The empty map. -/ instance : EmptyCollection (Finmap β) := ⟨⟨0, nodupKeys_nil⟩⟩ instance : Inhabited (Finmap β) := ⟨∅⟩ @[simp] theorem empty_toFinmap : (⟦∅⟧ : Finmap β) = ∅ := rfl @[simp] theorem toFinmap_nil [DecidableEq α] : ([].toFinmap : Finmap β) = ∅ := rfl theorem not_mem_empty {a : α} : a ∉ (∅ : Finmap β) := Multiset.not_mem_zero a @[simp] theorem keys_empty : (∅ : Finmap β).keys = ∅ := rfl /-! ### singleton -/ /-- The singleton map. -/ def singleton (a : α) (b : β a) : Finmap β := ⟦AList.singleton a b⟧ @[simp] theorem keys_singleton (a : α) (b : β a) : (singleton a b).keys = {a} := rfl @[simp] theorem mem_singleton (x y : α) (b : β y) : x ∈ singleton y b ↔ x = y := by simp only [singleton]; erw [mem_cons, mem_nil_iff, or_false_iff] section variable [DecidableEq α] instance decidableEq [∀ a, DecidableEq (β a)] : DecidableEq (Finmap β) | _, _ => decidable_of_iff _ Finmap.ext_iff.symm /-! ### lookup -/ /-- Look up the value associated to a key in a map. -/ def lookup (a : α) (s : Finmap β) : Option (β a) := liftOn s (AList.lookup a) fun _ _ => perm_lookup @[simp] theorem lookup_toFinmap (a : α) (s : AList β) : lookup a ⟦s⟧ = s.lookup a := rfl -- Porting note: renaming to `List.dlookup` since `List.lookup` already exists @[simp] theorem dlookup_list_toFinmap (a : α) (s : List (Sigma β)) : lookup a s.toFinmap = s.dlookup a := by rw [List.toFinmap, lookup_toFinmap, lookup_to_alist] @[simp] theorem lookup_empty (a) : lookup a (∅ : Finmap β) = none := rfl theorem lookup_isSome {a : α} {s : Finmap β} : (s.lookup a).isSome ↔ a ∈ s := induction_on s fun _ => AList.lookup_isSome theorem lookup_eq_none {a} {s : Finmap β} : lookup a s = none ↔ a ∉ s := induction_on s fun _ => AList.lookup_eq_none lemma mem_lookup_iff {s : Finmap β} {a : α} {b : β a} : b ∈ s.lookup a ↔ Sigma.mk a b ∈ s.entries := by rcases s with ⟨⟨l⟩, hl⟩; exact List.mem_dlookup_iff hl lemma lookup_eq_some_iff {s : Finmap β} {a : α} {b : β a} : s.lookup a = b ↔ Sigma.mk a b ∈ s.entries := mem_lookup_iff @[simp] lemma sigma_keys_lookup (s : Finmap β) : s.keys.sigma (fun i => (s.lookup i).toFinset) = ⟨s.entries, s.nodup_entries⟩ := by ext x have : x ∈ s.entries → x.1 ∈ s.keys := Multiset.mem_map_of_mem _ simpa [lookup_eq_some_iff] @[simp] theorem lookup_singleton_eq {a : α} {b : β a} : (singleton a b).lookup a = some b := by rw [singleton, lookup_toFinmap, AList.singleton, AList.lookup, dlookup_cons_eq] instance (a : α) (s : Finmap β) : Decidable (a ∈ s) := decidable_of_iff _ lookup_isSome theorem mem_iff {a : α} {s : Finmap β} : a ∈ s ↔ ∃ b, s.lookup a = some b := induction_on s fun s => Iff.trans List.mem_keys <| exists_congr fun _ => (mem_dlookup_iff s.nodupKeys).symm theorem mem_of_lookup_eq_some {a : α} {b : β a} {s : Finmap β} (h : s.lookup a = some b) : a ∈ s := mem_iff.mpr ⟨_, h⟩ theorem ext_lookup {s₁ s₂ : Finmap β} : (∀ x, s₁.lookup x = s₂.lookup x) → s₁ = s₂ := induction_on₂ s₁ s₂ fun s₁ s₂ h => by simp only [AList.lookup, lookup_toFinmap] at h rw [AList.toFinmap_eq] apply lookup_ext s₁.nodupKeys s₂.nodupKeys intro x y rw [h] /-- An equivalence between `Finmap β` and pairs `(keys : Finset α, lookup : ∀ a, Option (β a))` such that `(lookup a).isSome ↔ a ∈ keys`. -/ @[simps apply_coe_fst apply_coe_snd] def keysLookupEquiv : Finmap β ≃ { f : Finset α × (∀ a, Option (β a)) // ∀ i, (f.2 i).isSome ↔ i ∈ f.1 } where toFun s := ⟨(s.keys, fun i => s.lookup i), fun _ => lookup_isSome⟩ invFun f := mk (f.1.1.sigma fun i => (f.1.2 i).toFinset).val <| by refine Multiset.nodup_keys.1 ((Finset.nodup _).map_on ?_) simp only [Finset.mem_val, Finset.mem_sigma, Option.mem_toFinset, Option.mem_def] rintro ⟨i, x⟩ ⟨_, hx⟩ ⟨j, y⟩ ⟨_, hy⟩ (rfl : i = j) simpa using hx.symm.trans hy left_inv f := ext <| by simp right_inv := fun ⟨(s, f), hf⟩ => by dsimp only at hf ext · simp [keys, Multiset.keys, ← hf, Option.isSome_iff_exists] · simp (config := { contextual := true }) [lookup_eq_some_iff, ← hf] @[simp] lemma keysLookupEquiv_symm_apply_keys : ∀ f : {f : Finset α × (∀ a, Option (β a)) // ∀ i, (f.2 i).isSome ↔ i ∈ f.1}, (keysLookupEquiv.symm f).keys = f.1.1 := keysLookupEquiv.surjective.forall.2 fun _ => by simp only [Equiv.symm_apply_apply, keysLookupEquiv_apply_coe_fst] @[simp] lemma keysLookupEquiv_symm_apply_lookup : ∀ (f : {f : Finset α × (∀ a, Option (β a)) // ∀ i, (f.2 i).isSome ↔ i ∈ f.1}) a, (keysLookupEquiv.symm f).lookup a = f.1.2 a := keysLookupEquiv.surjective.forall.2 fun _ _ => by simp only [Equiv.symm_apply_apply, keysLookupEquiv_apply_coe_snd] /-! ### replace -/ /-- Replace a key with a given value in a finite map. If the key is not present it does nothing. -/ def replace (a : α) (b : β a) (s : Finmap β) : Finmap β := (liftOn s fun t => AList.toFinmap (AList.replace a b t)) fun _ _ p => toFinmap_eq.2 <| perm_replace p -- Porting note: explicit type required because of the ambiguity @[simp] theorem replace_toFinmap (a : α) (b : β a) (s : AList β) : replace a b ⟦s⟧ = (⟦s.replace a b⟧ : Finmap β) := by simp [replace] @[simp] theorem keys_replace (a : α) (b : β a) (s : Finmap β) : (replace a b s).keys = s.keys := induction_on s fun s => by simp @[simp] theorem mem_replace {a a' : α} {b : β a} {s : Finmap β} : a' ∈ replace a b s ↔ a' ∈ s := induction_on s fun s => by simp end /-! ### foldl -/ /-- Fold a commutative function over the key-value pairs in the map -/ def foldl {δ : Type w} (f : δ → ∀ a, β a → δ) (H : ∀ d a₁ b₁ a₂ b₂, f (f d a₁ b₁) a₂ b₂ = f (f d a₂ b₂) a₁ b₁) (d : δ) (m : Finmap β) : δ := m.entries.foldl (fun d s => f d s.1 s.2) (fun _ _ _ => H _ _ _ _ _) d /-- `any f s` returns `true` iff there exists a value `v` in `s` such that `f v = true`. -/ def any (f : ∀ x, β x → Bool) (s : Finmap β) : Bool := s.foldl (fun x y z => x || f y z) (fun _ _ _ _ => by simp_rw [Bool.or_assoc, Bool.or_comm, imp_true_iff]) false /-- `all f s` returns `true` iff `f v = true` for all values `v` in `s`. -/ def all (f : ∀ x, β x → Bool) (s : Finmap β) : Bool := s.foldl (fun x y z => x && f y z) (fun _ _ _ _ => by simp_rw [Bool.and_assoc, Bool.and_comm, imp_true_iff]) true /-! ### erase -/ section variable [DecidableEq α] /-- Erase a key from the map. If the key is not present it does nothing. -/ def erase (a : α) (s : Finmap β) : Finmap β := (liftOn s fun t => AList.toFinmap (AList.erase a t)) fun _ _ p => toFinmap_eq.2 <| perm_erase p @[simp] theorem erase_toFinmap (a : α) (s : AList β) : erase a ⟦s⟧ = AList.toFinmap (s.erase a) := by simp [erase] @[simp] theorem keys_erase_toFinset (a : α) (s : AList β) : keys ⟦s.erase a⟧ = (keys ⟦s⟧).erase a := by simp [Finset.erase, keys, AList.erase, keys_kerase] @[simp] theorem keys_erase (a : α) (s : Finmap β) : (erase a s).keys = s.keys.erase a := induction_on s fun s => by simp @[simp] theorem mem_erase {a a' : α} {s : Finmap β} : a' ∈ erase a s ↔ a' ≠ a ∧ a' ∈ s := induction_on s fun s => by simp theorem not_mem_erase_self {a : α} {s : Finmap β} : ¬a ∈ erase a s := by rw [mem_erase, not_and_or, not_not] left rfl @[simp] theorem lookup_erase (a) (s : Finmap β) : lookup a (erase a s) = none := induction_on s <| AList.lookup_erase a @[simp] theorem lookup_erase_ne {a a'} {s : Finmap β} (h : a ≠ a') : lookup a (erase a' s) = lookup a s := induction_on s fun _ => AList.lookup_erase_ne h theorem erase_erase {a a' : α} {s : Finmap β} : erase a (erase a' s) = erase a' (erase a s) := induction_on s fun s => ext (by simp only [AList.erase_erase, erase_toFinmap]) /-! ### sdiff -/ /-- `sdiff s s'` consists of all key-value pairs from `s` and `s'` where the keys are in `s` or `s'` but not both. -/ def sdiff (s s' : Finmap β) : Finmap β := s'.foldl (fun s x _ => s.erase x) (fun _ _ _ _ _ => erase_erase) s instance : SDiff (Finmap β) := ⟨sdiff⟩ /-! ### insert -/ /-- Insert a key-value pair into a finite map, replacing any existing pair with the same key. -/ def insert (a : α) (b : β a) (s : Finmap β) : Finmap β := (liftOn s fun t => AList.toFinmap (AList.insert a b t)) fun _ _ p => toFinmap_eq.2 <| perm_insert p @[simp] theorem insert_toFinmap (a : α) (b : β a) (s : AList β) : insert a b (AList.toFinmap s) = AList.toFinmap (s.insert a b) := by simp [insert] theorem insert_entries_of_neg {a : α} {b : β a} {s : Finmap β} : a ∉ s → (insert a b s).entries = ⟨a, b⟩ ::ₘ s.entries := induction_on s fun s h => by -- Porting note: `-insert_entries` required simp [AList.insert_entries_of_neg (mt mem_toFinmap.1 h), -insert_entries] @[simp] theorem mem_insert {a a' : α} {b' : β a'} {s : Finmap β} : a ∈ insert a' b' s ↔ a = a' ∨ a ∈ s := induction_on s AList.mem_insert @[simp] theorem lookup_insert {a} {b : β a} (s : Finmap β) : lookup a (insert a b s) = some b := induction_on s fun s => by simp only [insert_toFinmap, lookup_toFinmap, AList.lookup_insert] @[simp] theorem lookup_insert_of_ne {a a'} {b : β a} (s : Finmap β) (h : a' ≠ a) : lookup a' (insert a b s) = lookup a' s := induction_on s fun s => by simp only [insert_toFinmap, lookup_toFinmap, lookup_insert_ne h] @[simp] theorem insert_insert {a} {b b' : β a} (s : Finmap β) : (s.insert a b).insert a b' = s.insert a b' := induction_on s fun s => by simp only [insert_toFinmap, AList.insert_insert] theorem insert_insert_of_ne {a a'} {b : β a} {b' : β a'} (s : Finmap β) (h : a ≠ a') : (s.insert a b).insert a' b' = (s.insert a' b').insert a b := induction_on s fun s => by simp only [insert_toFinmap, AList.toFinmap_eq, AList.insert_insert_of_ne _ h] theorem toFinmap_cons (a : α) (b : β a) (xs : List (Sigma β)) : List.toFinmap (⟨a, b⟩ :: xs) = insert a b xs.toFinmap := rfl theorem mem_list_toFinmap (a : α) (xs : List (Sigma β)) : a ∈ xs.toFinmap ↔ ∃ b : β a, Sigma.mk a b ∈ xs := by -- Porting note: golfed induction' xs with x xs · simp only [toFinmap_nil, not_mem_empty, find?, not_mem_nil, exists_false] cases' x with fst_i snd_i -- Porting note: `Sigma.mk.inj_iff` required because `simp` behaves differently simp only [toFinmap_cons, *, exists_or, mem_cons, mem_insert, exists_and_left, Sigma.mk.inj_iff] refine (or_congr_left <| and_iff_left_of_imp ?_).symm rintro rfl simp only [exists_eq, heq_iff_eq] @[simp] theorem insert_singleton_eq {a : α} {b b' : β a} : insert a b (singleton a b') = singleton a b := by simp only [singleton, Finmap.insert_toFinmap, AList.insert_singleton_eq] /-! ### extract -/ /-- Erase a key from the map, and return the corresponding value, if found. -/ def extract (a : α) (s : Finmap β) : Option (β a) × Finmap β := (liftOn s fun t => Prod.map id AList.toFinmap (AList.extract a t)) fun s₁ s₂ p => by simp [perm_lookup p, toFinmap_eq, perm_erase p] @[simp] theorem extract_eq_lookup_erase (a : α) (s : Finmap β) : extract a s = (lookup a s, erase a s) := induction_on s fun s => by simp [extract] /-! ### union -/ /-- `s₁ ∪ s₂` is the key-based union of two finite maps. It is left-biased: if there exists an `a ∈ s₁`, `lookup a (s₁ ∪ s₂) = lookup a s₁`. -/ def union (s₁ s₂ : Finmap β) : Finmap β := (liftOn₂ s₁ s₂ fun s₁ s₂ => (AList.toFinmap (s₁ ∪ s₂))) fun _ _ _ _ p₁₃ p₂₄ => toFinmap_eq.mpr <| perm_union p₁₃ p₂₄ instance : Union (Finmap β) := ⟨union⟩ @[simp] theorem mem_union {a} {s₁ s₂ : Finmap β} : a ∈ s₁ ∪ s₂ ↔ a ∈ s₁ ∨ a ∈ s₂ := induction_on₂ s₁ s₂ fun _ _ => AList.mem_union @[simp] theorem union_toFinmap (s₁ s₂ : AList β) : (toFinmap s₁) ∪ (toFinmap s₂) = toFinmap (s₁ ∪ s₂) := by simp [(· ∪ ·), union] theorem keys_union {s₁ s₂ : Finmap β} : (s₁ ∪ s₂).keys = s₁.keys ∪ s₂.keys := induction_on₂ s₁ s₂ fun s₁ s₂ => Finset.ext <| by simp [keys] @[simp] theorem lookup_union_left {a} {s₁ s₂ : Finmap β} : a ∈ s₁ → lookup a (s₁ ∪ s₂) = lookup a s₁ := induction_on₂ s₁ s₂ fun _ _ => AList.lookup_union_left @[simp] theorem lookup_union_right {a} {s₁ s₂ : Finmap β} : a ∉ s₁ → lookup a (s₁ ∪ s₂) = lookup a s₂ := induction_on₂ s₁ s₂ fun _ _ => AList.lookup_union_right theorem lookup_union_left_of_not_in {a} {s₁ s₂ : Finmap β} (h : a ∉ s₂) : lookup a (s₁ ∪ s₂) = lookup a s₁ := by by_cases h' : a ∈ s₁ · rw [lookup_union_left h'] · rw [lookup_union_right h', lookup_eq_none.mpr h, lookup_eq_none.mpr h'] -- @[simp] -- Porting note (#10618): simp can prove this theorem mem_lookup_union {a} {b : β a} {s₁ s₂ : Finmap β} : b ∈ lookup a (s₁ ∪ s₂) ↔ b ∈ lookup a s₁ ∨ a ∉ s₁ ∧ b ∈ lookup a s₂ := induction_on₂ s₁ s₂ fun _ _ => AList.mem_lookup_union theorem mem_lookup_union_middle {a} {b : β a} {s₁ s₂ s₃ : Finmap β} : b ∈ lookup a (s₁ ∪ s₃) → a ∉ s₂ → b ∈ lookup a (s₁ ∪ s₂ ∪ s₃) := induction_on₃ s₁ s₂ s₃ fun _ _ _ => AList.mem_lookup_union_middle theorem insert_union {a} {b : β a} {s₁ s₂ : Finmap β} : insert a b (s₁ ∪ s₂) = insert a b s₁ ∪ s₂ := induction_on₂ s₁ s₂ fun a₁ a₂ => by simp [AList.insert_union] theorem union_assoc {s₁ s₂ s₃ : Finmap β} : s₁ ∪ s₂ ∪ s₃ = s₁ ∪ (s₂ ∪ s₃) := induction_on₃ s₁ s₂ s₃ fun s₁ s₂ s₃ => by simp only [AList.toFinmap_eq, union_toFinmap, AList.union_assoc] @[simp] theorem empty_union {s₁ : Finmap β} : ∅ ∪ s₁ = s₁ := induction_on s₁ fun s₁ => by rw [← empty_toFinmap] simp [-empty_toFinmap, AList.toFinmap_eq, union_toFinmap, AList.union_assoc] @[simp] theorem union_empty {s₁ : Finmap β} : s₁ ∪ ∅ = s₁ := induction_on s₁ fun s₁ => by rw [← empty_toFinmap] simp [-empty_toFinmap, AList.toFinmap_eq, union_toFinmap, AList.union_assoc] theorem erase_union_singleton (a : α) (b : β a) (s : Finmap β) (h : s.lookup a = some b) : s.erase a ∪ singleton a b = s := ext_lookup fun x => by by_cases h' : x = a · subst a rw [lookup_union_right not_mem_erase_self, lookup_singleton_eq, h] · have : x ∉ singleton a b := by rwa [mem_singleton] rw [lookup_union_left_of_not_in this, lookup_erase_ne h'] end /-! ### Disjoint -/ /-- `Disjoint s₁ s₂` holds if `s₁` and `s₂` have no keys in common. -/ def Disjoint (s₁ s₂ : Finmap β) : Prop := ∀ x ∈ s₁, ¬x ∈ s₂ theorem disjoint_empty (x : Finmap β) : Disjoint ∅ x := nofun @[symm] theorem Disjoint.symm (x y : Finmap β) (h : Disjoint x y) : Disjoint y x := fun p hy hx => h p hx hy theorem Disjoint.symm_iff (x y : Finmap β) : Disjoint x y ↔ Disjoint y x := ⟨Disjoint.symm x y, Disjoint.symm y x⟩ section variable [DecidableEq α] instance : DecidableRel (@Disjoint α β) := fun x y => by dsimp only [Disjoint]; infer_instance theorem disjoint_union_left (x y z : Finmap β) : Disjoint (x ∪ y) z ↔ Disjoint x z ∧ Disjoint y z := by simp [Disjoint, Finmap.mem_union, or_imp, forall_and] theorem disjoint_union_right (x y z : Finmap β) : Disjoint x (y ∪ z) ↔ Disjoint x y ∧ Disjoint x z := by rw [Disjoint.symm_iff, disjoint_union_left, Disjoint.symm_iff _ x, Disjoint.symm_iff _ x] theorem union_comm_of_disjoint {s₁ s₂ : Finmap β} : Disjoint s₁ s₂ → s₁ ∪ s₂ = s₂ ∪ s₁ := induction_on₂ s₁ s₂ fun s₁ s₂ => by intro h simp only [AList.toFinmap_eq, union_toFinmap, AList.union_comm_of_disjoint h] theorem union_cancel {s₁ s₂ s₃ : Finmap β} (h : Disjoint s₁ s₃) (h' : Disjoint s₂ s₃) : s₁ ∪ s₃ = s₂ ∪ s₃ ↔ s₁ = s₂ := ⟨fun h'' => by apply ext_lookup intro x have : (s₁ ∪ s₃).lookup x = (s₂ ∪ s₃).lookup x := h'' ▸ rfl by_cases hs₁ : x ∈ s₁ · rwa [lookup_union_left hs₁, lookup_union_left_of_not_in (h _ hs₁)] at this · by_cases hs₂ : x ∈ s₂ · rwa [lookup_union_left_of_not_in (h' _ hs₂), lookup_union_left hs₂] at this · rw [lookup_eq_none.mpr hs₁, lookup_eq_none.mpr hs₂], fun h => h ▸ rfl⟩ end end Finmap
Data\HashMap.lean
/- Copyright (c) 2022 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison As `HashMap` has been completely reimplemented in `Batteries`, nothing from the mathlib3 file `data.hash_map` is reflected here. The porting header is just here to mark that no further work on `data.hash_map` is desired. -/ import Batteries.Data.HashMap.Basic import Batteries.Data.RBMap.Basic /-! # Additional API for `HashMap` and `RBSet`. These should be replaced by proper implementations in Batteries. -/ set_option autoImplicit true namespace Batteries.HashMap -- not an exact match, the Lean3 version was dependently-typed variable [BEq α] [Hashable α] /-- The list of keys in a `HashMap`. -/ @[deprecated "This declaration is unused in Mathlib: if you need it, \ please file an issue in the Batteries repository." (since := "2024-06-12")] def keys (m : HashMap α β) : List α := m.fold (fun ks k _ => k :: ks) [] /-- The list of values in a `HashMap`. -/ @[deprecated "This declaration is unused in Mathlib: if you need it, \ please file an issue in the Batteries repository." (since := "2024-06-12")] def values (m : HashMap α β) : List β := m.fold (fun vs _ v => v :: vs) [] /-- Add a value to a `HashMap α (List β)` viewed as a multimap. -/ @[deprecated "This declaration is unused in Mathlib: if you need it, \ please file an issue in the Batteries repository." (since := "2024-06-12")] def consVal (self : HashMap α (List β)) (a : α) (b : β) : HashMap α (List β) := match self.find? a with | none => self.insert a [b] | some L => self.insert a (b::L) end Batteries.HashMap namespace Batteries.RBSet /-- Insert all elements of a list into an `RBSet`. -/ @[deprecated "This declaration is unused in Mathlib: if you need it, \ please file an issue in the Batteries repository." (since := "2024-06-12")] def insertList {cmp} (m : RBSet α cmp) (L : List α) : RBSet α cmp := L.foldl (fun m a => m.insert a) m end Batteries.RBSet
Data\Holor.lean
/- Copyright (c) 2018 Alexander Bentkamp. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alexander Bentkamp -/ import Mathlib.Algebra.BigOperators.Group.Finset import Mathlib.Algebra.Module.Pi /-! # Basic properties of holors Holors are indexed collections of tensor coefficients. Confusingly, they are often called tensors in physics and in the neural network community. A holor is simply a multidimensional array of values. The size of a holor is specified by a `List ℕ`, whose length is called the dimension of the holor. The tensor product of `x₁ : Holor α ds₁` and `x₂ : Holor α ds₂` is the holor given by `(x₁ ⊗ x₂) (i₁ ++ i₂) = x₁ i₁ * x₂ i₂`. A holor is "of rank at most 1" if it is a tensor product of one-dimensional holors. The CP rank of a holor `x` is the smallest N such that `x` is the sum of N holors of rank at most 1. Based on the tensor library found in <https://www.isa-afp.org/entries/Deep_Learning.html> ## References * <https://en.wikipedia.org/wiki/Tensor_rank_decomposition> -/ universe u open List /-- `HolorIndex ds` is the type of valid index tuples used to identify an entry of a holor of dimensions `ds`. -/ def HolorIndex (ds : List ℕ) : Type := { is : List ℕ // Forall₂ (· < ·) is ds } namespace HolorIndex variable {ds₁ ds₂ ds₃ : List ℕ} def take : ∀ {ds₁ : List ℕ}, HolorIndex (ds₁ ++ ds₂) → HolorIndex ds₁ | ds, is => ⟨List.take (length ds) is.1, forall₂_take_append is.1 ds ds₂ is.2⟩ def drop : ∀ {ds₁ : List ℕ}, HolorIndex (ds₁ ++ ds₂) → HolorIndex ds₂ | ds, is => ⟨List.drop (length ds) is.1, forall₂_drop_append is.1 ds ds₂ is.2⟩ theorem cast_type (is : List ℕ) (eq : ds₁ = ds₂) (h : Forall₂ (· < ·) is ds₁) : (cast (congr_arg HolorIndex eq) ⟨is, h⟩).val = is := by subst eq; rfl def assocRight : HolorIndex (ds₁ ++ ds₂ ++ ds₃) → HolorIndex (ds₁ ++ (ds₂ ++ ds₃)) := cast (congr_arg HolorIndex (append_assoc ds₁ ds₂ ds₃)) def assocLeft : HolorIndex (ds₁ ++ (ds₂ ++ ds₃)) → HolorIndex (ds₁ ++ ds₂ ++ ds₃) := cast (congr_arg HolorIndex (append_assoc ds₁ ds₂ ds₃).symm) theorem take_take : ∀ t : HolorIndex (ds₁ ++ ds₂ ++ ds₃), t.assocRight.take = t.take.take | ⟨is, h⟩ => Subtype.eq <| by simp [assocRight, take, cast_type, List.take_take, Nat.le_add_right, min_eq_left] theorem drop_take : ∀ t : HolorIndex (ds₁ ++ ds₂ ++ ds₃), t.assocRight.drop.take = t.take.drop | ⟨is, h⟩ => Subtype.eq (by simp [assocRight, take, drop, cast_type, List.drop_take]) theorem drop_drop : ∀ t : HolorIndex (ds₁ ++ ds₂ ++ ds₃), t.assocRight.drop.drop = t.drop | ⟨is, h⟩ => Subtype.eq (by simp [add_comm, assocRight, drop, cast_type, List.drop_drop]) end HolorIndex /-- Holor (indexed collections of tensor coefficients) -/ def Holor (α : Type u) (ds : List ℕ) := HolorIndex ds → α namespace Holor variable {α : Type} {d : ℕ} {ds : List ℕ} {ds₁ : List ℕ} {ds₂ : List ℕ} {ds₃ : List ℕ} instance [Inhabited α] : Inhabited (Holor α ds) := ⟨fun _ => default⟩ instance [Zero α] : Zero (Holor α ds) := ⟨fun _ => 0⟩ instance [Add α] : Add (Holor α ds) := ⟨fun x y t => x t + y t⟩ instance [Neg α] : Neg (Holor α ds) := ⟨fun a t => -a t⟩ instance [AddSemigroup α] : AddSemigroup (Holor α ds) := Pi.addSemigroup instance [AddCommSemigroup α] : AddCommSemigroup (Holor α ds) := Pi.addCommSemigroup instance [AddMonoid α] : AddMonoid (Holor α ds) := Pi.addMonoid instance [AddCommMonoid α] : AddCommMonoid (Holor α ds) := Pi.addCommMonoid instance [AddGroup α] : AddGroup (Holor α ds) := Pi.addGroup instance [AddCommGroup α] : AddCommGroup (Holor α ds) := Pi.addCommGroup -- scalar product instance [Mul α] : SMul α (Holor α ds) := ⟨fun a x => fun t => a * x t⟩ instance [Semiring α] : Module α (Holor α ds) := Pi.module _ _ _ /-- The tensor product of two holors. -/ def mul [Mul α] (x : Holor α ds₁) (y : Holor α ds₂) : Holor α (ds₁ ++ ds₂) := fun t => x t.take * y t.drop local infixl:70 " ⊗ " => mul theorem cast_type (eq : ds₁ = ds₂) (a : Holor α ds₁) : cast (congr_arg (Holor α) eq) a = fun t => a (cast (congr_arg HolorIndex eq.symm) t) := by subst eq; rfl def assocRight : Holor α (ds₁ ++ ds₂ ++ ds₃) → Holor α (ds₁ ++ (ds₂ ++ ds₃)) := cast (congr_arg (Holor α) (append_assoc ds₁ ds₂ ds₃)) def assocLeft : Holor α (ds₁ ++ (ds₂ ++ ds₃)) → Holor α (ds₁ ++ ds₂ ++ ds₃) := cast (congr_arg (Holor α) (append_assoc ds₁ ds₂ ds₃).symm) theorem mul_assoc0 [Semigroup α] (x : Holor α ds₁) (y : Holor α ds₂) (z : Holor α ds₃) : x ⊗ y ⊗ z = (x ⊗ (y ⊗ z)).assocLeft := funext fun t : HolorIndex (ds₁ ++ ds₂ ++ ds₃) => by rw [assocLeft] unfold mul rw [mul_assoc, ← HolorIndex.take_take, ← HolorIndex.drop_take, ← HolorIndex.drop_drop, cast_type] · rfl rw [append_assoc] theorem mul_assoc [Semigroup α] (x : Holor α ds₁) (y : Holor α ds₂) (z : Holor α ds₃) : HEq (mul (mul x y) z) (mul x (mul y z)) := by simp [cast_heq, mul_assoc0, assocLeft] theorem mul_left_distrib [Distrib α] (x : Holor α ds₁) (y : Holor α ds₂) (z : Holor α ds₂) : x ⊗ (y + z) = x ⊗ y + x ⊗ z := funext fun t => left_distrib (x t.take) (y t.drop) (z t.drop) theorem mul_right_distrib [Distrib α] (x : Holor α ds₁) (y : Holor α ds₁) (z : Holor α ds₂) : (x + y) ⊗ z = x ⊗ z + y ⊗ z := funext fun t => add_mul (x t.take) (y t.take) (z t.drop) @[simp] nonrec theorem zero_mul {α : Type} [Ring α] (x : Holor α ds₂) : (0 : Holor α ds₁) ⊗ x = 0 := funext fun t => zero_mul (x (HolorIndex.drop t)) @[simp] nonrec theorem mul_zero {α : Type} [Ring α] (x : Holor α ds₁) : x ⊗ (0 : Holor α ds₂) = 0 := funext fun t => mul_zero (x (HolorIndex.take t)) theorem mul_scalar_mul [Monoid α] (x : Holor α []) (y : Holor α ds) : x ⊗ y = x ⟨[], Forall₂.nil⟩ • y := by simp (config := { unfoldPartialApp := true }) [mul, SMul.smul, HolorIndex.take, HolorIndex.drop, HSMul.hSMul] -- holor slices /-- A slice is a subholor consisting of all entries with initial index i. -/ def slice (x : Holor α (d :: ds)) (i : ℕ) (h : i < d) : Holor α ds := fun is : HolorIndex ds => x ⟨i :: is.1, Forall₂.cons h is.2⟩ /-- The 1-dimensional "unit" holor with 1 in the `j`th position. -/ def unitVec [Monoid α] [AddMonoid α] (d : ℕ) (j : ℕ) : Holor α [d] := fun ti => if ti.1 = [j] then 1 else 0 theorem holor_index_cons_decomp (p : HolorIndex (d :: ds) → Prop) : ∀ t : HolorIndex (d :: ds), (∀ i is, ∀ h : t.1 = i :: is, p ⟨i :: is, by rw [← h]; exact t.2⟩) → p t | ⟨[], hforall₂⟩, _ => absurd (forall₂_nil_left_iff.1 hforall₂) (cons_ne_nil d ds) | ⟨i :: is, _⟩, hp => hp i is rfl /-- Two holors are equal if all their slices are equal. -/ theorem slice_eq (x : Holor α (d :: ds)) (y : Holor α (d :: ds)) (h : slice x = slice y) : x = y := funext fun t : HolorIndex (d :: ds) => holor_index_cons_decomp (fun t => x t = y t) t fun i is hiis => have hiisdds : Forall₂ (· < ·) (i :: is) (d :: ds) := by rw [← hiis]; exact t.2 have hid : i < d := (forall₂_cons.1 hiisdds).1 have hisds : Forall₂ (· < ·) is ds := (forall₂_cons.1 hiisdds).2 calc x ⟨i :: is, _⟩ = slice x i hid ⟨is, hisds⟩ := congr_arg (fun t => x t) (Subtype.eq rfl) _ = slice y i hid ⟨is, hisds⟩ := by rw [h] _ = y ⟨i :: is, _⟩ := congr_arg (fun t => y t) (Subtype.eq rfl) theorem slice_unitVec_mul [Ring α] {i : ℕ} {j : ℕ} (hid : i < d) (x : Holor α ds) : slice (unitVec d j ⊗ x) i hid = if i = j then x else 0 := funext fun t : HolorIndex ds => if h : i = j then by simp [slice, mul, HolorIndex.take, unitVec, HolorIndex.drop, h] else by simp [slice, mul, HolorIndex.take, unitVec, HolorIndex.drop, h]; rfl theorem slice_add [Add α] (i : ℕ) (hid : i < d) (x : Holor α (d :: ds)) (y : Holor α (d :: ds)) : slice x i hid + slice y i hid = slice (x + y) i hid := funext fun t => by simp [slice, (· + ·), Add.add] theorem slice_zero [Zero α] (i : ℕ) (hid : i < d) : slice (0 : Holor α (d :: ds)) i hid = 0 := rfl theorem slice_sum [AddCommMonoid α] {β : Type} (i : ℕ) (hid : i < d) (s : Finset β) (f : β → Holor α (d :: ds)) : (∑ x ∈ s, slice (f x) i hid) = slice (∑ x ∈ s, f x) i hid := by letI := Classical.decEq β refine Finset.induction_on s ?_ ?_ · simp [slice_zero] · intro _ _ h_not_in ih rw [Finset.sum_insert h_not_in, ih, slice_add, Finset.sum_insert h_not_in] /-- The original holor can be recovered from its slices by multiplying with unit vectors and summing up. -/ @[simp] theorem sum_unitVec_mul_slice [Ring α] (x : Holor α (d :: ds)) : (∑ i ∈ (Finset.range d).attach, unitVec d i ⊗ slice x i (Nat.succ_le_of_lt (Finset.mem_range.1 i.prop))) = x := by apply slice_eq _ _ _ ext i hid rw [← slice_sum] simp only [slice_unitVec_mul hid] rw [Finset.sum_eq_single (Subtype.mk i <| Finset.mem_range.2 hid)] · simp · intro (b : { x // x ∈ Finset.range d }) (_ : b ∈ (Finset.range d).attach) (hbi : b ≠ ⟨i, _⟩) have hbi' : i ≠ b := by simpa only [Ne, Subtype.ext_iff, Subtype.coe_mk] using hbi.symm simp [hbi'] · intro (hid' : Subtype.mk i _ ∉ Finset.attach (Finset.range d)) exfalso exact absurd (Finset.mem_attach _ _) hid' -- CP rank /-- `CPRankMax1 x` means `x` has CP rank at most 1, that is, it is the tensor product of 1-dimensional holors. -/ inductive CPRankMax1 [Mul α] : ∀ {ds}, Holor α ds → Prop | nil (x : Holor α []) : CPRankMax1 x | cons {d} {ds} (x : Holor α [d]) (y : Holor α ds) : CPRankMax1 y → CPRankMax1 (x ⊗ y) /-- `CPRankMax N x` means `x` has CP rank at most `N`, that is, it can be written as the sum of N holors of rank at most 1. -/ inductive CPRankMax [Mul α] [AddMonoid α] : ℕ → ∀ {ds}, Holor α ds → Prop | zero {ds} : CPRankMax 0 (0 : Holor α ds) | succ (n) {ds} (x : Holor α ds) (y : Holor α ds) : CPRankMax1 x → CPRankMax n y → CPRankMax (n + 1) (x + y) theorem cprankMax_nil [Monoid α] [AddMonoid α] (x : Holor α nil) : CPRankMax 1 x := by have h := CPRankMax.succ 0 x 0 (CPRankMax1.nil x) CPRankMax.zero rwa [add_zero x, zero_add] at h theorem cprankMax_1 [Monoid α] [AddMonoid α] {x : Holor α ds} (h : CPRankMax1 x) : CPRankMax 1 x := by have h' := CPRankMax.succ 0 x 0 h CPRankMax.zero rwa [zero_add, add_zero] at h' theorem cprankMax_add [Monoid α] [AddMonoid α] : ∀ {m : ℕ} {n : ℕ} {x : Holor α ds} {y : Holor α ds}, CPRankMax m x → CPRankMax n y → CPRankMax (m + n) (x + y) | 0, n, x, y, hx, hy => by match hx with | CPRankMax.zero => simp only [zero_add, hy] | m + 1, n, _, y, CPRankMax.succ _ x₁ x₂ hx₁ hx₂, hy => by simp only [add_comm, add_assoc] apply CPRankMax.succ · assumption · -- Porting note: Single line is added. simp only [Nat.add_eq, add_zero, add_comm n m] exact cprankMax_add hx₂ hy theorem cprankMax_mul [Ring α] : ∀ (n : ℕ) (x : Holor α [d]) (y : Holor α ds), CPRankMax n y → CPRankMax n (x ⊗ y) | 0, x, _, CPRankMax.zero => by simp [mul_zero x, CPRankMax.zero] | n + 1, x, _, CPRankMax.succ _ y₁ y₂ hy₁ hy₂ => by rw [mul_left_distrib] rw [Nat.add_comm] apply cprankMax_add · exact cprankMax_1 (CPRankMax1.cons _ _ hy₁) · exact cprankMax_mul _ x y₂ hy₂ theorem cprankMax_sum [Ring α] {β} {n : ℕ} (s : Finset β) (f : β → Holor α ds) : (∀ x ∈ s, CPRankMax n (f x)) → CPRankMax (s.card * n) (∑ x ∈ s, f x) := letI := Classical.decEq β Finset.induction_on s (by simp [CPRankMax.zero]) (by intro x s (h_x_notin_s : x ∉ s) ih h_cprank simp only [Finset.sum_insert h_x_notin_s, Finset.card_insert_of_not_mem h_x_notin_s] rw [Nat.right_distrib] simp only [Nat.one_mul, Nat.add_comm] have ih' : CPRankMax (Finset.card s * n) (∑ x ∈ s, f x) := by apply ih intro (x : β) (h_x_in_s : x ∈ s) simp only [h_cprank, Finset.mem_insert_of_mem, h_x_in_s] exact cprankMax_add (h_cprank x (Finset.mem_insert_self x s)) ih') theorem cprankMax_upper_bound [Ring α] : ∀ {ds}, ∀ x : Holor α ds, CPRankMax ds.prod x | [], x => cprankMax_nil x | d :: ds, x => by have h_summands : ∀ i : { x // x ∈ Finset.range d }, CPRankMax ds.prod (unitVec d i.1 ⊗ slice x i.1 (mem_range.1 i.2)) := fun i => cprankMax_mul _ _ _ (cprankMax_upper_bound (slice x i.1 (mem_range.1 i.2))) have h_dds_prod : (List.cons d ds).prod = Finset.card (Finset.range d) * prod ds := by simp [Finset.card_range] have : CPRankMax (Finset.card (Finset.attach (Finset.range d)) * prod ds) (∑ i ∈ Finset.attach (Finset.range d), unitVec d i.val ⊗ slice x i.val (mem_range.1 i.2)) := cprankMax_sum (Finset.range d).attach _ fun i _ => h_summands i have h_cprankMax_sum : CPRankMax (Finset.card (Finset.range d) * prod ds) (∑ i ∈ Finset.attach (Finset.range d), unitVec d i.val ⊗ slice x i.val (mem_range.1 i.2)) := by rwa [Finset.card_attach] at this rw [← sum_unitVec_mul_slice x] rw [h_dds_prod] exact h_cprankMax_sum /-- The CP rank of a holor `x`: the smallest N such that `x` can be written as the sum of N holors of rank at most 1. -/ noncomputable def cprank [Ring α] (x : Holor α ds) : Nat := @Nat.find (fun n => CPRankMax n x) (Classical.decPred _) ⟨ds.prod, cprankMax_upper_bound x⟩ theorem cprank_upper_bound [Ring α] : ∀ {ds}, ∀ x : Holor α ds, cprank x ≤ ds.prod := fun {ds} x => letI := Classical.decPred fun n : ℕ => CPRankMax n x Nat.find_min' ⟨ds.prod, show (fun n => CPRankMax n x) ds.prod from cprankMax_upper_bound x⟩ (cprankMax_upper_bound x) end Holor
Data\Opposite.lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Reid Barton, Simon Hudon, Kenny Lau -/ import Mathlib.Logic.Equiv.Defs /-! # Opposites In this file we define a structure `Opposite α` containing a single field of type `α` and two bijections `op : α → αᵒᵖ` and `unop : αᵒᵖ → α`. If `α` is a category, then `αᵒᵖ` is the opposite category, with all arrows reversed. -/ universe v u -- morphism levels before object levels. See note [CategoryTheory universes]. variable (α : Sort u) -- Porting note: in mathlib, `opposite α` was a type synonym for `α`, but if we did -- the same in Lean4, one could write problematic definitions like: -- example (X : C) : Cᵒᵖ := X -- example {X Y : C} (f : X ⟶ Y): op Y ⟶ op X := f /-- The type of objects of the opposite of `α`; used to define the opposite category. Now that Lean 4 supports definitional eta equality for records, both `unop (op X) = X` and `op (unop X) = X` are definitional equalities. -/ structure Opposite := /-- The canonical map `α → αᵒᵖ`. -/ op :: /-- The canonical map `αᵒᵖ → α`. -/ unop : α attribute [pp_nodot] Opposite.unop /-- Make sure that `Opposite.op a` is pretty-printed as `op a` instead of `{ unop := a }` or `⟨a⟩`. -/ @[app_unexpander Opposite.op] protected def Opposite.unexpander_op : Lean.PrettyPrinter.Unexpander | s => pure s @[inherit_doc] notation:max -- Use a high right binding power (like that of postfix ⁻¹) so that, for example, -- `Presheaf Cᵒᵖ` parses as `Presheaf (Cᵒᵖ)` and not `(Presheaf C)ᵒᵖ`. α "ᵒᵖ" => Opposite α namespace Opposite variable {α} theorem op_injective : Function.Injective (op : α → αᵒᵖ) := fun _ _ => congr_arg Opposite.unop theorem unop_injective : Function.Injective (unop : αᵒᵖ → α) := fun ⟨_⟩⟨_⟩ => by simp @[simp] theorem op_unop (x : αᵒᵖ) : op (unop x) = x := rfl theorem unop_op (x : α) : unop (op x) = x := rfl -- We could prove these by `Iff.rfl`, but that would make these eligible for `dsimp`. That would be -- a bad idea because `Opposite` is irreducible. theorem op_inj_iff (x y : α) : op x = op y ↔ x = y := op_injective.eq_iff @[simp] theorem unop_inj_iff (x y : αᵒᵖ) : unop x = unop y ↔ x = y := unop_injective.eq_iff /-- The type-level equivalence between a type and its opposite. -/ def equivToOpposite : α ≃ αᵒᵖ where toFun := op invFun := unop left_inv := unop_op right_inv := op_unop theorem op_surjective : Function.Surjective (op : α → αᵒᵖ) := equivToOpposite.surjective theorem unop_surjective : Function.Surjective (unop : αᵒᵖ → α) := equivToOpposite.symm.surjective @[simp] theorem equivToOpposite_coe : (equivToOpposite : α → αᵒᵖ) = op := rfl @[simp] theorem equivToOpposite_symm_coe : (equivToOpposite.symm : αᵒᵖ → α) = unop := rfl theorem op_eq_iff_eq_unop {x : α} {y} : op x = y ↔ x = unop y := equivToOpposite.apply_eq_iff_eq_symm_apply theorem unop_eq_iff_eq_op {x} {y : α} : unop x = y ↔ x = op y := equivToOpposite.symm.apply_eq_iff_eq_symm_apply instance [Inhabited α] : Inhabited αᵒᵖ := ⟨op default⟩ instance [Nonempty α] : Nonempty αᵒᵖ := Nonempty.map op ‹_› instance [Subsingleton α] : Subsingleton αᵒᵖ := unop_injective.subsingleton /-- A recursor for `Opposite`. The `@[induction_eliminator]` attribute makes it the default induction principle for `Opposite` so you don't need to use `induction x using Opposite.rec'`. -/ @[simp, induction_eliminator] protected def rec' {F : αᵒᵖ → Sort v} (h : ∀ X, F (op X)) : ∀ X, F X := fun X => h (unop X) end Opposite
Data\Part.lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Jeremy Avigad, Simon Hudon -/ import Mathlib.Data.Set.Subsingleton import Mathlib.Logic.Equiv.Defs import Mathlib.Algebra.Group.Defs /-! # Partial values of a type This file defines `Part α`, the partial values of a type. `o : Part α` carries a proposition `o.Dom`, its domain, along with a function `get : o.Dom → α`, its value. The rule is then that every partial value has a value but, to access it, you need to provide a proof of the domain. `Part α` behaves the same as `Option α` except that `o : Option α` is decidably `none` or `some a` for some `a : α`, while the domain of `o : Part α` doesn't have to be decidable. That means you can translate back and forth between a partial value with a decidable domain and an option, and `Option α` and `Part α` are classically equivalent. In general, `Part α` is bigger than `Option α`. In current mathlib, `Part ℕ`, aka `PartENat`, is used to move decidability of the order to decidability of `PartENat.find` (which is the smallest natural satisfying a predicate, or `∞` if there's none). ## Main declarations `Option`-like declarations: * `Part.none`: The partial value whose domain is `False`. * `Part.some a`: The partial value whose domain is `True` and whose value is `a`. * `Part.ofOption`: Converts an `Option α` to a `Part α` by sending `none` to `none` and `some a` to `some a`. * `Part.toOption`: Converts a `Part α` with a decidable domain to an `Option α`. * `Part.equivOption`: Classical equivalence between `Part α` and `Option α`. Monadic structure: * `Part.bind`: `o.bind f` has value `(f (o.get _)).get _` (`f o` morally) and is defined when `o` and `f (o.get _)` are defined. * `Part.map`: Maps the value and keeps the same domain. Other: * `Part.restrict`: `Part.restrict p o` replaces the domain of `o : Part α` by `p : Prop` so long as `p → o.Dom`. * `Part.assert`: `assert p f` appends `p` to the domains of the values of a partial function. * `Part.unwrap`: Gets the value of a partial value regardless of its domain. Unsound. ## Notation For `a : α`, `o : Part α`, `a ∈ o` means that `o` is defined and equal to `a`. Formally, it means `o.Dom` and `o.get _ = a`. -/ open Function /-- `Part α` is the type of "partial values" of type `α`. It is similar to `Option α` except the domain condition can be an arbitrary proposition, not necessarily decidable. -/ structure Part.{u} (α : Type u) : Type u where /-- The domain of a partial value -/ Dom : Prop /-- Extract a value from a partial value given a proof of `Dom` -/ get : Dom → α namespace Part variable {α : Type*} {β : Type*} {γ : Type*} /-- Convert a `Part α` with a decidable domain to an option -/ def toOption (o : Part α) [Decidable o.Dom] : Option α := if h : Dom o then some (o.get h) else none @[simp] lemma toOption_isSome (o : Part α) [Decidable o.Dom] : o.toOption.isSome ↔ o.Dom := by by_cases h : o.Dom <;> simp [h, toOption] @[simp] lemma toOption_eq_none (o : Part α) [Decidable o.Dom] : o.toOption = none ↔ ¬o.Dom := by by_cases h : o.Dom <;> simp [h, toOption] @[deprecated (since := "2024-06-20")] alias toOption_isNone := toOption_eq_none /-- `Part` extensionality -/ theorem ext' : ∀ {o p : Part α}, (o.Dom ↔ p.Dom) → (∀ h₁ h₂, o.get h₁ = p.get h₂) → o = p | ⟨od, o⟩, ⟨pd, p⟩, H1, H2 => by have t : od = pd := propext H1 cases t; rw [show o = p from funext fun p => H2 p p] /-- `Part` eta expansion -/ @[simp] theorem eta : ∀ o : Part α, (⟨o.Dom, fun h => o.get h⟩ : Part α) = o | ⟨_, _⟩ => rfl /-- `a ∈ o` means that `o` is defined and equal to `a` -/ protected def Mem (a : α) (o : Part α) : Prop := ∃ h, o.get h = a instance : Membership α (Part α) := ⟨Part.Mem⟩ theorem mem_eq (a : α) (o : Part α) : (a ∈ o) = ∃ h, o.get h = a := rfl theorem dom_iff_mem : ∀ {o : Part α}, o.Dom ↔ ∃ y, y ∈ o | ⟨_, f⟩ => ⟨fun h => ⟨f h, h, rfl⟩, fun ⟨_, h, rfl⟩ => h⟩ theorem get_mem {o : Part α} (h) : get o h ∈ o := ⟨_, rfl⟩ @[simp] theorem mem_mk_iff {p : Prop} {o : p → α} {a : α} : a ∈ Part.mk p o ↔ ∃ h, o h = a := Iff.rfl /-- `Part` extensionality -/ @[ext] theorem ext {o p : Part α} (H : ∀ a, a ∈ o ↔ a ∈ p) : o = p := (ext' ⟨fun h => ((H _).1 ⟨h, rfl⟩).fst, fun h => ((H _).2 ⟨h, rfl⟩).fst⟩) fun _ _ => ((H _).2 ⟨_, rfl⟩).snd /-- The `none` value in `Part` has a `False` domain and an empty function. -/ def none : Part α := ⟨False, False.rec⟩ instance : Inhabited (Part α) := ⟨none⟩ @[simp] theorem not_mem_none (a : α) : a ∉ @none α := fun h => h.fst /-- The `some a` value in `Part` has a `True` domain and the function returns `a`. -/ def some (a : α) : Part α := ⟨True, fun _ => a⟩ @[simp] theorem some_dom (a : α) : (some a).Dom := trivial theorem mem_unique : ∀ {a b : α} {o : Part α}, a ∈ o → b ∈ o → a = b | _, _, ⟨_, _⟩, ⟨_, rfl⟩, ⟨_, rfl⟩ => rfl theorem Mem.left_unique : Relator.LeftUnique ((· ∈ ·) : α → Part α → Prop) := fun _ _ _ => mem_unique theorem get_eq_of_mem {o : Part α} {a} (h : a ∈ o) (h') : get o h' = a := mem_unique ⟨_, rfl⟩ h protected theorem subsingleton (o : Part α) : Set.Subsingleton { a | a ∈ o } := fun _ ha _ hb => mem_unique ha hb @[simp] theorem get_some {a : α} (ha : (some a).Dom) : get (some a) ha = a := rfl theorem mem_some (a : α) : a ∈ some a := ⟨trivial, rfl⟩ @[simp] theorem mem_some_iff {a b} : b ∈ (some a : Part α) ↔ b = a := ⟨fun ⟨_, e⟩ => e.symm, fun e => ⟨trivial, e.symm⟩⟩ theorem eq_some_iff {a : α} {o : Part α} : o = some a ↔ a ∈ o := ⟨fun e => e.symm ▸ mem_some _, fun ⟨h, e⟩ => e ▸ ext' (iff_true_intro h) fun _ _ => rfl⟩ theorem eq_none_iff {o : Part α} : o = none ↔ ∀ a, a ∉ o := ⟨fun e => e.symm ▸ not_mem_none, fun h => ext (by simpa)⟩ theorem eq_none_iff' {o : Part α} : o = none ↔ ¬o.Dom := ⟨fun e => e.symm ▸ id, fun h => eq_none_iff.2 fun _ h' => h h'.fst⟩ @[simp] theorem not_none_dom : ¬(none : Part α).Dom := id @[simp] theorem some_ne_none (x : α) : some x ≠ none := by intro h exact true_ne_false (congr_arg Dom h) @[simp] theorem none_ne_some (x : α) : none ≠ some x := (some_ne_none x).symm theorem ne_none_iff {o : Part α} : o ≠ none ↔ ∃ x, o = some x := by constructor · rw [Ne, eq_none_iff', not_not] exact fun h => ⟨o.get h, eq_some_iff.2 (get_mem h)⟩ · rintro ⟨x, rfl⟩ apply some_ne_none theorem eq_none_or_eq_some (o : Part α) : o = none ∨ ∃ x, o = some x := or_iff_not_imp_left.2 ne_none_iff.1 theorem some_injective : Injective (@Part.some α) := fun _ _ h => congr_fun (eq_of_heq (Part.mk.inj h).2) trivial @[simp] theorem some_inj {a b : α} : Part.some a = some b ↔ a = b := some_injective.eq_iff @[simp] theorem some_get {a : Part α} (ha : a.Dom) : Part.some (Part.get a ha) = a := Eq.symm (eq_some_iff.2 ⟨ha, rfl⟩) theorem get_eq_iff_eq_some {a : Part α} {ha : a.Dom} {b : α} : a.get ha = b ↔ a = some b := ⟨fun h => by simp [h.symm], fun h => by simp [h]⟩ theorem get_eq_get_of_eq (a : Part α) (ha : a.Dom) {b : Part α} (h : a = b) : a.get ha = b.get (h ▸ ha) := by congr theorem get_eq_iff_mem {o : Part α} {a : α} (h : o.Dom) : o.get h = a ↔ a ∈ o := ⟨fun H => ⟨h, H⟩, fun ⟨_, H⟩ => H⟩ theorem eq_get_iff_mem {o : Part α} {a : α} (h : o.Dom) : a = o.get h ↔ a ∈ o := eq_comm.trans (get_eq_iff_mem h) @[simp] theorem none_toOption [Decidable (@none α).Dom] : (none : Part α).toOption = Option.none := dif_neg id @[simp] theorem some_toOption (a : α) [Decidable (some a).Dom] : (some a).toOption = Option.some a := dif_pos trivial instance noneDecidable : Decidable (@none α).Dom := instDecidableFalse instance someDecidable (a : α) : Decidable (some a).Dom := instDecidableTrue /-- Retrieves the value of `a : Part α` if it exists, and return the provided default value otherwise. -/ def getOrElse (a : Part α) [Decidable a.Dom] (d : α) := if ha : a.Dom then a.get ha else d theorem getOrElse_of_dom (a : Part α) (h : a.Dom) [Decidable a.Dom] (d : α) : getOrElse a d = a.get h := dif_pos h theorem getOrElse_of_not_dom (a : Part α) (h : ¬a.Dom) [Decidable a.Dom] (d : α) : getOrElse a d = d := dif_neg h @[simp] theorem getOrElse_none (d : α) [Decidable (none : Part α).Dom] : getOrElse none d = d := none.getOrElse_of_not_dom not_none_dom d @[simp] theorem getOrElse_some (a : α) (d : α) [Decidable (some a).Dom] : getOrElse (some a) d = a := (some a).getOrElse_of_dom (some_dom a) d -- Porting note: removed `simp` theorem mem_toOption {o : Part α} [Decidable o.Dom] {a : α} : a ∈ toOption o ↔ a ∈ o := by unfold toOption by_cases h : o.Dom <;> simp [h] · exact ⟨fun h => ⟨_, h⟩, fun ⟨_, h⟩ => h⟩ · exact mt Exists.fst h @[simp] theorem toOption_eq_some_iff {o : Part α} [Decidable o.Dom] {a : α} : toOption o = Option.some a ↔ a ∈ o := by rw [← Option.mem_def, mem_toOption] protected theorem Dom.toOption {o : Part α} [Decidable o.Dom] (h : o.Dom) : o.toOption = o.get h := dif_pos h theorem toOption_eq_none_iff {a : Part α} [Decidable a.Dom] : a.toOption = Option.none ↔ ¬a.Dom := Ne.dite_eq_right_iff fun _ => Option.some_ne_none _ /- Porting TODO: Removed `simp`. Maybe add `@[simp]` later if `@[simp]` is taken off definition of `Option.elim` -/ theorem elim_toOption {α β : Type*} (a : Part α) [Decidable a.Dom] (b : β) (f : α → β) : a.toOption.elim b f = if h : a.Dom then f (a.get h) else b := by split_ifs with h · rw [h.toOption] rfl · rw [Part.toOption_eq_none_iff.2 h] rfl /-- Converts an `Option α` into a `Part α`. -/ @[coe] def ofOption : Option α → Part α | Option.none => none | Option.some a => some a @[simp] theorem mem_ofOption {a : α} : ∀ {o : Option α}, a ∈ ofOption o ↔ a ∈ o | Option.none => ⟨fun h => h.fst.elim, fun h => Option.noConfusion h⟩ | Option.some _ => ⟨fun h => congr_arg Option.some h.snd, fun h => ⟨trivial, Option.some.inj h⟩⟩ @[simp] theorem ofOption_dom {α} : ∀ o : Option α, (ofOption o).Dom ↔ o.isSome | Option.none => by simp [ofOption, none] | Option.some a => by simp [ofOption] theorem ofOption_eq_get {α} (o : Option α) : ofOption o = ⟨_, @Option.get _ o⟩ := Part.ext' (ofOption_dom o) fun h₁ h₂ => by cases o · simp at h₂ · rfl instance : Coe (Option α) (Part α) := ⟨ofOption⟩ theorem mem_coe {a : α} {o : Option α} : a ∈ (o : Part α) ↔ a ∈ o := mem_ofOption @[simp] theorem coe_none : (@Option.none α : Part α) = none := rfl @[simp] theorem coe_some (a : α) : (Option.some a : Part α) = some a := rfl @[elab_as_elim] protected theorem induction_on {P : Part α → Prop} (a : Part α) (hnone : P none) (hsome : ∀ a : α, P (some a)) : P a := (Classical.em a.Dom).elim (fun h => Part.some_get h ▸ hsome _) fun h => (eq_none_iff'.2 h).symm ▸ hnone instance ofOptionDecidable : ∀ o : Option α, Decidable (ofOption o).Dom | Option.none => Part.noneDecidable | Option.some a => Part.someDecidable a @[simp] theorem to_ofOption (o : Option α) : toOption (ofOption o) = o := by cases o <;> rfl @[simp] theorem of_toOption (o : Part α) [Decidable o.Dom] : ofOption (toOption o) = o := ext fun _ => mem_ofOption.trans mem_toOption /-- `Part α` is (classically) equivalent to `Option α`. -/ noncomputable def equivOption : Part α ≃ Option α := haveI := Classical.dec ⟨fun o => toOption o, ofOption, fun o => of_toOption o, fun o => Eq.trans (by dsimp; congr) (to_ofOption o)⟩ /-- We give `Part α` the order where everything is greater than `none`. -/ instance : PartialOrder (Part α) where le x y := ∀ i, i ∈ x → i ∈ y le_refl x y := id le_trans x y z f g i := g _ ∘ f _ le_antisymm x y f g := Part.ext fun z => ⟨f _, g _⟩ instance : OrderBot (Part α) where bot := none bot_le := by rintro x _ ⟨⟨_⟩, _⟩ theorem le_total_of_le_of_le {x y : Part α} (z : Part α) (hx : x ≤ z) (hy : y ≤ z) : x ≤ y ∨ y ≤ x := by rcases Part.eq_none_or_eq_some x with (h | ⟨b, h₀⟩) · rw [h] left apply OrderBot.bot_le _ right; intro b' h₁ rw [Part.eq_some_iff] at h₀ have hx := hx _ h₀; have hy := hy _ h₁ have hx := Part.mem_unique hx hy; subst hx exact h₀ /-- `assert p f` is a bind-like operation which appends an additional condition `p` to the domain and uses `f` to produce the value. -/ def assert (p : Prop) (f : p → Part α) : Part α := ⟨∃ h : p, (f h).Dom, fun ha => (f ha.fst).get ha.snd⟩ /-- The bind operation has value `g (f.get)`, and is defined when all the parts are defined. -/ protected def bind (f : Part α) (g : α → Part β) : Part β := assert (Dom f) fun b => g (f.get b) /-- The map operation for `Part` just maps the value and maintains the same domain. -/ @[simps] def map (f : α → β) (o : Part α) : Part β := ⟨o.Dom, f ∘ o.get⟩ theorem mem_map (f : α → β) {o : Part α} : ∀ {a}, a ∈ o → f a ∈ map f o | _, ⟨_, rfl⟩ => ⟨_, rfl⟩ @[simp] theorem mem_map_iff (f : α → β) {o : Part α} {b} : b ∈ map f o ↔ ∃ a ∈ o, f a = b := ⟨fun hb => match b, hb with | _, ⟨_, rfl⟩ => ⟨_, ⟨_, rfl⟩, rfl⟩, fun ⟨_, h₁, h₂⟩ => h₂ ▸ mem_map f h₁⟩ @[simp] theorem map_none (f : α → β) : map f none = none := eq_none_iff.2 fun a => by simp @[simp] theorem map_some (f : α → β) (a : α) : map f (some a) = some (f a) := eq_some_iff.2 <| mem_map f <| mem_some _ theorem mem_assert {p : Prop} {f : p → Part α} : ∀ {a} (h : p), a ∈ f h → a ∈ assert p f | _, x, ⟨h, rfl⟩ => ⟨⟨x, h⟩, rfl⟩ @[simp] theorem mem_assert_iff {p : Prop} {f : p → Part α} {a} : a ∈ assert p f ↔ ∃ h : p, a ∈ f h := ⟨fun ha => match a, ha with | _, ⟨_, rfl⟩ => ⟨_, ⟨_, rfl⟩⟩, fun ⟨_, h⟩ => mem_assert _ h⟩ theorem assert_pos {p : Prop} {f : p → Part α} (h : p) : assert p f = f h := by dsimp [assert] cases h' : f h simp only [h', mk.injEq, h, exists_prop_of_true, true_and] apply Function.hfunext · simp only [h, h', exists_prop_of_true] · aesop theorem assert_neg {p : Prop} {f : p → Part α} (h : ¬p) : assert p f = none := by dsimp [assert, none]; congr · simp only [h, not_false_iff, exists_prop_of_false] · apply Function.hfunext · simp only [h, not_false_iff, exists_prop_of_false] simp at * theorem mem_bind {f : Part α} {g : α → Part β} : ∀ {a b}, a ∈ f → b ∈ g a → b ∈ f.bind g | _, _, ⟨h, rfl⟩, ⟨h₂, rfl⟩ => ⟨⟨h, h₂⟩, rfl⟩ @[simp] theorem mem_bind_iff {f : Part α} {g : α → Part β} {b} : b ∈ f.bind g ↔ ∃ a ∈ f, b ∈ g a := ⟨fun hb => match b, hb with | _, ⟨⟨_, _⟩, rfl⟩ => ⟨_, ⟨_, rfl⟩, ⟨_, rfl⟩⟩, fun ⟨_, h₁, h₂⟩ => mem_bind h₁ h₂⟩ protected theorem Dom.bind {o : Part α} (h : o.Dom) (f : α → Part β) : o.bind f = f (o.get h) := by ext b simp only [Part.mem_bind_iff, exists_prop] refine ⟨?_, fun hb => ⟨o.get h, Part.get_mem _, hb⟩⟩ rintro ⟨a, ha, hb⟩ rwa [Part.get_eq_of_mem ha] theorem Dom.of_bind {f : α → Part β} {a : Part α} (h : (a.bind f).Dom) : a.Dom := h.1 @[simp] theorem bind_none (f : α → Part β) : none.bind f = none := eq_none_iff.2 fun a => by simp @[simp] theorem bind_some (a : α) (f : α → Part β) : (some a).bind f = f a := ext <| by simp theorem bind_of_mem {o : Part α} {a : α} (h : a ∈ o) (f : α → Part β) : o.bind f = f a := by rw [eq_some_iff.2 h, bind_some] theorem bind_some_eq_map (f : α → β) (x : Part α) : x.bind (some ∘ f) = map f x := ext <| by simp [eq_comm] theorem bind_toOption (f : α → Part β) (o : Part α) [Decidable o.Dom] [∀ a, Decidable (f a).Dom] [Decidable (o.bind f).Dom] : (o.bind f).toOption = o.toOption.elim Option.none fun a => (f a).toOption := by by_cases h : o.Dom · simp_rw [h.toOption, h.bind] rfl · rw [Part.toOption_eq_none_iff.2 h] exact Part.toOption_eq_none_iff.2 fun ho => h ho.of_bind theorem bind_assoc {γ} (f : Part α) (g : α → Part β) (k : β → Part γ) : (f.bind g).bind k = f.bind fun x => (g x).bind k := ext fun a => by simp only [mem_bind_iff] exact ⟨fun ⟨_, ⟨_, h₁, h₂⟩, h₃⟩ => ⟨_, h₁, _, h₂, h₃⟩, fun ⟨_, h₁, _, h₂, h₃⟩ => ⟨_, ⟨_, h₁, h₂⟩, h₃⟩⟩ @[simp] theorem bind_map {γ} (f : α → β) (x) (g : β → Part γ) : (map f x).bind g = x.bind fun y => g (f y) := by rw [← bind_some_eq_map, bind_assoc]; simp @[simp] theorem map_bind {γ} (f : α → Part β) (x : Part α) (g : β → γ) : map g (x.bind f) = x.bind fun y => map g (f y) := by rw [← bind_some_eq_map, bind_assoc]; simp [bind_some_eq_map] theorem map_map (g : β → γ) (f : α → β) (o : Part α) : map g (map f o) = map (g ∘ f) o := by erw [← bind_some_eq_map, bind_map, bind_some_eq_map] instance : Monad Part where pure := @some map := @map bind := @Part.bind instance : LawfulMonad Part where bind_pure_comp := @bind_some_eq_map id_map f := by cases f; rfl pure_bind := @bind_some bind_assoc := @bind_assoc map_const := by simp [Functor.mapConst, Functor.map] --Porting TODO : In Lean3 these were automatic by a tactic seqLeft_eq x y := ext' (by simp [SeqLeft.seqLeft, Part.bind, assert, Seq.seq, const, (· <$> ·), and_comm]) (fun _ _ => rfl) seqRight_eq x y := ext' (by simp [SeqRight.seqRight, Part.bind, assert, Seq.seq, const, (· <$> ·), and_comm]) (fun _ _ => rfl) pure_seq x y := ext' (by simp [Seq.seq, Part.bind, assert, (· <$> ·), pure]) (fun _ _ => rfl) bind_map x y := ext' (by simp [(· >>= ·), Part.bind, assert, Seq.seq, get, (· <$> ·)] ) (fun _ _ => rfl) theorem map_id' {f : α → α} (H : ∀ x : α, f x = x) (o) : map f o = o := by rw [show f = id from funext H]; exact id_map o @[simp] theorem bind_some_right (x : Part α) : x.bind some = x := by erw [bind_some_eq_map]; simp [map_id'] @[simp] theorem pure_eq_some (a : α) : pure a = some a := rfl @[simp] theorem ret_eq_some (a : α) : (return a : Part α) = some a := rfl @[simp] theorem map_eq_map {α β} (f : α → β) (o : Part α) : f <$> o = map f o := rfl @[simp] theorem bind_eq_bind {α β} (f : Part α) (g : α → Part β) : f >>= g = f.bind g := rfl theorem bind_le {α} (x : Part α) (f : α → Part β) (y : Part β) : x >>= f ≤ y ↔ ∀ a, a ∈ x → f a ≤ y := by constructor <;> intro h · intro a h' b have h := h b simp only [and_imp, exists_prop, bind_eq_bind, mem_bind_iff, exists_imp] at h apply h _ h' · intro b h' simp only [exists_prop, bind_eq_bind, mem_bind_iff] at h' rcases h' with ⟨a, h₀, h₁⟩ apply h _ h₀ _ h₁ -- Porting note: No MonadFail in Lean4 yet -- instance : MonadFail Part := -- { Part.monad with fail := fun _ _ => none } /-- `restrict p o h` replaces the domain of `o` with `p`, and is well defined when `p` implies `o` is defined. -/ def restrict (p : Prop) (o : Part α) (H : p → o.Dom) : Part α := ⟨p, fun h => o.get (H h)⟩ @[simp] theorem mem_restrict (p : Prop) (o : Part α) (h : p → o.Dom) (a : α) : a ∈ restrict p o h ↔ p ∧ a ∈ o := by dsimp [restrict, mem_eq]; constructor · rintro ⟨h₀, h₁⟩ exact ⟨h₀, ⟨_, h₁⟩⟩ rintro ⟨h₀, _, h₂⟩; exact ⟨h₀, h₂⟩ /-- `unwrap o` gets the value at `o`, ignoring the condition. This function is unsound. -/ unsafe def unwrap (o : Part α) : α := o.get lcProof theorem assert_defined {p : Prop} {f : p → Part α} : ∀ h : p, (f h).Dom → (assert p f).Dom := Exists.intro theorem bind_defined {f : Part α} {g : α → Part β} : ∀ h : f.Dom, (g (f.get h)).Dom → (f.bind g).Dom := assert_defined @[simp] theorem bind_dom {f : Part α} {g : α → Part β} : (f.bind g).Dom ↔ ∃ h : f.Dom, (g (f.get h)).Dom := Iff.rfl section Instances /-! We define several instances for constants and operations on `Part α` inherited from `α`. This section could be moved to a separate file to avoid the import of `Mathlib.Algebra.Group.Defs`. -/ @[to_additive] instance [One α] : One (Part α) where one := pure 1 @[to_additive] instance [Mul α] : Mul (Part α) where mul a b := (· * ·) <$> a <*> b @[to_additive] instance [Inv α] : Inv (Part α) where inv := map Inv.inv @[to_additive] instance [Div α] : Div (Part α) where div a b := (· / ·) <$> a <*> b instance [Mod α] : Mod (Part α) where mod a b := (· % ·) <$> a <*> b instance [Append α] : Append (Part α) where append a b := (· ++ ·) <$> a <*> b instance [Inter α] : Inter (Part α) where inter a b := (· ∩ ·) <$> a <*> b instance [Union α] : Union (Part α) where union a b := (· ∪ ·) <$> a <*> b instance [SDiff α] : SDiff (Part α) where sdiff a b := (· \ ·) <$> a <*> b section theorem mul_def [Mul α] (a b : Part α) : a * b = bind a fun y ↦ map (y * ·) b := rfl theorem one_def [One α] : (1 : Part α) = some 1 := rfl theorem inv_def [Inv α] (a : Part α) : a⁻¹ = Part.map (· ⁻¹) a := rfl theorem div_def [Div α] (a b : Part α) : a / b = bind a fun y => map (y / ·) b := rfl theorem mod_def [Mod α] (a b : Part α) : a % b = bind a fun y => map (y % ·) b := rfl theorem append_def [Append α] (a b : Part α) : a ++ b = bind a fun y => map (y ++ ·) b := rfl theorem inter_def [Inter α] (a b : Part α) : a ∩ b = bind a fun y => map (y ∩ ·) b := rfl theorem union_def [Union α] (a b : Part α) : a ∪ b = bind a fun y => map (y ∪ ·) b := rfl theorem sdiff_def [SDiff α] (a b : Part α) : a \ b = bind a fun y => map (y \ ·) b := rfl end @[to_additive] theorem one_mem_one [One α] : (1 : α) ∈ (1 : Part α) := ⟨trivial, rfl⟩ @[to_additive] theorem mul_mem_mul [Mul α] (a b : Part α) (ma mb : α) (ha : ma ∈ a) (hb : mb ∈ b) : ma * mb ∈ a * b := ⟨⟨ha.1, hb.1⟩, by simp only [← ha.2, ← hb.2]; rfl⟩ @[to_additive] theorem left_dom_of_mul_dom [Mul α] {a b : Part α} (hab : Dom (a * b)) : a.Dom := hab.1 @[to_additive] theorem right_dom_of_mul_dom [Mul α] {a b : Part α} (hab : Dom (a * b)) : b.Dom := hab.2 @[to_additive (attr := simp)] theorem mul_get_eq [Mul α] (a b : Part α) (hab : Dom (a * b)) : (a * b).get hab = a.get (left_dom_of_mul_dom hab) * b.get (right_dom_of_mul_dom hab) := rfl @[to_additive] theorem some_mul_some [Mul α] (a b : α) : some a * some b = some (a * b) := by simp [mul_def] @[to_additive] theorem inv_mem_inv [Inv α] (a : Part α) (ma : α) (ha : ma ∈ a) : ma⁻¹ ∈ a⁻¹ := by simp [inv_def]; aesop @[to_additive] theorem inv_some [Inv α] (a : α) : (some a)⁻¹ = some a⁻¹ := rfl @[to_additive] theorem div_mem_div [Div α] (a b : Part α) (ma mb : α) (ha : ma ∈ a) (hb : mb ∈ b) : ma / mb ∈ a / b := by simp [div_def]; aesop @[to_additive] theorem left_dom_of_div_dom [Div α] {a b : Part α} (hab : Dom (a / b)) : a.Dom := hab.1 @[to_additive] theorem right_dom_of_div_dom [Div α] {a b : Part α} (hab : Dom (a / b)) : b.Dom := hab.2 @[to_additive (attr := simp)] theorem div_get_eq [Div α] (a b : Part α) (hab : Dom (a / b)) : (a / b).get hab = a.get (left_dom_of_div_dom hab) / b.get (right_dom_of_div_dom hab) := by simp [div_def]; aesop @[to_additive] theorem some_div_some [Div α] (a b : α) : some a / some b = some (a / b) := by simp [div_def] theorem mod_mem_mod [Mod α] (a b : Part α) (ma mb : α) (ha : ma ∈ a) (hb : mb ∈ b) : ma % mb ∈ a % b := by simp [mod_def]; aesop theorem left_dom_of_mod_dom [Mod α] {a b : Part α} (hab : Dom (a % b)) : a.Dom := hab.1 theorem right_dom_of_mod_dom [Mod α] {a b : Part α} (hab : Dom (a % b)) : b.Dom := hab.2 @[simp] theorem mod_get_eq [Mod α] (a b : Part α) (hab : Dom (a % b)) : (a % b).get hab = a.get (left_dom_of_mod_dom hab) % b.get (right_dom_of_mod_dom hab) := by simp [mod_def]; aesop theorem some_mod_some [Mod α] (a b : α) : some a % some b = some (a % b) := by simp [mod_def] theorem append_mem_append [Append α] (a b : Part α) (ma mb : α) (ha : ma ∈ a) (hb : mb ∈ b) : ma ++ mb ∈ a ++ b := by simp [append_def]; aesop theorem left_dom_of_append_dom [Append α] {a b : Part α} (hab : Dom (a ++ b)) : a.Dom := hab.1 theorem right_dom_of_append_dom [Append α] {a b : Part α} (hab : Dom (a ++ b)) : b.Dom := hab.2 @[simp] theorem append_get_eq [Append α] (a b : Part α) (hab : Dom (a ++ b)) : (a ++ b).get hab = a.get (left_dom_of_append_dom hab) ++ b.get (right_dom_of_append_dom hab) := by simp [append_def]; aesop theorem some_append_some [Append α] (a b : α) : some a ++ some b = some (a ++ b) := by simp [append_def] theorem inter_mem_inter [Inter α] (a b : Part α) (ma mb : α) (ha : ma ∈ a) (hb : mb ∈ b) : ma ∩ mb ∈ a ∩ b := by simp [inter_def]; aesop theorem left_dom_of_inter_dom [Inter α] {a b : Part α} (hab : Dom (a ∩ b)) : a.Dom := hab.1 theorem right_dom_of_inter_dom [Inter α] {a b : Part α} (hab : Dom (a ∩ b)) : b.Dom := hab.2 @[simp] theorem inter_get_eq [Inter α] (a b : Part α) (hab : Dom (a ∩ b)) : (a ∩ b).get hab = a.get (left_dom_of_inter_dom hab) ∩ b.get (right_dom_of_inter_dom hab) := by simp [inter_def]; aesop theorem some_inter_some [Inter α] (a b : α) : some a ∩ some b = some (a ∩ b) := by simp [inter_def] theorem union_mem_union [Union α] (a b : Part α) (ma mb : α) (ha : ma ∈ a) (hb : mb ∈ b) : ma ∪ mb ∈ a ∪ b := by simp [union_def]; aesop theorem left_dom_of_union_dom [Union α] {a b : Part α} (hab : Dom (a ∪ b)) : a.Dom := hab.1 theorem right_dom_of_union_dom [Union α] {a b : Part α} (hab : Dom (a ∪ b)) : b.Dom := hab.2 @[simp] theorem union_get_eq [Union α] (a b : Part α) (hab : Dom (a ∪ b)) : (a ∪ b).get hab = a.get (left_dom_of_union_dom hab) ∪ b.get (right_dom_of_union_dom hab) := by simp [union_def]; aesop theorem some_union_some [Union α] (a b : α) : some a ∪ some b = some (a ∪ b) := by simp [union_def] theorem sdiff_mem_sdiff [SDiff α] (a b : Part α) (ma mb : α) (ha : ma ∈ a) (hb : mb ∈ b) : ma \ mb ∈ a \ b := by simp [sdiff_def]; aesop theorem left_dom_of_sdiff_dom [SDiff α] {a b : Part α} (hab : Dom (a \ b)) : a.Dom := hab.1 theorem right_dom_of_sdiff_dom [SDiff α] {a b : Part α} (hab : Dom (a \ b)) : b.Dom := hab.2 @[simp] theorem sdiff_get_eq [SDiff α] (a b : Part α) (hab : Dom (a \ b)) : (a \ b).get hab = a.get (left_dom_of_sdiff_dom hab) \ b.get (right_dom_of_sdiff_dom hab) := by simp [sdiff_def]; aesop theorem some_sdiff_some [SDiff α] (a b : α) : some a \ some b = some (a \ b) := by simp [sdiff_def] end Instances end Part
Data\PEquiv.lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import Mathlib.Data.Option.Basic import Mathlib.Data.Set.Basic import Batteries.Tactic.Congr /-! # Partial Equivalences In this file, we define partial equivalences `PEquiv`, which are a bijection between a subset of `α` and a subset of `β`. Notationally, a `PEquiv` is denoted by "`≃.`" (note that the full stop is part of the notation). The way we store these internally is with two functions `f : α → Option β` and the reverse function `g : β → Option α`, with the condition that if `f a` is `some b`, then `g b` is `some a`. ## Main results - `PEquiv.ofSet`: creates a `PEquiv` from a set `s`, which sends an element to itself if it is in `s`. - `PEquiv.single`: given two elements `a : α` and `b : β`, create a `PEquiv` that sends them to each other, and ignores all other elements. - `PEquiv.injective_of_forall_ne_isSome`/`injective_of_forall_isSome`: If the domain of a `PEquiv` is all of `α` (except possibly one point), its `toFun` is injective. ## Canonical order `PEquiv` is canonically ordered by inclusion; that is, if a function `f` defined on a subset `s` is equal to `g` on that subset, but `g` is also defined on a larger set, then `f ≤ g`. We also have a definition of `⊥`, which is the empty `PEquiv` (sends all to `none`), which in the end gives us a `SemilatticeInf` with an `OrderBot` instance. ## Tags pequiv, partial equivalence -/ universe u v w x /-- A `PEquiv` is a partial equivalence, a representation of a bijection between a subset of `α` and a subset of `β`. See also `PartialEquiv` for a version that requires `toFun` and `invFun` to be globally defined functions and has `source` and `target` sets as extra fields. -/ structure PEquiv (α : Type u) (β : Type v) where /-- The underlying partial function of a `PEquiv` -/ toFun : α → Option β /-- The partial inverse of `toFun` -/ invFun : β → Option α /-- `invFun` is the partial inverse of `toFun` -/ inv : ∀ (a : α) (b : β), a ∈ invFun b ↔ b ∈ toFun a /-- A `PEquiv` is a partial equivalence, a representation of a bijection between a subset of `α` and a subset of `β`. See also `PartialEquiv` for a version that requires `toFun` and `invFun` to be globally defined functions and has `source` and `target` sets as extra fields. -/ infixr:25 " ≃. " => PEquiv namespace PEquiv variable {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} open Function Option instance : FunLike (α ≃. β) α (Option β) := { coe := toFun coe_injective' := by rintro ⟨f₁, f₂, hf⟩ ⟨g₁, g₂, hg⟩ (rfl : f₁ = g₁) congr with y x simp only [hf, hg] } @[simp] theorem coe_mk (f₁ : α → Option β) (f₂ h) : (mk f₁ f₂ h : α → Option β) = f₁ := rfl theorem coe_mk_apply (f₁ : α → Option β) (f₂ : β → Option α) (h) (x : α) : (PEquiv.mk f₁ f₂ h : α → Option β) x = f₁ x := rfl @[ext] theorem ext {f g : α ≃. β} (h : ∀ x, f x = g x) : f = g := DFunLike.ext f g h /-- The identity map as a partial equivalence. -/ @[refl] protected def refl (α : Type*) : α ≃. α where toFun := some invFun := some inv _ _ := eq_comm /-- The inverse partial equivalence. -/ @[symm] protected def symm (f : α ≃. β) : β ≃. α where toFun := f.2 invFun := f.1 inv _ _ := (f.inv _ _).symm theorem mem_iff_mem (f : α ≃. β) : ∀ {a : α} {b : β}, a ∈ f.symm b ↔ b ∈ f a := f.3 _ _ theorem eq_some_iff (f : α ≃. β) : ∀ {a : α} {b : β}, f.symm b = some a ↔ f a = some b := f.3 _ _ /-- Composition of partial equivalences `f : α ≃. β` and `g : β ≃. γ`. -/ @[trans] protected def trans (f : α ≃. β) (g : β ≃. γ) : α ≃. γ where toFun a := (f a).bind g invFun a := (g.symm a).bind f.symm inv a b := by simp_all [and_comm, eq_some_iff f, eq_some_iff g, bind_eq_some] @[simp] theorem refl_apply (a : α) : PEquiv.refl α a = some a := rfl @[simp] theorem symm_refl : (PEquiv.refl α).symm = PEquiv.refl α := rfl @[simp] theorem symm_symm (f : α ≃. β) : f.symm.symm = f := by cases f; rfl theorem symm_bijective : Function.Bijective (PEquiv.symm : (α ≃. β) → β ≃. α) := Function.bijective_iff_has_inverse.mpr ⟨_, symm_symm, symm_symm⟩ theorem symm_injective : Function.Injective (@PEquiv.symm α β) := symm_bijective.injective theorem trans_assoc (f : α ≃. β) (g : β ≃. γ) (h : γ ≃. δ) : (f.trans g).trans h = f.trans (g.trans h) := ext fun _ => Option.bind_assoc _ _ _ theorem mem_trans (f : α ≃. β) (g : β ≃. γ) (a : α) (c : γ) : c ∈ f.trans g a ↔ ∃ b, b ∈ f a ∧ c ∈ g b := Option.bind_eq_some' theorem trans_eq_some (f : α ≃. β) (g : β ≃. γ) (a : α) (c : γ) : f.trans g a = some c ↔ ∃ b, f a = some b ∧ g b = some c := Option.bind_eq_some' theorem trans_eq_none (f : α ≃. β) (g : β ≃. γ) (a : α) : f.trans g a = none ↔ ∀ b c, b ∉ f a ∨ c ∉ g b := by simp only [eq_none_iff_forall_not_mem, mem_trans, imp_iff_not_or.symm] push_neg exact forall_swap @[simp] theorem refl_trans (f : α ≃. β) : (PEquiv.refl α).trans f = f := by ext; dsimp [PEquiv.trans]; rfl @[simp] theorem trans_refl (f : α ≃. β) : f.trans (PEquiv.refl β) = f := by ext; dsimp [PEquiv.trans]; simp protected theorem inj (f : α ≃. β) {a₁ a₂ : α} {b : β} (h₁ : b ∈ f a₁) (h₂ : b ∈ f a₂) : a₁ = a₂ := by rw [← mem_iff_mem] at *; cases h : f.symm b <;> simp_all /-- If the domain of a `PEquiv` is `α` except a point, its forward direction is injective. -/ theorem injective_of_forall_ne_isSome (f : α ≃. β) (a₂ : α) (h : ∀ a₁ : α, a₁ ≠ a₂ → isSome (f a₁)) : Injective f := HasLeftInverse.injective ⟨fun b => Option.recOn b a₂ fun b' => Option.recOn (f.symm b') a₂ id, fun x => by classical cases hfx : f x · have : x = a₂ := not_imp_comm.1 (h x) (hfx.symm ▸ by simp) simp [this] · dsimp only rw [(eq_some_iff f).2 hfx] rfl⟩ /-- If the domain of a `PEquiv` is all of `α`, its forward direction is injective. -/ theorem injective_of_forall_isSome {f : α ≃. β} (h : ∀ a : α, isSome (f a)) : Injective f := (Classical.em (Nonempty α)).elim (fun hn => injective_of_forall_ne_isSome f (Classical.choice hn) fun a _ => h a) fun hn x => (hn ⟨x⟩).elim section OfSet variable (s : Set α) [DecidablePred (· ∈ s)] /-- Creates a `PEquiv` that is the identity on `s`, and `none` outside of it. -/ def ofSet (s : Set α) [DecidablePred (· ∈ s)] : α ≃. α where toFun a := if a ∈ s then some a else none invFun a := if a ∈ s then some a else none inv a b := by dsimp only split_ifs with hb ha ha · simp [eq_comm] · simp [ne_of_mem_of_not_mem hb ha] · simp [ne_of_mem_of_not_mem ha hb] · simp theorem mem_ofSet_self_iff {s : Set α} [DecidablePred (· ∈ s)] {a : α} : a ∈ ofSet s a ↔ a ∈ s := by dsimp [ofSet]; split_ifs <;> simp [*] theorem mem_ofSet_iff {s : Set α} [DecidablePred (· ∈ s)] {a b : α} : a ∈ ofSet s b ↔ a = b ∧ a ∈ s := by dsimp [ofSet] split_ifs with h · simp only [mem_def, eq_comm, some.injEq, iff_self_and] rintro rfl exact h · simp only [mem_def, false_iff, not_and] rintro rfl exact h @[simp] theorem ofSet_eq_some_iff {s : Set α} {_ : DecidablePred (· ∈ s)} {a b : α} : ofSet s b = some a ↔ a = b ∧ a ∈ s := mem_ofSet_iff theorem ofSet_eq_some_self_iff {s : Set α} {_ : DecidablePred (· ∈ s)} {a : α} : ofSet s a = some a ↔ a ∈ s := mem_ofSet_self_iff @[simp] theorem ofSet_symm : (ofSet s).symm = ofSet s := rfl @[simp] theorem ofSet_univ : ofSet Set.univ = PEquiv.refl α := rfl @[simp] theorem ofSet_eq_refl {s : Set α} [DecidablePred (· ∈ s)] : ofSet s = PEquiv.refl α ↔ s = Set.univ := ⟨fun h => by rw [Set.eq_univ_iff_forall] intro rw [← mem_ofSet_self_iff, h] exact rfl, fun h => by simp only [← ofSet_univ, h]⟩ end OfSet theorem symm_trans_rev (f : α ≃. β) (g : β ≃. γ) : (f.trans g).symm = g.symm.trans f.symm := rfl theorem self_trans_symm (f : α ≃. β) : f.trans f.symm = ofSet { a | (f a).isSome } := by ext dsimp [PEquiv.trans] simp only [eq_some_iff f, Option.isSome_iff_exists, Option.mem_def, bind_eq_some', ofSet_eq_some_iff] constructor · rintro ⟨b, hb₁, hb₂⟩ exact ⟨PEquiv.inj _ hb₂ hb₁, b, hb₂⟩ · simp (config := { contextual := true }) theorem symm_trans_self (f : α ≃. β) : f.symm.trans f = ofSet { b | (f.symm b).isSome } := symm_injective <| by simp [symm_trans_rev, self_trans_symm, -symm_symm] theorem trans_symm_eq_iff_forall_isSome {f : α ≃. β} : f.trans f.symm = PEquiv.refl α ↔ ∀ a, isSome (f a) := by rw [self_trans_symm, ofSet_eq_refl, Set.eq_univ_iff_forall]; rfl instance instBotPEquiv : Bot (α ≃. β) := ⟨{ toFun := fun _ => none invFun := fun _ => none inv := by simp }⟩ instance : Inhabited (α ≃. β) := ⟨⊥⟩ @[simp] theorem bot_apply (a : α) : (⊥ : α ≃. β) a = none := rfl @[simp] theorem symm_bot : (⊥ : α ≃. β).symm = ⊥ := rfl @[simp] theorem trans_bot (f : α ≃. β) : f.trans (⊥ : β ≃. γ) = ⊥ := by ext; dsimp [PEquiv.trans]; simp @[simp] theorem bot_trans (f : β ≃. γ) : (⊥ : α ≃. β).trans f = ⊥ := by ext; dsimp [PEquiv.trans]; simp theorem isSome_symm_get (f : α ≃. β) {a : α} (h : isSome (f a)) : isSome (f.symm (Option.get _ h)) := isSome_iff_exists.2 ⟨a, by rw [f.eq_some_iff, some_get]⟩ section Single variable [DecidableEq α] [DecidableEq β] [DecidableEq γ] /-- Create a `PEquiv` which sends `a` to `b` and `b` to `a`, but is otherwise `none`. -/ def single (a : α) (b : β) : α ≃. β where toFun x := if x = a then some b else none invFun x := if x = b then some a else none inv x y := by dsimp only split_ifs with h1 h2 · simp [*] · simp only [mem_def, some.injEq, iff_false] at * exact Ne.symm h2 · simp only [mem_def, some.injEq, false_iff] at * exact Ne.symm h1 · simp theorem mem_single (a : α) (b : β) : b ∈ single a b a := if_pos rfl theorem mem_single_iff (a₁ a₂ : α) (b₁ b₂ : β) : b₁ ∈ single a₂ b₂ a₁ ↔ a₁ = a₂ ∧ b₁ = b₂ := by dsimp [single]; split_ifs <;> simp [*, eq_comm] @[simp] theorem symm_single (a : α) (b : β) : (single a b).symm = single b a := rfl @[simp] theorem single_apply (a : α) (b : β) : single a b a = some b := if_pos rfl theorem single_apply_of_ne {a₁ a₂ : α} (h : a₁ ≠ a₂) (b : β) : single a₁ b a₂ = none := if_neg h.symm theorem single_trans_of_mem (a : α) {b : β} {c : γ} {f : β ≃. γ} (h : c ∈ f b) : (single a b).trans f = single a c := by ext dsimp [single, PEquiv.trans] split_ifs <;> simp_all theorem trans_single_of_mem {a : α} {b : β} (c : γ) {f : α ≃. β} (h : b ∈ f a) : f.trans (single b c) = single a c := symm_injective <| single_trans_of_mem _ ((mem_iff_mem f).2 h) @[simp] theorem single_trans_single (a : α) (b : β) (c : γ) : (single a b).trans (single b c) = single a c := single_trans_of_mem _ (mem_single _ _) @[simp] theorem single_subsingleton_eq_refl [Subsingleton α] (a b : α) : single a b = PEquiv.refl α := by ext i j dsimp [single] rw [if_pos (Subsingleton.elim i a), Subsingleton.elim i j, Subsingleton.elim b j] theorem trans_single_of_eq_none {b : β} (c : γ) {f : δ ≃. β} (h : f.symm b = none) : f.trans (single b c) = ⊥ := by ext simp only [eq_none_iff_forall_not_mem, Option.mem_def, f.eq_some_iff] at h dsimp [PEquiv.trans, single] simp only [mem_def, bind_eq_some, iff_false, not_exists, not_and] intros split_ifs <;> simp_all theorem single_trans_of_eq_none (a : α) {b : β} {f : β ≃. δ} (h : f b = none) : (single a b).trans f = ⊥ := symm_injective <| trans_single_of_eq_none _ h theorem single_trans_single_of_ne {b₁ b₂ : β} (h : b₁ ≠ b₂) (a : α) (c : γ) : (single a b₁).trans (single b₂ c) = ⊥ := single_trans_of_eq_none _ (single_apply_of_ne h.symm _) end Single section Order instance instPartialOrderPEquiv : PartialOrder (α ≃. β) where le f g := ∀ (a : α) (b : β), b ∈ f a → b ∈ g a le_refl _ _ _ := id le_trans f g h fg gh a b := gh a b ∘ fg a b le_antisymm f g fg gf := ext (by intro a cases' h : g a with b · exact eq_none_iff_forall_not_mem.2 fun b hb => Option.not_mem_none b <| h ▸ fg a b hb · exact gf _ _ h) theorem le_def {f g : α ≃. β} : f ≤ g ↔ ∀ (a : α) (b : β), b ∈ f a → b ∈ g a := Iff.rfl instance : OrderBot (α ≃. β) := { instBotPEquiv with bot_le := fun _ _ _ h => (not_mem_none _ h).elim } instance [DecidableEq α] [DecidableEq β] : SemilatticeInf (α ≃. β) := { instPartialOrderPEquiv with inf := fun f g => { toFun := fun a => if f a = g a then f a else none invFun := fun b => if f.symm b = g.symm b then f.symm b else none inv := fun a b => by have hf := @mem_iff_mem _ _ f a b have hg := @mem_iff_mem _ _ g a b simp only [Option.mem_def] at * split_ifs with h1 h2 h2 <;> try simp [hf] · contrapose! h2 rw [h2] rw [← h1, hf, h2] at hg simp only [mem_def, true_iff_iff, eq_self_iff_true] at hg rw [hg] · contrapose! h1 rw [h1] at hf h2 rw [← h2] at hg simp only [iff_true] at hf hg rw [hf, hg] } inf_le_left := fun _ _ _ _ => by simp only [coe_mk, mem_def]; split_ifs <;> simp [*] inf_le_right := fun _ _ _ _ => by simp only [coe_mk, mem_def]; split_ifs <;> simp [*] le_inf := fun f g h fg gh a b => by intro H have hf := fg a b H have hg := gh a b H simp only [Option.mem_def, PEquiv.coe_mk_apply] at * rw [hf, hg, if_pos rfl] } end Order end PEquiv namespace Equiv variable {α : Type*} {β : Type*} {γ : Type*} /-- Turns an `Equiv` into a `PEquiv` of the whole type. -/ def toPEquiv (f : α ≃ β) : α ≃. β where toFun := some ∘ f invFun := some ∘ f.symm inv := by simp [Equiv.eq_symm_apply, eq_comm] @[simp] theorem toPEquiv_refl : (Equiv.refl α).toPEquiv = PEquiv.refl α := rfl theorem toPEquiv_trans (f : α ≃ β) (g : β ≃ γ) : (f.trans g).toPEquiv = f.toPEquiv.trans g.toPEquiv := rfl theorem toPEquiv_symm (f : α ≃ β) : f.symm.toPEquiv = f.toPEquiv.symm := rfl theorem toPEquiv_apply (f : α ≃ β) (x : α) : f.toPEquiv x = some (f x) := rfl end Equiv
Data\PFun.lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Jeremy Avigad, Simon Hudon -/ import Mathlib.Data.Part import Mathlib.Data.Rel import Batteries.WF /-! # Partial functions This file defines partial functions. Partial functions are like functions, except they can also be "undefined" on some inputs. We define them as functions `α → Part β`. ## Definitions * `PFun α β`: Type of partial functions from `α` to `β`. Defined as `α → Part β` and denoted `α →. β`. * `PFun.Dom`: Domain of a partial function. Set of values on which it is defined. Not to be confused with the domain of a function `α → β`, which is a type (`α` presently). * `PFun.fn`: Evaluation of a partial function. Takes in an element and a proof it belongs to the partial function's `Dom`. * `PFun.asSubtype`: Returns a partial function as a function from its `Dom`. * `PFun.toSubtype`: Restricts the codomain of a function to a subtype. * `PFun.evalOpt`: Returns a partial function with a decidable `Dom` as a function `a → Option β`. * `PFun.lift`: Turns a function into a partial function. * `PFun.id`: The identity as a partial function. * `PFun.comp`: Composition of partial functions. * `PFun.restrict`: Restriction of a partial function to a smaller `Dom`. * `PFun.res`: Turns a function into a partial function with a prescribed domain. * `PFun.fix` : First return map of a partial function `f : α →. β ⊕ α`. * `PFun.fix_induction`: A recursion principle for `PFun.fix`. ### Partial functions as relations Partial functions can be considered as relations, so we specialize some `Rel` definitions to `PFun`: * `PFun.image`: Image of a set under a partial function. * `PFun.ran`: Range of a partial function. * `PFun.preimage`: Preimage of a set under a partial function. * `PFun.core`: Core of a set under a partial function. * `PFun.graph`: Graph of a partial function `a →. β`as a `Set (α × β)`. * `PFun.graph'`: Graph of a partial function `a →. β`as a `Rel α β`. ### `PFun α` as a monad Monad operations: * `PFun.pure`: The monad `pure` function, the constant `x` function. * `PFun.bind`: The monad `bind` function, pointwise `Part.bind` * `PFun.map`: The monad `map` function, pointwise `Part.map`. -/ open Function /-- `PFun α β`, or `α →. β`, is the type of partial functions from `α` to `β`. It is defined as `α → Part β`. -/ def PFun (α β : Type*) := α → Part β /-- `α →. β` is notation for the type `PFun α β` of partial functions from `α` to `β`. -/ infixr:25 " →. " => PFun namespace PFun variable {α β γ δ ε ι : Type*} instance inhabited : Inhabited (α →. β) := ⟨fun _ => Part.none⟩ /-- The domain of a partial function -/ def Dom (f : α →. β) : Set α := { a | (f a).Dom } @[simp] theorem mem_dom (f : α →. β) (x : α) : x ∈ Dom f ↔ ∃ y, y ∈ f x := by simp [Dom, Part.dom_iff_mem] @[simp] theorem dom_mk (p : α → Prop) (f : ∀ a, p a → β) : (PFun.Dom fun x => ⟨p x, f x⟩) = { x | p x } := rfl theorem dom_eq (f : α →. β) : Dom f = { x | ∃ y, y ∈ f x } := Set.ext (mem_dom f) /-- Evaluate a partial function -/ def fn (f : α →. β) (a : α) : Dom f a → β := (f a).get @[simp] theorem fn_apply (f : α →. β) (a : α) : f.fn a = (f a).get := rfl /-- Evaluate a partial function to return an `Option` -/ def evalOpt (f : α →. β) [D : DecidablePred (· ∈ Dom f)] (x : α) : Option β := @Part.toOption _ _ (D x) /-- Partial function extensionality -/ theorem ext' {f g : α →. β} (H1 : ∀ a, a ∈ Dom f ↔ a ∈ Dom g) (H2 : ∀ a p q, f.fn a p = g.fn a q) : f = g := funext fun a => Part.ext' (H1 a) (H2 a) theorem ext {f g : α →. β} (H : ∀ a b, b ∈ f a ↔ b ∈ g a) : f = g := funext fun a => Part.ext (H a) /-- Turns a partial function into a function out of its domain. -/ def asSubtype (f : α →. β) (s : f.Dom) : β := f.fn s s.2 /-- The type of partial functions `α →. β` is equivalent to the type of pairs `(p : α → Prop, f : Subtype p → β)`. -/ def equivSubtype : (α →. β) ≃ Σp : α → Prop, Subtype p → β := ⟨fun f => ⟨fun a => (f a).Dom, asSubtype f⟩, fun f x => ⟨f.1 x, fun h => f.2 ⟨x, h⟩⟩, fun f => funext fun a => Part.eta _, fun ⟨p, f⟩ => by dsimp; congr⟩ theorem asSubtype_eq_of_mem {f : α →. β} {x : α} {y : β} (fxy : y ∈ f x) (domx : x ∈ f.Dom) : f.asSubtype ⟨x, domx⟩ = y := Part.mem_unique (Part.get_mem _) fxy /-- Turn a total function into a partial function. -/ @[coe] protected def lift (f : α → β) : α →. β := fun a => Part.some (f a) instance coe : Coe (α → β) (α →. β) := ⟨PFun.lift⟩ @[simp] theorem coe_val (f : α → β) (a : α) : (f : α →. β) a = Part.some (f a) := rfl @[simp] theorem dom_coe (f : α → β) : (f : α →. β).Dom = Set.univ := rfl theorem lift_injective : Injective (PFun.lift : (α → β) → α →. β) := fun _ _ h => funext fun a => Part.some_injective <| congr_fun h a /-- Graph of a partial function `f` as the set of pairs `(x, f x)` where `x` is in the domain of `f`. -/ def graph (f : α →. β) : Set (α × β) := { p | p.2 ∈ f p.1 } /-- Graph of a partial function as a relation. `x` and `y` are related iff `f x` is defined and "equals" `y`. -/ def graph' (f : α →. β) : Rel α β := fun x y => y ∈ f x /-- The range of a partial function is the set of values `f x` where `x` is in the domain of `f`. -/ def ran (f : α →. β) : Set β := { b | ∃ a, b ∈ f a } /-- Restrict a partial function to a smaller domain. -/ def restrict (f : α →. β) {p : Set α} (H : p ⊆ f.Dom) : α →. β := fun x => (f x).restrict (x ∈ p) (@H x) @[simp] theorem mem_restrict {f : α →. β} {s : Set α} (h : s ⊆ f.Dom) (a : α) (b : β) : b ∈ f.restrict h a ↔ a ∈ s ∧ b ∈ f a := by simp [restrict] /-- Turns a function into a partial function with a prescribed domain. -/ def res (f : α → β) (s : Set α) : α →. β := (PFun.lift f).restrict s.subset_univ theorem mem_res (f : α → β) (s : Set α) (a : α) (b : β) : b ∈ res f s a ↔ a ∈ s ∧ f a = b := by simp [res, @eq_comm _ b] theorem res_univ (f : α → β) : PFun.res f Set.univ = f := rfl theorem dom_iff_graph (f : α →. β) (x : α) : x ∈ f.Dom ↔ ∃ y, (x, y) ∈ f.graph := Part.dom_iff_mem theorem lift_graph {f : α → β} {a b} : (a, b) ∈ (f : α →. β).graph ↔ f a = b := show (∃ _ : True, f a = b) ↔ f a = b by simp /-- The monad `pure` function, the total constant `x` function -/ protected def pure (x : β) : α →. β := fun _ => Part.some x /-- The monad `bind` function, pointwise `Part.bind` -/ def bind (f : α →. β) (g : β → α →. γ) : α →. γ := fun a => (f a).bind fun b => g b a @[simp] theorem bind_apply (f : α →. β) (g : β → α →. γ) (a : α) : f.bind g a = (f a).bind fun b => g b a := rfl /-- The monad `map` function, pointwise `Part.map` -/ def map (f : β → γ) (g : α →. β) : α →. γ := fun a => (g a).map f instance monad : Monad (PFun α) where pure := PFun.pure bind := PFun.bind map := PFun.map instance lawfulMonad : LawfulMonad (PFun α) := LawfulMonad.mk' (bind_pure_comp := fun f x => funext fun a => Part.bind_some_eq_map _ _) (id_map := fun f => by funext a; dsimp [Functor.map, PFun.map]; cases f a; rfl) (pure_bind := fun x f => funext fun a => Part.bind_some _ (f x)) (bind_assoc := fun f g k => funext fun a => (f a).bind_assoc (fun b => g b a) fun b => k b a) theorem pure_defined (p : Set α) (x : β) : p ⊆ (@PFun.pure α _ x).Dom := p.subset_univ theorem bind_defined {α β γ} (p : Set α) {f : α →. β} {g : β → α →. γ} (H1 : p ⊆ f.Dom) (H2 : ∀ x, p ⊆ (g x).Dom) : p ⊆ (f >>= g).Dom := fun a ha => (⟨H1 ha, H2 _ ha⟩ : (f >>= g).Dom a) /-- First return map. Transforms a partial function `f : α →. β ⊕ α` into the partial function `α →. β` which sends `a : α` to the first value in `β` it hits by iterating `f`, if such a value exists. By abusing notation to illustrate, either `f a` is in the `β` part of `β ⊕ α` (in which case `f.fix a` returns `f a`), or it is undefined (in which case `f.fix a` is undefined as well), or it is in the `α` part of `β ⊕ α` (in which case we repeat the procedure, so `f.fix a` will return `f.fix (f a)`). -/ def fix (f : α →. β ⊕ α) : α →. β := fun a => Part.assert (Acc (fun x y => Sum.inr x ∈ f y) a) fun h => WellFounded.fixF (fun a IH => Part.assert (f a).Dom fun hf => match e : (f a).get hf with | Sum.inl b => Part.some b | Sum.inr a' => IH a' ⟨hf, e⟩) a h theorem dom_of_mem_fix {f : α →. β ⊕ α} {a : α} {b : β} (h : b ∈ f.fix a) : (f a).Dom := by let ⟨h₁, h₂⟩ := Part.mem_assert_iff.1 h rw [WellFounded.fixFEq] at h₂; exact h₂.fst.fst theorem mem_fix_iff {f : α →. β ⊕ α} {a : α} {b : β} : b ∈ f.fix a ↔ Sum.inl b ∈ f a ∨ ∃ a', Sum.inr a' ∈ f a ∧ b ∈ f.fix a' := ⟨fun h => by let ⟨h₁, h₂⟩ := Part.mem_assert_iff.1 h rw [WellFounded.fixFEq] at h₂ simp only [Part.mem_assert_iff] at h₂ cases' h₂ with h₂ h₃ split at h₃ next e => simp only [Part.mem_some_iff] at h₃; subst b; exact Or.inl ⟨h₂, e⟩ next e => exact Or.inr ⟨_, ⟨_, e⟩, Part.mem_assert _ h₃⟩, fun h => by simp only [fix, Part.mem_assert_iff] rcases h with (⟨h₁, h₂⟩ | ⟨a', h, h₃⟩) · refine ⟨⟨_, fun y h' => ?_⟩, ?_⟩ · injection Part.mem_unique ⟨h₁, h₂⟩ h' · rw [WellFounded.fixFEq] -- Porting note: used to be simp [h₁, h₂] apply Part.mem_assert h₁ split next e => injection h₂.symm.trans e with h; simp [h] next e => injection h₂.symm.trans e · simp only [fix, Part.mem_assert_iff] at h₃ cases' h₃ with h₃ h₄ refine ⟨⟨_, fun y h' => ?_⟩, ?_⟩ · injection Part.mem_unique h h' with e exact e ▸ h₃ · cases' h with h₁ h₂ rw [WellFounded.fixFEq] -- Porting note: used to be simp [h₁, h₂, h₄] apply Part.mem_assert h₁ split next e => injection h₂.symm.trans e next e => injection h₂.symm.trans e; subst a'; exact h₄⟩ /-- If advancing one step from `a` leads to `b : β`, then `f.fix a = b` -/ theorem fix_stop {f : α →. β ⊕ α} {b : β} {a : α} (hb : Sum.inl b ∈ f a) : b ∈ f.fix a := by rw [PFun.mem_fix_iff] exact Or.inl hb /-- If advancing one step from `a` on `f` leads to `a' : α`, then `f.fix a = f.fix a'` -/ theorem fix_fwd_eq {f : α →. β ⊕ α} {a a' : α} (ha' : Sum.inr a' ∈ f a) : f.fix a = f.fix a' := by ext b; constructor · intro h obtain h' | ⟨a, h', e'⟩ := mem_fix_iff.1 h <;> cases Part.mem_unique ha' h' exact e' · intro h rw [PFun.mem_fix_iff] exact Or.inr ⟨a', ha', h⟩ theorem fix_fwd {f : α →. β ⊕ α} {b : β} {a a' : α} (hb : b ∈ f.fix a) (ha' : Sum.inr a' ∈ f a) : b ∈ f.fix a' := by rwa [← fix_fwd_eq ha'] /-- A recursion principle for `PFun.fix`. -/ @[elab_as_elim] def fixInduction {C : α → Sort*} {f : α →. β ⊕ α} {b : β} {a : α} (h : b ∈ f.fix a) (H : ∀ a', b ∈ f.fix a' → (∀ a'', Sum.inr a'' ∈ f a' → C a'') → C a') : C a := by have h₂ := (Part.mem_assert_iff.1 h).snd generalize_proofs at h₂ clear h induction' ‹Acc _ _› with a ha IH have h : b ∈ f.fix a := Part.mem_assert_iff.2 ⟨⟨a, ha⟩, h₂⟩ exact H a h fun a' fa' => IH a' fa' (Part.mem_assert_iff.1 (fix_fwd h fa')).snd theorem fixInduction_spec {C : α → Sort*} {f : α →. β ⊕ α} {b : β} {a : α} (h : b ∈ f.fix a) (H : ∀ a', b ∈ f.fix a' → (∀ a'', Sum.inr a'' ∈ f a' → C a'') → C a') : @fixInduction _ _ C _ _ _ h H = H a h fun a' h' => fixInduction (fix_fwd h h') H := by unfold fixInduction generalize_proofs induction ‹Acc _ _› rfl /-- Another induction lemma for `b ∈ f.fix a` which allows one to prove a predicate `P` holds for `a` given that `f a` inherits `P` from `a` and `P` holds for preimages of `b`. -/ @[elab_as_elim] def fixInduction' {C : α → Sort*} {f : α →. β ⊕ α} {b : β} {a : α} (h : b ∈ f.fix a) (hbase : ∀ a_final : α, Sum.inl b ∈ f a_final → C a_final) (hind : ∀ a₀ a₁ : α, b ∈ f.fix a₁ → Sum.inr a₁ ∈ f a₀ → C a₁ → C a₀) : C a := by refine fixInduction h fun a' h ih => ?_ rcases e : (f a').get (dom_of_mem_fix h) with b' | a'' <;> replace e : _ ∈ f a' := ⟨_, e⟩ · apply hbase convert e exact Part.mem_unique h (fix_stop e) · exact hind _ _ (fix_fwd h e) e (ih _ e) theorem fixInduction'_stop {C : α → Sort*} {f : α →. β ⊕ α} {b : β} {a : α} (h : b ∈ f.fix a) (fa : Sum.inl b ∈ f a) (hbase : ∀ a_final : α, Sum.inl b ∈ f a_final → C a_final) (hind : ∀ a₀ a₁ : α, b ∈ f.fix a₁ → Sum.inr a₁ ∈ f a₀ → C a₁ → C a₀) : @fixInduction' _ _ C _ _ _ h hbase hind = hbase a fa := by unfold fixInduction' rw [fixInduction_spec] -- Porting note: the explicit motive required because `simp` behaves differently refine Eq.rec (motive := fun x e ↦ Sum.casesOn x ?_ ?_ (Eq.trans (Part.get_eq_of_mem fa (dom_of_mem_fix h)) e) = hbase a fa) ?_ (Part.get_eq_of_mem fa (dom_of_mem_fix h)).symm simp theorem fixInduction'_fwd {C : α → Sort*} {f : α →. β ⊕ α} {b : β} {a a' : α} (h : b ∈ f.fix a) (h' : b ∈ f.fix a') (fa : Sum.inr a' ∈ f a) (hbase : ∀ a_final : α, Sum.inl b ∈ f a_final → C a_final) (hind : ∀ a₀ a₁ : α, b ∈ f.fix a₁ → Sum.inr a₁ ∈ f a₀ → C a₁ → C a₀) : @fixInduction' _ _ C _ _ _ h hbase hind = hind a a' h' fa (fixInduction' h' hbase hind) := by unfold fixInduction' rw [fixInduction_spec] -- Porting note: the explicit motive required because `simp` behaves differently refine Eq.rec (motive := fun x e => Sum.casesOn (motive := fun y => (f a).get (dom_of_mem_fix h) = y → C a) x ?_ ?_ (Eq.trans (Part.get_eq_of_mem fa (dom_of_mem_fix h)) e) = _) ?_ (Part.get_eq_of_mem fa (dom_of_mem_fix h)).symm simp variable (f : α →. β) /-- Image of a set under a partial function. -/ def image (s : Set α) : Set β := f.graph'.image s theorem image_def (s : Set α) : f.image s = { y | ∃ x ∈ s, y ∈ f x } := rfl theorem mem_image (y : β) (s : Set α) : y ∈ f.image s ↔ ∃ x ∈ s, y ∈ f x := Iff.rfl theorem image_mono {s t : Set α} (h : s ⊆ t) : f.image s ⊆ f.image t := Rel.image_mono _ h theorem image_inter (s t : Set α) : f.image (s ∩ t) ⊆ f.image s ∩ f.image t := Rel.image_inter _ s t theorem image_union (s t : Set α) : f.image (s ∪ t) = f.image s ∪ f.image t := Rel.image_union _ s t /-- Preimage of a set under a partial function. -/ def preimage (s : Set β) : Set α := Rel.image (fun x y => x ∈ f y) s theorem Preimage_def (s : Set β) : f.preimage s = { x | ∃ y ∈ s, y ∈ f x } := rfl @[simp] theorem mem_preimage (s : Set β) (x : α) : x ∈ f.preimage s ↔ ∃ y ∈ s, y ∈ f x := Iff.rfl theorem preimage_subset_dom (s : Set β) : f.preimage s ⊆ f.Dom := fun _ ⟨y, _, fxy⟩ => Part.dom_iff_mem.mpr ⟨y, fxy⟩ theorem preimage_mono {s t : Set β} (h : s ⊆ t) : f.preimage s ⊆ f.preimage t := Rel.preimage_mono _ h theorem preimage_inter (s t : Set β) : f.preimage (s ∩ t) ⊆ f.preimage s ∩ f.preimage t := Rel.preimage_inter _ s t theorem preimage_union (s t : Set β) : f.preimage (s ∪ t) = f.preimage s ∪ f.preimage t := Rel.preimage_union _ s t theorem preimage_univ : f.preimage Set.univ = f.Dom := by ext; simp [mem_preimage, mem_dom] theorem coe_preimage (f : α → β) (s : Set β) : (f : α →. β).preimage s = f ⁻¹' s := by ext; simp /-- Core of a set `s : Set β` with respect to a partial function `f : α →. β`. Set of all `a : α` such that `f a ∈ s`, if `f a` is defined. -/ def core (s : Set β) : Set α := f.graph'.core s theorem core_def (s : Set β) : f.core s = { x | ∀ y, y ∈ f x → y ∈ s } := rfl @[simp] theorem mem_core (x : α) (s : Set β) : x ∈ f.core s ↔ ∀ y, y ∈ f x → y ∈ s := Iff.rfl theorem compl_dom_subset_core (s : Set β) : f.Domᶜ ⊆ f.core s := fun x hx y fxy => absurd ((mem_dom f x).mpr ⟨y, fxy⟩) hx theorem core_mono {s t : Set β} (h : s ⊆ t) : f.core s ⊆ f.core t := Rel.core_mono _ h theorem core_inter (s t : Set β) : f.core (s ∩ t) = f.core s ∩ f.core t := Rel.core_inter _ s t theorem mem_core_res (f : α → β) (s : Set α) (t : Set β) (x : α) : x ∈ (res f s).core t ↔ x ∈ s → f x ∈ t := by simp [mem_core, mem_res] theorem core_res (f : α → β) (s : Set α) (t : Set β) : (res f s).core t = sᶜ ∪ f ⁻¹' t := by ext x rw [mem_core_res] by_cases h : x ∈ s <;> simp [h] theorem core_restrict (f : α → β) (s : Set β) : (f : α →. β).core s = s.preimage f := by ext x; simp [core_def] theorem preimage_subset_core (f : α →. β) (s : Set β) : f.preimage s ⊆ f.core s := fun _ ⟨y, ys, fxy⟩ y' fxy' => have : y = y' := Part.mem_unique fxy fxy' this ▸ ys theorem preimage_eq (f : α →. β) (s : Set β) : f.preimage s = f.core s ∩ f.Dom := Set.eq_of_subset_of_subset (Set.subset_inter (f.preimage_subset_core s) (f.preimage_subset_dom s)) fun x ⟨xcore, xdom⟩ => let y := (f x).get xdom have ys : y ∈ s := xcore _ (Part.get_mem _) show x ∈ f.preimage s from ⟨(f x).get xdom, ys, Part.get_mem _⟩ theorem core_eq (f : α →. β) (s : Set β) : f.core s = f.preimage s ∪ f.Domᶜ := by rw [preimage_eq, Set.inter_union_distrib_right, Set.union_comm (Dom f), Set.compl_union_self, Set.inter_univ, Set.union_eq_self_of_subset_right (f.compl_dom_subset_core s)] theorem preimage_asSubtype (f : α →. β) (s : Set β) : f.asSubtype ⁻¹' s = Subtype.val ⁻¹' f.preimage s := by ext x simp only [Set.mem_preimage, Set.mem_setOf_eq, PFun.asSubtype, PFun.mem_preimage] show f.fn x.val _ ∈ s ↔ ∃ y ∈ s, y ∈ f x.val exact Iff.intro (fun h => ⟨_, h, Part.get_mem _⟩) fun ⟨y, ys, fxy⟩ => have : f.fn x.val x.property ∈ f x.val := Part.get_mem _ Part.mem_unique fxy this ▸ ys /-- Turns a function into a partial function to a subtype. -/ def toSubtype (p : β → Prop) (f : α → β) : α →. Subtype p := fun a => ⟨p (f a), Subtype.mk _⟩ @[simp] theorem dom_toSubtype (p : β → Prop) (f : α → β) : (toSubtype p f).Dom = { a | p (f a) } := rfl @[simp] theorem toSubtype_apply (p : β → Prop) (f : α → β) (a : α) : toSubtype p f a = ⟨p (f a), Subtype.mk _⟩ := rfl theorem dom_toSubtype_apply_iff {p : β → Prop} {f : α → β} {a : α} : (toSubtype p f a).Dom ↔ p (f a) := Iff.rfl theorem mem_toSubtype_iff {p : β → Prop} {f : α → β} {a : α} {b : Subtype p} : b ∈ toSubtype p f a ↔ ↑b = f a := by rw [toSubtype_apply, Part.mem_mk_iff, exists_subtype_mk_eq_iff, eq_comm] /-- The identity as a partial function -/ protected def id (α : Type*) : α →. α := Part.some @[simp] theorem coe_id (α : Type*) : ((id : α → α) : α →. α) = PFun.id α := rfl @[simp] theorem id_apply (a : α) : PFun.id α a = Part.some a := rfl /-- Composition of partial functions as a partial function. -/ def comp (f : β →. γ) (g : α →. β) : α →. γ := fun a => (g a).bind f @[simp] theorem comp_apply (f : β →. γ) (g : α →. β) (a : α) : f.comp g a = (g a).bind f := rfl @[simp] theorem id_comp (f : α →. β) : (PFun.id β).comp f = f := ext fun _ _ => by simp @[simp] theorem comp_id (f : α →. β) : f.comp (PFun.id α) = f := ext fun _ _ => by simp @[simp] theorem dom_comp (f : β →. γ) (g : α →. β) : (f.comp g).Dom = g.preimage f.Dom := by ext simp_rw [mem_preimage, mem_dom, comp_apply, Part.mem_bind_iff, ← exists_and_right] rw [exists_comm] simp_rw [and_comm] @[simp] theorem preimage_comp (f : β →. γ) (g : α →. β) (s : Set γ) : (f.comp g).preimage s = g.preimage (f.preimage s) := by ext simp_rw [mem_preimage, comp_apply, Part.mem_bind_iff, ← exists_and_right, ← exists_and_left] rw [exists_comm] simp_rw [and_assoc, and_comm] @[simp] theorem Part.bind_comp (f : β →. γ) (g : α →. β) (a : Part α) : a.bind (f.comp g) = (a.bind g).bind f := by ext c simp_rw [Part.mem_bind_iff, comp_apply, Part.mem_bind_iff, ← exists_and_right, ← exists_and_left] rw [exists_comm] simp_rw [and_assoc] @[simp] theorem comp_assoc (f : γ →. δ) (g : β →. γ) (h : α →. β) : (f.comp g).comp h = f.comp (g.comp h) := ext fun _ _ => by simp only [comp_apply, Part.bind_comp] -- This can't be `simp` theorem coe_comp (g : β → γ) (f : α → β) : ((g ∘ f : α → γ) : α →. γ) = (g : β →. γ).comp f := ext fun _ _ => by simp only [coe_val, comp_apply, Function.comp, Part.bind_some] /-- Product of partial functions. -/ def prodLift (f : α →. β) (g : α →. γ) : α →. β × γ := fun x => ⟨(f x).Dom ∧ (g x).Dom, fun h => ((f x).get h.1, (g x).get h.2)⟩ @[simp] theorem dom_prodLift (f : α →. β) (g : α →. γ) : (f.prodLift g).Dom = { x | (f x).Dom ∧ (g x).Dom } := rfl theorem get_prodLift (f : α →. β) (g : α →. γ) (x : α) (h) : (f.prodLift g x).get h = ((f x).get h.1, (g x).get h.2) := rfl @[simp] theorem prodLift_apply (f : α →. β) (g : α →. γ) (x : α) : f.prodLift g x = ⟨(f x).Dom ∧ (g x).Dom, fun h => ((f x).get h.1, (g x).get h.2)⟩ := rfl theorem mem_prodLift {f : α →. β} {g : α →. γ} {x : α} {y : β × γ} : y ∈ f.prodLift g x ↔ y.1 ∈ f x ∧ y.2 ∈ g x := by trans ∃ hp hq, (f x).get hp = y.1 ∧ (g x).get hq = y.2 · simp only [prodLift, Part.mem_mk_iff, And.exists, Prod.ext_iff] -- Porting note: was just `[exists_and_left, exists_and_right]` · simp only [exists_and_left, exists_and_right, (· ∈ ·), Part.Mem] /-- Product of partial functions. -/ def prodMap (f : α →. γ) (g : β →. δ) : α × β →. γ × δ := fun x => ⟨(f x.1).Dom ∧ (g x.2).Dom, fun h => ((f x.1).get h.1, (g x.2).get h.2)⟩ @[simp] theorem dom_prodMap (f : α →. γ) (g : β →. δ) : (f.prodMap g).Dom = { x | (f x.1).Dom ∧ (g x.2).Dom } := rfl theorem get_prodMap (f : α →. γ) (g : β →. δ) (x : α × β) (h) : (f.prodMap g x).get h = ((f x.1).get h.1, (g x.2).get h.2) := rfl @[simp] theorem prodMap_apply (f : α →. γ) (g : β →. δ) (x : α × β) : f.prodMap g x = ⟨(f x.1).Dom ∧ (g x.2).Dom, fun h => ((f x.1).get h.1, (g x.2).get h.2)⟩ := rfl theorem mem_prodMap {f : α →. γ} {g : β →. δ} {x : α × β} {y : γ × δ} : y ∈ f.prodMap g x ↔ y.1 ∈ f x.1 ∧ y.2 ∈ g x.2 := by trans ∃ hp hq, (f x.1).get hp = y.1 ∧ (g x.2).get hq = y.2 · simp only [prodMap, Part.mem_mk_iff, And.exists, Prod.ext_iff] · simp only [exists_and_left, exists_and_right, (· ∈ ·), Part.Mem] @[simp] theorem prodLift_fst_comp_snd_comp (f : α →. γ) (g : β →. δ) : prodLift (f.comp ((Prod.fst : α × β → α) : α × β →. α)) (g.comp ((Prod.snd : α × β → β) : α × β →. β)) = prodMap f g := ext fun a => by simp @[simp] theorem prodMap_id_id : (PFun.id α).prodMap (PFun.id β) = PFun.id _ := ext fun _ _ ↦ by simp [eq_comm] @[simp] theorem prodMap_comp_comp (f₁ : α →. β) (f₂ : β →. γ) (g₁ : δ →. ε) (g₂ : ε →. ι) : (f₂.comp f₁).prodMap (g₂.comp g₁) = (f₂.prodMap g₂).comp (f₁.prodMap g₁) := -- by -- Porting note: was `by tidy`, below is a golfed version of the `tidy?` proof ext <| fun ⟨_, _⟩ ⟨_, _⟩ ↦ ⟨fun ⟨⟨⟨h1l1, h1l2⟩, ⟨h1r1, h1r2⟩⟩, h2⟩ ↦ ⟨⟨⟨h1l1, h1r1⟩, ⟨h1l2, h1r2⟩⟩, h2⟩, fun ⟨⟨⟨h1l1, h1r1⟩, ⟨h1l2, h1r2⟩⟩, h2⟩ ↦ ⟨⟨⟨h1l1, h1l2⟩, ⟨h1r1, h1r2⟩⟩, h2⟩⟩ end PFun
Data\Quot.lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import Mathlib.Init.Data.Quot import Mathlib.Logic.Relator import Mathlib.Logic.Unique import Mathlib.Mathport.Notation /-! # Quotient types This module extends the core library's treatment of quotient types (`Init.Core`). ## Tags quotient -/ variable {α : Sort*} {β : Sort*} namespace Setoid theorem ext {α : Sort*} : ∀ {s t : Setoid α}, (∀ a b, @Setoid.r α s a b ↔ @Setoid.r α t a b) → s = t | ⟨r, _⟩, ⟨p, _⟩, Eq => by have : r = p := funext fun a ↦ funext fun b ↦ propext <| Eq a b subst this rfl end Setoid namespace Quot variable {ra : α → α → Prop} {rb : β → β → Prop} {φ : Quot ra → Quot rb → Sort*} @[inherit_doc Quot.mk] local notation3:arg "⟦" a "⟧" => Quot.mk _ a @[elab_as_elim] protected theorem induction_on {α : Sort*} {r : α → α → Prop} {β : Quot r → Prop} (q : Quot r) (h : ∀ a, β (Quot.mk r a)) : β q := ind h q instance (r : α → α → Prop) [Inhabited α] : Inhabited (Quot r) := ⟨⟦default⟧⟩ protected instance Subsingleton [Subsingleton α] : Subsingleton (Quot ra) := ⟨fun x ↦ Quot.induction_on x fun _ ↦ Quot.ind fun _ ↦ congr_arg _ (Subsingleton.elim _ _)⟩ instance [Unique α] : Unique (Quot ra) := Unique.mk' _ /-- Recursion on two `Quotient` arguments `a` and `b`, result type depends on `⟦a⟧` and `⟦b⟧`. -/ protected def hrecOn₂ (qa : Quot ra) (qb : Quot rb) (f : ∀ a b, φ ⟦a⟧ ⟦b⟧) (ca : ∀ {b a₁ a₂}, ra a₁ a₂ → HEq (f a₁ b) (f a₂ b)) (cb : ∀ {a b₁ b₂}, rb b₁ b₂ → HEq (f a b₁) (f a b₂)) : φ qa qb := Quot.hrecOn (motive := fun qa ↦ φ qa qb) qa (fun a ↦ Quot.hrecOn qb (f a) (fun b₁ b₂ pb ↦ cb pb)) fun a₁ a₂ pa ↦ Quot.induction_on qb fun b ↦ have h₁ : HEq (@Quot.hrecOn _ _ (φ _) ⟦b⟧ (f a₁) (@cb _)) (f a₁ b) := by simp [heq_self_iff_true] have h₂ : HEq (f a₂ b) (@Quot.hrecOn _ _ (φ _) ⟦b⟧ (f a₂) (@cb _)) := by simp [heq_self_iff_true] (h₁.trans (ca pa)).trans h₂ /-- Map a function `f : α → β` such that `ra x y` implies `rb (f x) (f y)` to a map `Quot ra → Quot rb`. -/ protected def map (f : α → β) (h : (ra ⇒ rb) f f) : Quot ra → Quot rb := (Quot.lift fun x ↦ ⟦f x⟧) fun x y (h₁ : ra x y) ↦ Quot.sound <| h h₁ /-- If `ra` is a subrelation of `ra'`, then we have a natural map `Quot ra → Quot ra'`. -/ protected def mapRight {ra' : α → α → Prop} (h : ∀ a₁ a₂, ra a₁ a₂ → ra' a₁ a₂) : Quot ra → Quot ra' := Quot.map id h /-- Weaken the relation of a quotient. This is the same as `Quot.map id`. -/ def factor {α : Type*} (r s : α → α → Prop) (h : ∀ x y, r x y → s x y) : Quot r → Quot s := Quot.lift (Quot.mk s) fun x y rxy ↦ Quot.sound (h x y rxy) theorem factor_mk_eq {α : Type*} (r s : α → α → Prop) (h : ∀ x y, r x y → s x y) : factor r s h ∘ Quot.mk _ = Quot.mk _ := rfl variable {γ : Sort*} {r : α → α → Prop} {s : β → β → Prop} -- Porting note: used to be an Alias of `Quot.lift_mk`. theorem lift_mk (f : α → γ) (h : ∀ a₁ a₂, r a₁ a₂ → f a₁ = f a₂) (a : α) : Quot.lift f h (Quot.mk r a) = f a := rfl theorem liftOn_mk (a : α) (f : α → γ) (h : ∀ a₁ a₂, r a₁ a₂ → f a₁ = f a₂) : Quot.liftOn (Quot.mk r a) f h = f a := rfl @[simp] theorem surjective_lift {f : α → γ} (h : ∀ a₁ a₂, r a₁ a₂ → f a₁ = f a₂) : Function.Surjective (lift f h) ↔ Function.Surjective f := ⟨fun hf => hf.comp Quot.exists_rep, fun hf y => let ⟨x, hx⟩ := hf y; ⟨Quot.mk _ x, hx⟩⟩ /-- Descends a function `f : α → β → γ` to quotients of `α` and `β`. -/ -- Porting note: removed `@[elab_as_elim]`, gave "unexpected resulting type γ" -- porting note (#11083): removed `@[reducible]` because it caused extremely slow `simp` protected def lift₂ (f : α → β → γ) (hr : ∀ a b₁ b₂, s b₁ b₂ → f a b₁ = f a b₂) (hs : ∀ a₁ a₂ b, r a₁ a₂ → f a₁ b = f a₂ b) (q₁ : Quot r) (q₂ : Quot s) : γ := Quot.lift (fun a ↦ Quot.lift (f a) (hr a)) (fun a₁ a₂ ha ↦ funext fun q ↦ Quot.induction_on q fun b ↦ hs a₁ a₂ b ha) q₁ q₂ @[simp] theorem lift₂_mk (f : α → β → γ) (hr : ∀ a b₁ b₂, s b₁ b₂ → f a b₁ = f a b₂) (hs : ∀ a₁ a₂ b, r a₁ a₂ → f a₁ b = f a₂ b) (a : α) (b : β) : Quot.lift₂ f hr hs (Quot.mk r a) (Quot.mk s b) = f a b := rfl /-- Descends a function `f : α → β → γ` to quotients of `α` and `β` and applies it. -/ -- porting note (#11083): removed `@[elab_as_elim]`, gave "unexpected resulting type γ" -- porting note (#11083): removed `@[reducible]` because it caused extremely slow `simp` protected def liftOn₂ (p : Quot r) (q : Quot s) (f : α → β → γ) (hr : ∀ a b₁ b₂, s b₁ b₂ → f a b₁ = f a b₂) (hs : ∀ a₁ a₂ b, r a₁ a₂ → f a₁ b = f a₂ b) : γ := Quot.lift₂ f hr hs p q @[simp] theorem liftOn₂_mk (a : α) (b : β) (f : α → β → γ) (hr : ∀ a b₁ b₂, s b₁ b₂ → f a b₁ = f a b₂) (hs : ∀ a₁ a₂ b, r a₁ a₂ → f a₁ b = f a₂ b) : Quot.liftOn₂ (Quot.mk r a) (Quot.mk s b) f hr hs = f a b := rfl variable {t : γ → γ → Prop} /-- Descends a function `f : α → β → γ` to quotients of `α` and `β` with values in a quotient of `γ`. -/ protected def map₂ (f : α → β → γ) (hr : ∀ a b₁ b₂, s b₁ b₂ → t (f a b₁) (f a b₂)) (hs : ∀ a₁ a₂ b, r a₁ a₂ → t (f a₁ b) (f a₂ b)) (q₁ : Quot r) (q₂ : Quot s) : Quot t := Quot.lift₂ (fun a b ↦ Quot.mk t <| f a b) (fun a b₁ b₂ hb ↦ Quot.sound (hr a b₁ b₂ hb)) (fun a₁ a₂ b ha ↦ Quot.sound (hs a₁ a₂ b ha)) q₁ q₂ @[simp] theorem map₂_mk (f : α → β → γ) (hr : ∀ a b₁ b₂, s b₁ b₂ → t (f a b₁) (f a b₂)) (hs : ∀ a₁ a₂ b, r a₁ a₂ → t (f a₁ b) (f a₂ b)) (a : α) (b : β) : Quot.map₂ f hr hs (Quot.mk r a) (Quot.mk s b) = Quot.mk t (f a b) := rfl /-- A binary version of `Quot.recOnSubsingleton`. -/ -- porting note (#11083): removed `@[reducible]` because it caused extremely slow `simp` @[elab_as_elim] protected def recOnSubsingleton₂ {φ : Quot r → Quot s → Sort*} [h : ∀ a b, Subsingleton (φ ⟦a⟧ ⟦b⟧)] (q₁ : Quot r) (q₂ : Quot s) (f : ∀ a b, φ ⟦a⟧ ⟦b⟧) : φ q₁ q₂ := @Quot.recOnSubsingleton _ r (fun q ↦ φ q q₂) (fun a ↦ Quot.ind (β := fun b ↦ Subsingleton (φ (mk r a) b)) (h a) q₂) q₁ fun a ↦ Quot.recOnSubsingleton q₂ fun b ↦ f a b @[elab_as_elim] protected theorem induction_on₂ {δ : Quot r → Quot s → Prop} (q₁ : Quot r) (q₂ : Quot s) (h : ∀ a b, δ (Quot.mk r a) (Quot.mk s b)) : δ q₁ q₂ := Quot.ind (β := fun a ↦ δ a q₂) (fun a₁ ↦ Quot.ind (fun a₂ ↦ h a₁ a₂) q₂) q₁ @[elab_as_elim] protected theorem induction_on₃ {δ : Quot r → Quot s → Quot t → Prop} (q₁ : Quot r) (q₂ : Quot s) (q₃ : Quot t) (h : ∀ a b c, δ (Quot.mk r a) (Quot.mk s b) (Quot.mk t c)) : δ q₁ q₂ q₃ := Quot.ind (β := fun a ↦ δ a q₂ q₃) (fun a₁ ↦ Quot.ind (β := fun b ↦ δ _ b q₃) (fun a₂ ↦ Quot.ind (fun a₃ ↦ h a₁ a₂ a₃) q₃) q₂) q₁ instance lift.decidablePred (r : α → α → Prop) (f : α → Prop) (h : ∀ a b, r a b → f a = f b) [hf : DecidablePred f] : DecidablePred (Quot.lift f h) := fun q ↦ Quot.recOnSubsingleton (motive := fun _ ↦ Decidable _) q hf /-- Note that this provides `DecidableRel (Quot.Lift₂ f ha hb)` when `α = β`. -/ instance lift₂.decidablePred (r : α → α → Prop) (s : β → β → Prop) (f : α → β → Prop) (ha : ∀ a b₁ b₂, s b₁ b₂ → f a b₁ = f a b₂) (hb : ∀ a₁ a₂ b, r a₁ a₂ → f a₁ b = f a₂ b) [hf : ∀ a, DecidablePred (f a)] (q₁ : Quot r) : DecidablePred (Quot.lift₂ f ha hb q₁) := fun q₂ ↦ Quot.recOnSubsingleton₂ q₁ q₂ hf instance (r : α → α → Prop) (q : Quot r) (f : α → Prop) (h : ∀ a b, r a b → f a = f b) [DecidablePred f] : Decidable (Quot.liftOn q f h) := Quot.lift.decidablePred _ _ _ _ instance (r : α → α → Prop) (s : β → β → Prop) (q₁ : Quot r) (q₂ : Quot s) (f : α → β → Prop) (ha : ∀ a b₁ b₂, s b₁ b₂ → f a b₁ = f a b₂) (hb : ∀ a₁ a₂ b, r a₁ a₂ → f a₁ b = f a₂ b) [∀ a, DecidablePred (f a)] : Decidable (Quot.liftOn₂ q₁ q₂ f ha hb) := Quot.lift₂.decidablePred _ _ _ _ _ _ _ end Quot namespace Quotient variable [sa : Setoid α] [sb : Setoid β] variable {φ : Quotient sa → Quotient sb → Sort*} -- Porting note: in mathlib3 this notation took the Setoid as an instance-implicit argument, -- now it's explicit but left as a metavariable. -- We have not yet decided which one works best, since the setoid instance can't always be -- reliably found but it can't always be inferred from the expected type either. -- See also: https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/confusion.20between.20equivalence.20and.20instance.20setoid/near/360822354 @[inherit_doc Quotient.mk] notation3:arg "⟦" a "⟧" => Quotient.mk _ a instance instInhabitedQuotient (s : Setoid α) [Inhabited α] : Inhabited (Quotient s) := ⟨⟦default⟧⟩ instance instSubsingletonQuotient (s : Setoid α) [Subsingleton α] : Subsingleton (Quotient s) := Quot.Subsingleton instance instUniqueQuotient (s : Setoid α) [Unique α] : Unique (Quotient s) := Unique.mk' _ instance {α : Type*} [Setoid α] : IsEquiv α (· ≈ ·) where refl := Setoid.refl symm _ _ := Setoid.symm trans _ _ _ := Setoid.trans /-- Induction on two `Quotient` arguments `a` and `b`, result type depends on `⟦a⟧` and `⟦b⟧`. -/ protected def hrecOn₂ (qa : Quotient sa) (qb : Quotient sb) (f : ∀ a b, φ ⟦a⟧ ⟦b⟧) (c : ∀ a₁ b₁ a₂ b₂, a₁ ≈ a₂ → b₁ ≈ b₂ → HEq (f a₁ b₁) (f a₂ b₂)) : φ qa qb := Quot.hrecOn₂ qa qb f (fun p ↦ c _ _ _ _ p (Setoid.refl _)) fun p ↦ c _ _ _ _ (Setoid.refl _) p /-- Map a function `f : α → β` that sends equivalent elements to equivalent elements to a function `Quotient sa → Quotient sb`. Useful to define unary operations on quotients. -/ protected def map (f : α → β) (h : ((· ≈ ·) ⇒ (· ≈ ·)) f f) : Quotient sa → Quotient sb := Quot.map f h @[simp] theorem map_mk (f : α → β) (h : ((· ≈ ·) ⇒ (· ≈ ·)) f f) (x : α) : Quotient.map f h (⟦x⟧ : Quotient sa) = (⟦f x⟧ : Quotient sb) := rfl variable {γ : Sort*} [sc : Setoid γ] /-- Map a function `f : α → β → γ` that sends equivalent elements to equivalent elements to a function `f : Quotient sa → Quotient sb → Quotient sc`. Useful to define binary operations on quotients. -/ protected def map₂ (f : α → β → γ) (h : ((· ≈ ·) ⇒ (· ≈ ·) ⇒ (· ≈ ·)) f f) : Quotient sa → Quotient sb → Quotient sc := Quotient.lift₂ (fun x y ↦ ⟦f x y⟧) fun _ _ _ _ h₁ h₂ ↦ Quot.sound <| h h₁ h₂ @[simp] theorem map₂_mk (f : α → β → γ) (h : ((· ≈ ·) ⇒ (· ≈ ·) ⇒ (· ≈ ·)) f f) (x : α) (y : β) : Quotient.map₂ f h (⟦x⟧ : Quotient sa) (⟦y⟧ : Quotient sb) = (⟦f x y⟧ : Quotient sc) := rfl instance lift.decidablePred (f : α → Prop) (h : ∀ a b, a ≈ b → f a = f b) [DecidablePred f] : DecidablePred (Quotient.lift f h) := Quot.lift.decidablePred _ _ _ /-- Note that this provides `DecidableRel (Quotient.lift₂ f h)` when `α = β`. -/ instance lift₂.decidablePred (f : α → β → Prop) (h : ∀ a₁ b₁ a₂ b₂, a₁ ≈ a₂ → b₁ ≈ b₂ → f a₁ b₁ = f a₂ b₂) [hf : ∀ a, DecidablePred (f a)] (q₁ : Quotient sa) : DecidablePred (Quotient.lift₂ f h q₁) := fun q₂ ↦ Quotient.recOnSubsingleton₂ q₁ q₂ hf instance (q : Quotient sa) (f : α → Prop) (h : ∀ a b, a ≈ b → f a = f b) [DecidablePred f] : Decidable (Quotient.liftOn q f h) := Quotient.lift.decidablePred _ _ _ instance (q₁ : Quotient sa) (q₂ : Quotient sb) (f : α → β → Prop) (h : ∀ a₁ b₁ a₂ b₂, a₁ ≈ a₂ → b₁ ≈ b₂ → f a₁ b₁ = f a₂ b₂) [∀ a, DecidablePred (f a)] : Decidable (Quotient.liftOn₂ q₁ q₂ f h) := Quotient.lift₂.decidablePred _ _ _ _ end Quotient theorem Quot.eq {α : Type*} {r : α → α → Prop} {x y : α} : Quot.mk r x = Quot.mk r y ↔ EqvGen r x y := ⟨Quot.exact r, Quot.EqvGen_sound⟩ @[simp] theorem Quotient.eq [r : Setoid α] {x y : α} : Quotient.mk r x = ⟦y⟧ ↔ x ≈ y := ⟨Quotient.exact, Quotient.sound⟩ theorem Quotient.forall {α : Sort*} {s : Setoid α} {p : Quotient s → Prop} : (∀ a, p a) ↔ ∀ a : α, p ⟦a⟧ := ⟨fun h _ ↦ h _, fun h a ↦ a.ind h⟩ theorem Quotient.exists {α : Sort*} {s : Setoid α} {p : Quotient s → Prop} : (∃ a, p a) ↔ ∃ a : α, p ⟦a⟧ := ⟨fun ⟨q, hq⟩ ↦ q.ind (motive := (p · → _)) .intro hq, fun ⟨a, ha⟩ ↦ ⟨⟦a⟧, ha⟩⟩ @[simp] theorem Quotient.lift_mk [s : Setoid α] (f : α → β) (h : ∀ a b : α, a ≈ b → f a = f b) (x : α) : Quotient.lift f h (Quotient.mk s x) = f x := rfl @[simp] theorem Quotient.lift_comp_mk [Setoid α] (f : α → β) (h : ∀ a b : α, a ≈ b → f a = f b) : Quotient.lift f h ∘ Quotient.mk _ = f := rfl @[simp] theorem Quotient.lift₂_mk {α : Sort*} {β : Sort*} {γ : Sort*} [Setoid α] [Setoid β] (f : α → β → γ) (h : ∀ (a₁ : α) (a₂ : β) (b₁ : α) (b₂ : β), a₁ ≈ b₁ → a₂ ≈ b₂ → f a₁ a₂ = f b₁ b₂) (a : α) (b : β) : Quotient.lift₂ f h (Quotient.mk _ a) (Quotient.mk _ b) = f a b := rfl theorem Quotient.liftOn_mk [s : Setoid α] (f : α → β) (h : ∀ a b : α, a ≈ b → f a = f b) (x : α) : Quotient.liftOn (Quotient.mk s x) f h = f x := rfl @[simp] theorem Quotient.liftOn₂_mk {α : Sort*} {β : Sort*} [Setoid α] (f : α → α → β) (h : ∀ a₁ a₂ b₁ b₂ : α, a₁ ≈ b₁ → a₂ ≈ b₂ → f a₁ a₂ = f b₁ b₂) (x y : α) : Quotient.liftOn₂ (Quotient.mk _ x) (Quotient.mk _ y) f h = f x y := rfl /-- `Quot.mk r` is a surjective function. -/ theorem surjective_quot_mk (r : α → α → Prop) : Function.Surjective (Quot.mk r) := Quot.exists_rep /-- `Quotient.mk` is a surjective function. -/ theorem surjective_quotient_mk {α : Sort*} (s : Setoid α) : Function.Surjective (Quotient.mk s) := Quot.exists_rep /-- `Quotient.mk'` is a surjective function. -/ theorem surjective_quotient_mk' (α : Sort*) [s : Setoid α] : Function.Surjective (Quotient.mk' : α → Quotient s) := Quot.exists_rep /-- Choose an element of the equivalence class using the axiom of choice. Sound but noncomputable. -/ noncomputable def Quot.out {r : α → α → Prop} (q : Quot r) : α := Classical.choose (Quot.exists_rep q) /-- Unwrap the VM representation of a quotient to obtain an element of the equivalence class. Computable but unsound. -/ unsafe def Quot.unquot {r : α → α → Prop} : Quot r → α := cast lcProof -- Porting note: was `unchecked_cast` before, which unfolds to `cast undefined` @[simp] theorem Quot.out_eq {r : α → α → Prop} (q : Quot r) : Quot.mk r q.out = q := Classical.choose_spec (Quot.exists_rep q) /-- Choose an element of the equivalence class using the axiom of choice. Sound but noncomputable. -/ noncomputable def Quotient.out [s : Setoid α] : Quotient s → α := Quot.out @[simp] theorem Quotient.out_eq [s : Setoid α] (q : Quotient s) : ⟦q.out⟧ = q := Quot.out_eq q theorem Quotient.mk_out [Setoid α] (a : α) : ⟦a⟧.out ≈ a := Quotient.exact (Quotient.out_eq _) theorem Quotient.mk_eq_iff_out [s : Setoid α] {x : α} {y : Quotient s} : ⟦x⟧ = y ↔ x ≈ Quotient.out y := by refine Iff.trans ?_ Quotient.eq rw [Quotient.out_eq y] theorem Quotient.eq_mk_iff_out [s : Setoid α] {x : Quotient s} {y : α} : x = ⟦y⟧ ↔ Quotient.out x ≈ y := by refine Iff.trans ?_ Quotient.eq rw [Quotient.out_eq x] @[simp] theorem Quotient.out_equiv_out {s : Setoid α} {x y : Quotient s} : x.out ≈ y.out ↔ x = y := by rw [← Quotient.eq_mk_iff_out, Quotient.out_eq] theorem Quotient.out_injective {s : Setoid α} : Function.Injective (@Quotient.out α s) := fun _ _ h ↦ Quotient.out_equiv_out.1 <| h ▸ Setoid.refl _ @[simp] theorem Quotient.out_inj {s : Setoid α} {x y : Quotient s} : x.out = y.out ↔ x = y := ⟨fun h ↦ Quotient.out_injective h, fun h ↦ h ▸ rfl⟩ section Pi instance piSetoid {ι : Sort*} {α : ι → Sort*} [∀ i, Setoid (α i)] : Setoid (∀ i, α i) where r a b := ∀ i, a i ≈ b i iseqv := ⟨fun _ _ ↦ Setoid.refl _, fun h _ ↦ Setoid.symm (h _), fun h₁ h₂ _ ↦ Setoid.trans (h₁ _) (h₂ _)⟩ /-- Given a function `f : Π i, Quotient (S i)`, returns the class of functions `Π i, α i` sending each `i` to an element of the class `f i`. -/ noncomputable def Quotient.choice {ι : Type*} {α : ι → Type*} [S : ∀ i, Setoid (α i)] (f : ∀ i, Quotient (S i)) : @Quotient (∀ i, α i) (by infer_instance) := ⟦fun i ↦ (f i).out⟧ @[simp] theorem Quotient.choice_eq {ι : Type*} {α : ι → Type*} [∀ i, Setoid (α i)] (f : ∀ i, α i) : (Quotient.choice fun i ↦ ⟦f i⟧) = ⟦f⟧ := Quotient.sound fun _ ↦ Quotient.mk_out _ @[elab_as_elim] theorem Quotient.induction_on_pi {ι : Type*} {α : ι → Sort*} [s : ∀ i, Setoid (α i)] {p : (∀ i, Quotient (s i)) → Prop} (f : ∀ i, Quotient (s i)) (h : ∀ a : ∀ i, α i, p fun i ↦ ⟦a i⟧) : p f := by rw [← (funext fun i ↦ Quotient.out_eq (f i) : (fun i ↦ ⟦(f i).out⟧) = f)] apply h end Pi theorem nonempty_quotient_iff (s : Setoid α) : Nonempty (Quotient s) ↔ Nonempty α := ⟨fun ⟨a⟩ ↦ Quotient.inductionOn a Nonempty.intro, fun ⟨a⟩ ↦ ⟨⟦a⟧⟩⟩ /-! ### Truncation -/ theorem true_equivalence : @Equivalence α fun _ _ ↦ True := ⟨fun _ ↦ trivial, fun _ ↦ trivial, fun _ _ ↦ trivial⟩ /-- Always-true relation as a `Setoid`. Note that in later files the preferred spelling is `⊤ : Setoid α`. -/ def trueSetoid : Setoid α := ⟨_, true_equivalence⟩ /-- `Trunc α` is the quotient of `α` by the always-true relation. This is related to the propositional truncation in HoTT, and is similar in effect to `Nonempty α`, but unlike `Nonempty α`, `Trunc α` is data, so the VM representation is the same as `α`, and so this can be used to maintain computability. -/ def Trunc.{u} (α : Sort u) : Sort u := @Quotient α trueSetoid namespace Trunc /-- Constructor for `Trunc α` -/ def mk (a : α) : Trunc α := Quot.mk _ a instance [Inhabited α] : Inhabited (Trunc α) := ⟨mk default⟩ /-- Any constant function lifts to a function out of the truncation -/ def lift (f : α → β) (c : ∀ a b : α, f a = f b) : Trunc α → β := Quot.lift f fun a b _ ↦ c a b theorem ind {β : Trunc α → Prop} : (∀ a : α, β (mk a)) → ∀ q : Trunc α, β q := Quot.ind protected theorem lift_mk (f : α → β) (c) (a : α) : lift f c (mk a) = f a := rfl /-- Lift a constant function on `q : Trunc α`. -/ -- Porting note: removed `@[elab_as_elim]` because it gave "unexpected eliminator resulting type" -- porting note (#11083): removed `@[reducible]` because it caused extremely slow `simp` protected def liftOn (q : Trunc α) (f : α → β) (c : ∀ a b : α, f a = f b) : β := lift f c q @[elab_as_elim] protected theorem induction_on {β : Trunc α → Prop} (q : Trunc α) (h : ∀ a, β (mk a)) : β q := ind h q theorem exists_rep (q : Trunc α) : ∃ a : α, mk a = q := Quot.exists_rep q @[elab_as_elim] protected theorem induction_on₂ {C : Trunc α → Trunc β → Prop} (q₁ : Trunc α) (q₂ : Trunc β) (h : ∀ a b, C (mk a) (mk b)) : C q₁ q₂ := Trunc.induction_on q₁ fun a₁ ↦ Trunc.induction_on q₂ (h a₁) protected theorem eq (a b : Trunc α) : a = b := Trunc.induction_on₂ a b fun _ _ ↦ Quot.sound trivial instance instSubsingletonTrunc : Subsingleton (Trunc α) := ⟨Trunc.eq⟩ /-- The `bind` operator for the `Trunc` monad. -/ def bind (q : Trunc α) (f : α → Trunc β) : Trunc β := Trunc.liftOn q f fun _ _ ↦ Trunc.eq _ _ /-- A function `f : α → β` defines a function `map f : Trunc α → Trunc β`. -/ def map (f : α → β) (q : Trunc α) : Trunc β := bind q (Trunc.mk ∘ f) instance : Monad Trunc where pure := @Trunc.mk bind := @Trunc.bind instance : LawfulMonad Trunc where id_map _ := Trunc.eq _ _ pure_bind _ _ := rfl bind_assoc _ _ _ := Trunc.eq _ _ -- Porting note: the fields below are new in Lean 4 map_const := rfl seqLeft_eq _ _ := Trunc.eq _ _ seqRight_eq _ _ := Trunc.eq _ _ pure_seq _ _ := rfl bind_pure_comp _ _ := rfl bind_map _ _ := rfl variable {C : Trunc α → Sort*} /-- Recursion/induction principle for `Trunc`. -/ -- porting note (#11083): removed `@[reducible]` because it caused extremely slow `simp` @[elab_as_elim] protected def rec (f : ∀ a, C (mk a)) (h : ∀ a b : α, (Eq.ndrec (f a) (Trunc.eq (mk a) (mk b)) : C (mk b)) = f b) (q : Trunc α) : C q := Quot.rec f (fun a b _ ↦ h a b) q /-- A version of `Trunc.rec` taking `q : Trunc α` as the first argument. -/ -- porting note (#11083): removed `@[reducible]` because it caused extremely slow `simp` @[elab_as_elim] protected def recOn (q : Trunc α) (f : ∀ a, C (mk a)) (h : ∀ a b : α, (Eq.ndrec (f a) (Trunc.eq (mk a) (mk b)) : C (mk b)) = f b) : C q := Trunc.rec f h q /-- A version of `Trunc.recOn` assuming the codomain is a `Subsingleton`. -/ -- porting note (#11083)s: removed `@[reducible]` because it caused extremely slow `simp` @[elab_as_elim] protected def recOnSubsingleton [∀ a, Subsingleton (C (mk a))] (q : Trunc α) (f : ∀ a, C (mk a)) : C q := Trunc.rec f (fun _ b ↦ Subsingleton.elim _ (f b)) q /-- Noncomputably extract a representative of `Trunc α` (using the axiom of choice). -/ noncomputable def out : Trunc α → α := Quot.out @[simp] theorem out_eq (q : Trunc α) : mk q.out = q := Trunc.eq _ _ protected theorem nonempty (q : Trunc α) : Nonempty α := nonempty_of_exists q.exists_rep end Trunc /-! ### `Quotient` with implicit `Setoid` -/ namespace Quotient variable {γ : Sort*} {φ : Sort*} {s₁ : Setoid α} {s₂ : Setoid β} {s₃ : Setoid γ} /-! Versions of quotient definitions and lemmas ending in `'` use unification instead of typeclass inference for inferring the `Setoid` argument. This is useful when there are several different quotient relations on a type, for example quotient groups, rings and modules. -/ -- TODO: this whole section can probably be replaced `Quotient.mk`, with explicit parameter -- Porting note: Quotient.mk' is the equivalent of Lean 3's `Quotient.mk` /-- A version of `Quotient.mk` taking `{s : Setoid α}` as an implicit argument instead of an instance argument. -/ protected def mk'' (a : α) : Quotient s₁ := Quot.mk s₁.1 a /-- `Quotient.mk''` is a surjective function. -/ theorem surjective_Quotient_mk'' : Function.Surjective (Quotient.mk'' : α → Quotient s₁) := Quot.exists_rep /-- A version of `Quotient.liftOn` taking `{s : Setoid α}` as an implicit argument instead of an instance argument. -/ -- Porting note: removed `@[elab_as_elim]` because it gave "unexpected eliminator resulting type" -- porting note (#11083): removed `@[reducible]` because it caused extremely slow `simp` protected def liftOn' (q : Quotient s₁) (f : α → φ) (h : ∀ a b, @Setoid.r α s₁ a b → f a = f b) : φ := Quotient.liftOn q f h @[simp] protected theorem liftOn'_mk'' (f : α → φ) (h) (x : α) : Quotient.liftOn' (@Quotient.mk'' _ s₁ x) f h = f x := rfl @[simp] lemma surjective_liftOn' {f : α → φ} (h) : Function.Surjective (fun x : Quotient s₁ ↦ x.liftOn' f h) ↔ Function.Surjective f := Quot.surjective_lift _ /-- A version of `Quotient.liftOn₂` taking `{s₁ : Setoid α} {s₂ : Setoid β}` as implicit arguments instead of instance arguments. -/ -- Porting note: removed `@[elab_as_elim]` because it gave "unexpected eliminator resulting type" -- porting note (#11083): removed `@[reducible]` because it caused extremely slow `simp` protected def liftOn₂' (q₁ : Quotient s₁) (q₂ : Quotient s₂) (f : α → β → γ) (h : ∀ a₁ a₂ b₁ b₂, @Setoid.r α s₁ a₁ b₁ → @Setoid.r β s₂ a₂ b₂ → f a₁ a₂ = f b₁ b₂) : γ := Quotient.liftOn₂ q₁ q₂ f h @[simp] protected theorem liftOn₂'_mk'' (f : α → β → γ) (h) (a : α) (b : β) : Quotient.liftOn₂' (@Quotient.mk'' _ s₁ a) (@Quotient.mk'' _ s₂ b) f h = f a b := rfl /-- A version of `Quotient.ind` taking `{s : Setoid α}` as an implicit argument instead of an instance argument. -/ @[elab_as_elim] protected theorem ind' {p : Quotient s₁ → Prop} (h : ∀ a, p (Quotient.mk'' a)) (q : Quotient s₁) : p q := Quotient.ind h q /-- A version of `Quotient.ind₂` taking `{s₁ : Setoid α} {s₂ : Setoid β}` as implicit arguments instead of instance arguments. -/ @[elab_as_elim] protected theorem ind₂' {p : Quotient s₁ → Quotient s₂ → Prop} (h : ∀ a₁ a₂, p (Quotient.mk'' a₁) (Quotient.mk'' a₂)) (q₁ : Quotient s₁) (q₂ : Quotient s₂) : p q₁ q₂ := Quotient.ind₂ h q₁ q₂ /-- A version of `Quotient.inductionOn` taking `{s : Setoid α}` as an implicit argument instead of an instance argument. -/ @[elab_as_elim] protected theorem inductionOn' {p : Quotient s₁ → Prop} (q : Quotient s₁) (h : ∀ a, p (Quotient.mk'' a)) : p q := Quotient.inductionOn q h /-- A version of `Quotient.inductionOn₂` taking `{s₁ : Setoid α} {s₂ : Setoid β}` as implicit arguments instead of instance arguments. -/ @[elab_as_elim] protected theorem inductionOn₂' {p : Quotient s₁ → Quotient s₂ → Prop} (q₁ : Quotient s₁) (q₂ : Quotient s₂) (h : ∀ a₁ a₂, p (Quotient.mk'' a₁) (Quotient.mk'' a₂)) : p q₁ q₂ := Quotient.inductionOn₂ q₁ q₂ h /-- A version of `Quotient.inductionOn₃` taking `{s₁ : Setoid α} {s₂ : Setoid β} {s₃ : Setoid γ}` as implicit arguments instead of instance arguments. -/ @[elab_as_elim] protected theorem inductionOn₃' {p : Quotient s₁ → Quotient s₂ → Quotient s₃ → Prop} (q₁ : Quotient s₁) (q₂ : Quotient s₂) (q₃ : Quotient s₃) (h : ∀ a₁ a₂ a₃, p (Quotient.mk'' a₁) (Quotient.mk'' a₂) (Quotient.mk'' a₃)) : p q₁ q₂ q₃ := Quotient.inductionOn₃ q₁ q₂ q₃ h /-- A version of `Quotient.recOnSubsingleton` taking `{s₁ : Setoid α}` as an implicit argument instead of an instance argument. -/ @[elab_as_elim] protected def recOnSubsingleton' {φ : Quotient s₁ → Sort*} [∀ a, Subsingleton (φ ⟦a⟧)] (q : Quotient s₁) (f : ∀ a, φ (Quotient.mk'' a)) : φ q := Quotient.recOnSubsingleton q f /-- A version of `Quotient.recOnSubsingleton₂` taking `{s₁ : Setoid α} {s₂ : Setoid α}` as implicit arguments instead of instance arguments. -/ -- porting note (#11083): removed `@[reducible]` because it caused extremely slow `simp` @[elab_as_elim] protected def recOnSubsingleton₂' {φ : Quotient s₁ → Quotient s₂ → Sort*} [∀ a b, Subsingleton (φ ⟦a⟧ ⟦b⟧)] (q₁ : Quotient s₁) (q₂ : Quotient s₂) (f : ∀ a₁ a₂, φ (Quotient.mk'' a₁) (Quotient.mk'' a₂)) : φ q₁ q₂ := Quotient.recOnSubsingleton₂ q₁ q₂ f /-- Recursion on a `Quotient` argument `a`, result type depends on `⟦a⟧`. -/ protected def hrecOn' {φ : Quotient s₁ → Sort*} (qa : Quotient s₁) (f : ∀ a, φ (Quotient.mk'' a)) (c : ∀ a₁ a₂, a₁ ≈ a₂ → HEq (f a₁) (f a₂)) : φ qa := Quot.hrecOn qa f c @[simp] theorem hrecOn'_mk'' {φ : Quotient s₁ → Sort*} (f : ∀ a, φ (Quotient.mk'' a)) (c : ∀ a₁ a₂, a₁ ≈ a₂ → HEq (f a₁) (f a₂)) (x : α) : (Quotient.mk'' x).hrecOn' f c = f x := rfl /-- Recursion on two `Quotient` arguments `a` and `b`, result type depends on `⟦a⟧` and `⟦b⟧`. -/ protected def hrecOn₂' {φ : Quotient s₁ → Quotient s₂ → Sort*} (qa : Quotient s₁) (qb : Quotient s₂) (f : ∀ a b, φ (Quotient.mk'' a) (Quotient.mk'' b)) (c : ∀ a₁ b₁ a₂ b₂, a₁ ≈ a₂ → b₁ ≈ b₂ → HEq (f a₁ b₁) (f a₂ b₂)) : φ qa qb := Quotient.hrecOn₂ qa qb f c @[simp] theorem hrecOn₂'_mk'' {φ : Quotient s₁ → Quotient s₂ → Sort*} (f : ∀ a b, φ (Quotient.mk'' a) (Quotient.mk'' b)) (c : ∀ a₁ b₁ a₂ b₂, a₁ ≈ a₂ → b₁ ≈ b₂ → HEq (f a₁ b₁) (f a₂ b₂)) (x : α) (qb : Quotient s₂) : (Quotient.mk'' x).hrecOn₂' qb f c = qb.hrecOn' (f x) fun _ _ ↦ c _ _ _ _ (Setoid.refl _) := rfl /-- Map a function `f : α → β` that sends equivalent elements to equivalent elements to a function `Quotient sa → Quotient sb`. Useful to define unary operations on quotients. -/ protected def map' (f : α → β) (h : (s₁.r ⇒ s₂.r) f f) : Quotient s₁ → Quotient s₂ := Quot.map f h @[simp] theorem map'_mk'' (f : α → β) (h) (x : α) : (Quotient.mk'' x : Quotient s₁).map' f h = (Quotient.mk'' (f x) : Quotient s₂) := rfl /-- A version of `Quotient.map₂` using curly braces and unification. -/ protected def map₂' (f : α → β → γ) (h : (s₁.r ⇒ s₂.r ⇒ s₃.r) f f) : Quotient s₁ → Quotient s₂ → Quotient s₃ := Quotient.map₂ f h @[simp] theorem map₂'_mk'' (f : α → β → γ) (h) (x : α) : (Quotient.mk'' x : Quotient s₁).map₂' f h = (Quotient.map' (f x) (h (Setoid.refl x)) : Quotient s₂ → Quotient s₃) := rfl theorem exact' {a b : α} : (Quotient.mk'' a : Quotient s₁) = Quotient.mk'' b → @Setoid.r _ s₁ a b := Quotient.exact theorem sound' {a b : α} : @Setoid.r _ s₁ a b → @Quotient.mk'' α s₁ a = Quotient.mk'' b := Quotient.sound @[simp] protected theorem eq' [s₁ : Setoid α] {a b : α} : @Quotient.mk' α s₁ a = @Quotient.mk' α s₁ b ↔ @Setoid.r _ s₁ a b := Quotient.eq @[simp] protected theorem eq'' {a b : α} : @Quotient.mk'' α s₁ a = Quotient.mk'' b ↔ @Setoid.r _ s₁ a b := Quotient.eq /-- A version of `Quotient.out` taking `{s₁ : Setoid α}` as an implicit argument instead of an instance argument. -/ noncomputable def out' (a : Quotient s₁) : α := Quotient.out a @[simp] theorem out_eq' (q : Quotient s₁) : Quotient.mk'' q.out' = q := q.out_eq theorem mk_out' (a : α) : @Setoid.r α s₁ (Quotient.mk'' a : Quotient s₁).out' a := Quotient.exact (Quotient.out_eq _) section variable [s : Setoid α] protected theorem mk''_eq_mk : Quotient.mk'' = Quotient.mk s := rfl @[simp] protected theorem liftOn'_mk (x : α) (f : α → β) (h) : (Quotient.mk s x).liftOn' f h = f x := rfl @[simp] protected theorem liftOn₂'_mk [t : Setoid β] (f : α → β → γ) (h) (a : α) (b : β) : Quotient.liftOn₂' (Quotient.mk s a) (Quotient.mk t b) f h = f a b := Quotient.liftOn₂'_mk'' _ _ _ _ @[simp] theorem map'_mk [t : Setoid β] (f : α → β) (h) (x : α) : (Quotient.mk s x).map' f h = (Quotient.mk t (f x)) := rfl end instance (q : Quotient s₁) (f : α → Prop) (h : ∀ a b, @Setoid.r α s₁ a b → f a = f b) [DecidablePred f] : Decidable (Quotient.liftOn' q f h) := Quotient.lift.decidablePred _ _ q instance (q₁ : Quotient s₁) (q₂ : Quotient s₂) (f : α → β → Prop) (h : ∀ a₁ b₁ a₂ b₂, @Setoid.r α s₁ a₁ a₂ → @Setoid.r β s₂ b₁ b₂ → f a₁ b₁ = f a₂ b₂) [∀ a, DecidablePred (f a)] : Decidable (Quotient.liftOn₂' q₁ q₂ f h) := Quotient.lift₂.decidablePred _ h _ _ end Quotient @[simp] lemma Equivalence.quot_mk_eq_iff {α : Type*} {r : α → α → Prop} (h : Equivalence r) (x y : α) : Quot.mk r x = Quot.mk r y ↔ r x y := by constructor · rw [Quot.eq] intro hxy induction hxy with | rel _ _ H => exact H | refl _ => exact h.refl _ | symm _ _ _ H => exact h.symm H | trans _ _ _ _ _ h₁₂ h₂₃ => exact h.trans h₁₂ h₂₃ · exact Quot.sound
Data\Rel.lean
/- Copyright (c) 2018 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad -/ import Mathlib.Order.CompleteLattice import Mathlib.Order.GaloisConnection import Mathlib.Data.Set.Lattice import Mathlib.Tactic.AdaptationNote /-! # Relations This file defines bundled relations. A relation between `α` and `β` is a function `α → β → Prop`. Relations are also known as set-valued functions, or partial multifunctions. ## Main declarations * `Rel α β`: Relation between `α` and `β`. * `Rel.inv`: `r.inv` is the `Rel β α` obtained by swapping the arguments of `r`. * `Rel.dom`: Domain of a relation. `x ∈ r.dom` iff there exists `y` such that `r x y`. * `Rel.codom`: Codomain, aka range, of a relation. `y ∈ r.codom` iff there exists `x` such that `r x y`. * `Rel.comp`: Relation composition. Note that the arguments order follows the `CategoryTheory/` one, so `r.comp s x z ↔ ∃ y, r x y ∧ s y z`. * `Rel.image`: Image of a set under a relation. `r.image s` is the set of `f x` over all `x ∈ s`. * `Rel.preimage`: Preimage of a set under a relation. Note that `r.preimage = r.inv.image`. * `Rel.core`: Core of a set. For `s : Set β`, `r.core s` is the set of `x : α` such that all `y` related to `x` are in `s`. * `Rel.restrict_domain`: Domain-restriction of a relation to a subtype. * `Function.graph`: Graph of a function as a relation. ## TODO The `Rel.comp` function uses the notation `r • s`, rather than the more common `r ∘ s` for things named `comp`. This is because the latter is already used for function composition, and causes a clash. A better notation should be found, perhaps a variant of `r ∘r s` or `r; s`. -/ variable {α β γ : Type*} /-- A relation on `α` and `β`, aka a set-valued function, aka a partial multifunction -/ def Rel (α β : Type*) := α → β → Prop -- deriving CompleteLattice, Inhabited -- Porting note: `deriving` above doesn't work. instance : CompleteLattice (Rel α β) := show CompleteLattice (α → β → Prop) from inferInstance instance : Inhabited (Rel α β) := show Inhabited (α → β → Prop) from inferInstance namespace Rel variable (r : Rel α β) -- Porting note: required for later theorems. @[ext] theorem ext {r s : Rel α β} : (∀ a, r a = s a) → r = s := funext /-- The inverse relation : `r.inv x y ↔ r y x`. Note that this is *not* a groupoid inverse. -/ def inv : Rel β α := flip r theorem inv_def (x : α) (y : β) : r.inv y x ↔ r x y := Iff.rfl theorem inv_inv : inv (inv r) = r := by ext x y rfl /-- Domain of a relation -/ def dom := { x | ∃ y, r x y } theorem dom_mono {r s : Rel α β} (h : r ≤ s) : dom r ⊆ dom s := fun a ⟨b, hx⟩ => ⟨b, h a b hx⟩ /-- Codomain aka range of a relation -/ def codom := { y | ∃ x, r x y } theorem codom_inv : r.inv.codom = r.dom := by ext x rfl theorem dom_inv : r.inv.dom = r.codom := by ext x rfl /-- Composition of relation; note that it follows the `CategoryTheory/` order of arguments. -/ def comp (r : Rel α β) (s : Rel β γ) : Rel α γ := fun x z => ∃ y, r x y ∧ s y z -- Porting note: the original `∘` syntax can't be overloaded here, lean considers it ambiguous. /-- Local syntax for composition of relations. -/ local infixr:90 " • " => Rel.comp theorem comp_assoc {δ : Type*} (r : Rel α β) (s : Rel β γ) (t : Rel γ δ) : (r • s) • t = r • (s • t) := by unfold comp; ext (x w); constructor · rintro ⟨z, ⟨y, rxy, syz⟩, tzw⟩; exact ⟨y, rxy, z, syz, tzw⟩ · rintro ⟨y, rxy, z, syz, tzw⟩; exact ⟨z, ⟨y, rxy, syz⟩, tzw⟩ @[simp] theorem comp_right_id (r : Rel α β) : r • @Eq β = r := by unfold comp ext y simp @[simp] theorem comp_left_id (r : Rel α β) : @Eq α • r = r := by unfold comp ext x simp @[simp] theorem comp_right_bot (r : Rel α β) : r • (⊥ : Rel β γ) = ⊥ := by ext x y simp [comp, Bot.bot] @[simp] theorem comp_left_bot (r : Rel α β) : (⊥ : Rel γ α) • r = ⊥ := by ext x y simp [comp, Bot.bot] @[simp] theorem comp_right_top (r : Rel α β) : r • (⊤ : Rel β γ) = fun x _ ↦ x ∈ r.dom := by ext x z simp [comp, Top.top, dom] @[simp] theorem comp_left_top (r : Rel α β) : (⊤ : Rel γ α) • r = fun _ y ↦ y ∈ r.codom := by ext x z simp [comp, Top.top, codom] theorem inv_id : inv (@Eq α) = @Eq α := by ext x y constructor <;> apply Eq.symm theorem inv_comp (r : Rel α β) (s : Rel β γ) : inv (r • s) = inv s • inv r := by ext x z simp [comp, inv, flip, and_comm] @[simp] theorem inv_bot : (⊥ : Rel α β).inv = (⊥ : Rel β α) := by #adaptation_note /-- nightly-2024-03-16: simp was `simp [Bot.bot, inv, flip]` -/ simp [Bot.bot, inv, Function.flip_def] @[simp] theorem inv_top : (⊤ : Rel α β).inv = (⊤ : Rel β α) := by #adaptation_note /-- nightly-2024-03-16: simp was `simp [Top.top, inv, flip]` -/ simp [Top.top, inv, Function.flip_def] /-- Image of a set under a relation -/ def image (s : Set α) : Set β := { y | ∃ x ∈ s, r x y } theorem mem_image (y : β) (s : Set α) : y ∈ image r s ↔ ∃ x ∈ s, r x y := Iff.rfl theorem image_subset : ((· ⊆ ·) ⇒ (· ⊆ ·)) r.image r.image := fun _ _ h _ ⟨x, xs, rxy⟩ => ⟨x, h xs, rxy⟩ theorem image_mono : Monotone r.image := r.image_subset theorem image_inter (s t : Set α) : r.image (s ∩ t) ⊆ r.image s ∩ r.image t := r.image_mono.map_inf_le s t theorem image_union (s t : Set α) : r.image (s ∪ t) = r.image s ∪ r.image t := le_antisymm (fun _y ⟨x, xst, rxy⟩ => xst.elim (fun xs => Or.inl ⟨x, ⟨xs, rxy⟩⟩) fun xt => Or.inr ⟨x, ⟨xt, rxy⟩⟩) (r.image_mono.le_map_sup s t) @[simp] theorem image_id (s : Set α) : image (@Eq α) s = s := by ext x simp [mem_image] theorem image_comp (s : Rel β γ) (t : Set α) : image (r • s) t = image s (image r t) := by ext z; simp only [mem_image]; constructor · rintro ⟨x, xt, y, rxy, syz⟩; exact ⟨y, ⟨x, xt, rxy⟩, syz⟩ · rintro ⟨y, ⟨x, xt, rxy⟩, syz⟩; exact ⟨x, xt, y, rxy, syz⟩ theorem image_univ : r.image Set.univ = r.codom := by ext y simp [mem_image, codom] @[simp] theorem image_empty : r.image ∅ = ∅ := by ext x simp [mem_image] @[simp] theorem image_bot (s : Set α) : (⊥ : Rel α β).image s = ∅ := by rw [Set.eq_empty_iff_forall_not_mem] intro x h simp [mem_image, Bot.bot] at h @[simp] theorem image_top {s : Set α} (h : Set.Nonempty s) : (⊤ : Rel α β).image s = Set.univ := Set.eq_univ_of_forall fun x ↦ ⟨h.some, by simp [h.some_mem, Top.top]⟩ /-- Preimage of a set under a relation `r`. Same as the image of `s` under `r.inv` -/ def preimage (s : Set β) : Set α := r.inv.image s theorem mem_preimage (x : α) (s : Set β) : x ∈ r.preimage s ↔ ∃ y ∈ s, r x y := Iff.rfl theorem preimage_def (s : Set β) : preimage r s = { x | ∃ y ∈ s, r x y } := Set.ext fun _ => mem_preimage _ _ _ theorem preimage_mono {s t : Set β} (h : s ⊆ t) : r.preimage s ⊆ r.preimage t := image_mono _ h theorem preimage_inter (s t : Set β) : r.preimage (s ∩ t) ⊆ r.preimage s ∩ r.preimage t := image_inter _ s t theorem preimage_union (s t : Set β) : r.preimage (s ∪ t) = r.preimage s ∪ r.preimage t := image_union _ s t theorem preimage_id (s : Set α) : preimage (@Eq α) s = s := by simp only [preimage, inv_id, image_id] theorem preimage_comp (s : Rel β γ) (t : Set γ) : preimage (r • s) t = preimage r (preimage s t) := by simp only [preimage, inv_comp, image_comp] theorem preimage_univ : r.preimage Set.univ = r.dom := by rw [preimage, image_univ, codom_inv] @[simp] theorem preimage_empty : r.preimage ∅ = ∅ := by rw [preimage, image_empty] @[simp] theorem preimage_inv (s : Set α) : r.inv.preimage s = r.image s := by rw [preimage, inv_inv] @[simp] theorem preimage_bot (s : Set β) : (⊥ : Rel α β).preimage s = ∅ := by rw [preimage, inv_bot, image_bot] @[simp] theorem preimage_top {s : Set β} (h : Set.Nonempty s) : (⊤ : Rel α β).preimage s = Set.univ := by rwa [← inv_top, preimage, inv_inv, image_top] theorem image_eq_dom_of_codomain_subset {s : Set β} (h : r.codom ⊆ s) : r.preimage s = r.dom := by rw [← preimage_univ] apply Set.eq_of_subset_of_subset · exact image_subset _ (Set.subset_univ _) · intro x hx simp only [mem_preimage, Set.mem_univ, true_and] at hx rcases hx with ⟨y, ryx⟩ have hy : y ∈ s := h ⟨x, ryx⟩ exact ⟨y, ⟨hy, ryx⟩⟩ theorem preimage_eq_codom_of_domain_subset {s : Set α} (h : r.dom ⊆ s) : r.image s = r.codom := by apply r.inv.image_eq_dom_of_codomain_subset (by rwa [← codom_inv] at h) theorem image_inter_dom_eq (s : Set α) : r.image (s ∩ r.dom) = r.image s := by apply Set.eq_of_subset_of_subset · apply r.image_mono (by simp) · intro x h rw [mem_image] at * rcases h with ⟨y, hy, ryx⟩ use y suffices h : y ∈ r.dom by simp_all only [Set.mem_inter_iff, and_self] rw [dom, Set.mem_setOf_eq] use x @[simp] theorem preimage_inter_codom_eq (s : Set β) : r.preimage (s ∩ r.codom) = r.preimage s := by rw [← dom_inv, preimage, preimage, image_inter_dom_eq] theorem inter_dom_subset_preimage_image (s : Set α) : s ∩ r.dom ⊆ r.preimage (r.image s) := by intro x hx simp only [Set.mem_inter_iff, dom] at hx rcases hx with ⟨hx, ⟨y, rxy⟩⟩ use y simp only [image, Set.mem_setOf_eq] exact ⟨⟨x, hx, rxy⟩, rxy⟩ theorem image_preimage_subset_inter_codom (s : Set β) : s ∩ r.codom ⊆ r.image (r.preimage s) := by rw [← dom_inv, ← preimage_inv] apply inter_dom_subset_preimage_image /-- Core of a set `s : Set β` w.r.t `r : Rel α β` is the set of `x : α` that are related *only* to elements of `s`. Other generalization of `Function.preimage`. -/ def core (s : Set β) := { x | ∀ y, r x y → y ∈ s } theorem mem_core (x : α) (s : Set β) : x ∈ r.core s ↔ ∀ y, r x y → y ∈ s := Iff.rfl theorem core_subset : ((· ⊆ ·) ⇒ (· ⊆ ·)) r.core r.core := fun _s _t h _x h' y rxy => h (h' y rxy) theorem core_mono : Monotone r.core := r.core_subset theorem core_inter (s t : Set β) : r.core (s ∩ t) = r.core s ∩ r.core t := Set.ext (by simp [mem_core, imp_and, forall_and]) theorem core_union (s t : Set β) : r.core s ∪ r.core t ⊆ r.core (s ∪ t) := r.core_mono.le_map_sup s t @[simp] theorem core_univ : r.core Set.univ = Set.univ := Set.ext (by simp [mem_core]) theorem core_id (s : Set α) : core (@Eq α) s = s := by simp [core] theorem core_comp (s : Rel β γ) (t : Set γ) : core (r • s) t = core r (core s t) := by ext x; simp only [core, comp, forall_exists_index, and_imp, Set.mem_setOf_eq]; constructor · exact fun h y rxy z => h z y rxy · exact fun h z y rzy => h y rzy z /-- Restrict the domain of a relation to a subtype. -/ def restrictDomain (s : Set α) : Rel { x // x ∈ s } β := fun x y => r x.val y theorem image_subset_iff (s : Set α) (t : Set β) : image r s ⊆ t ↔ s ⊆ core r t := Iff.intro (fun h x xs _y rxy => h ⟨x, xs, rxy⟩) fun h y ⟨_x, xs, rxy⟩ => h xs y rxy theorem image_core_gc : GaloisConnection r.image r.core := image_subset_iff _ end Rel namespace Function /-- The graph of a function as a relation. -/ def graph (f : α → β) : Rel α β := fun x y => f x = y @[simp] lemma graph_def (f : α → β) (x y) : f.graph x y ↔ (f x = y) := Iff.rfl theorem graph_injective : Injective (graph : (α → β) → Rel α β) := by intro _ g h ext x have h2 := congr_fun₂ h x (g x) simp only [graph_def, eq_iff_iff, iff_true] at h2 exact h2 @[simp] lemma graph_inj {f g : α → β} : f.graph = g.graph ↔ f = g := graph_injective.eq_iff theorem graph_id : graph id = @Eq α := by simp (config := { unfoldPartialApp := true }) [graph] theorem graph_comp {f : β → γ} {g : α → β} : graph (f ∘ g) = Rel.comp (graph g) (graph f) := by ext x y simp [Rel.comp] end Function theorem Equiv.graph_inv (f : α ≃ β) : (f.symm : β → α).graph = Rel.inv (f : α → β).graph := by ext x y aesop (add norm Rel.inv_def) theorem Relation.is_graph_iff (r : Rel α β) : (∃! f, Function.graph f = r) ↔ ∀ x, ∃! y, r x y := by unfold Function.graph constructor · rintro ⟨f, rfl, _⟩ x use f x simp only [forall_eq', and_self] · intro h choose f hf using fun x ↦ (h x).exists use f constructor · ext x _ constructor · rintro rfl exact hf x · exact (h x).unique (hf x) · rintro _ rfl exact funext hf namespace Set theorem image_eq (f : α → β) (s : Set α) : f '' s = (Function.graph f).image s := by rfl theorem preimage_eq (f : α → β) (s : Set β) : f ⁻¹' s = (Function.graph f).preimage s := by simp [Set.preimage, Rel.preimage, Rel.inv, flip, Rel.image] theorem preimage_eq_core (f : α → β) (s : Set β) : f ⁻¹' s = (Function.graph f).core s := by simp [Set.preimage, Rel.core] end Set
Data\Semiquot.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 Mathlib.Data.Set.Lattice /-! # Semiquotients A data type for semiquotients, which are classically equivalent to nonempty sets, but are useful for programming; the idea is that a semiquotient set `S` represents some (particular but unknown) element of `S`. This can be used to model nondeterministic functions, which return something in a range of values (represented by the predicate `S`) but are not completely determined. -/ /-- A member of `Semiquot α` is classically a nonempty `Set α`, and in the VM is represented by an element of `α`; the relation between these is that the VM element is required to be a member of the set `s`. The specific element of `s` that the VM computes is hidden by a quotient construction, allowing for the representation of nondeterministic functions. -/ -- Porting note: removed universe parameter structure Semiquot (α : Type*) where mk' :: /-- Set containing some element of `α`-/ s : Set α /-- Assertion of non-emptiness via `Trunc`-/ val : Trunc s namespace Semiquot variable {α : Type*} {β : Type*} instance : Membership α (Semiquot α) := ⟨fun a q => a ∈ q.s⟩ /-- Construct a `Semiquot α` from `h : a ∈ s` where `s : Set α`. -/ def mk {a : α} {s : Set α} (h : a ∈ s) : Semiquot α := ⟨s, Trunc.mk ⟨a, h⟩⟩ theorem ext_s {q₁ q₂ : Semiquot α} : q₁ = q₂ ↔ q₁.s = q₂.s := by refine ⟨congr_arg _, fun h => ?_⟩ cases' q₁ with _ v₁; cases' q₂ with _ v₂; congr exact Subsingleton.helim (congrArg Trunc (congrArg Set.Elem h)) v₁ v₂ theorem ext {q₁ q₂ : Semiquot α} : q₁ = q₂ ↔ ∀ a, a ∈ q₁ ↔ a ∈ q₂ := ext_s.trans Set.ext_iff theorem exists_mem (q : Semiquot α) : ∃ a, a ∈ q := let ⟨⟨a, h⟩, _⟩ := q.2.exists_rep ⟨a, h⟩ theorem eq_mk_of_mem {q : Semiquot α} {a : α} (h : a ∈ q) : q = @mk _ a q.1 h := ext_s.2 rfl theorem nonempty (q : Semiquot α) : q.s.Nonempty := q.exists_mem /-- `pure a` is `a` reinterpreted as an unspecified element of `{a}`. -/ protected def pure (a : α) : Semiquot α := mk (Set.mem_singleton a) @[simp] theorem mem_pure' {a b : α} : a ∈ Semiquot.pure b ↔ a = b := Set.mem_singleton_iff /-- Replace `s` in a `Semiquot` with a superset. -/ def blur' (q : Semiquot α) {s : Set α} (h : q.s ⊆ s) : Semiquot α := ⟨s, Trunc.lift (fun a : q.s => Trunc.mk ⟨a.1, h a.2⟩) (fun _ _ => Trunc.eq _ _) q.2⟩ /-- Replace `s` in a `q : Semiquot α` with a union `s ∪ q.s` -/ def blur (s : Set α) (q : Semiquot α) : Semiquot α := blur' q (s.subset_union_right (t := q.s)) theorem blur_eq_blur' (q : Semiquot α) (s : Set α) (h : q.s ⊆ s) : blur s q = blur' q h := by unfold blur; congr; exact Set.union_eq_self_of_subset_right h @[simp] theorem mem_blur' (q : Semiquot α) {s : Set α} (h : q.s ⊆ s) {a : α} : a ∈ blur' q h ↔ a ∈ s := Iff.rfl /-- Convert a `Trunc α` to a `Semiquot α`. -/ def ofTrunc (q : Trunc α) : Semiquot α := ⟨Set.univ, q.map fun a => ⟨a, trivial⟩⟩ /-- Convert a `Semiquot α` to a `Trunc α`. -/ def toTrunc (q : Semiquot α) : Trunc α := q.2.map Subtype.val /-- If `f` is a constant on `q.s`, then `q.liftOn f` is the value of `f` at any point of `q`. -/ def liftOn (q : Semiquot α) (f : α → β) (h : ∀ a ∈ q, ∀ b ∈ q, f a = f b) : β := Trunc.liftOn q.2 (fun x => f x.1) fun x y => h _ x.2 _ y.2 theorem liftOn_ofMem (q : Semiquot α) (f : α → β) (h : ∀ a ∈ q, ∀ b ∈ q, f a = f b) (a : α) (aq : a ∈ q) : liftOn q f h = f a := by revert h; rw [eq_mk_of_mem aq]; intro; rfl /-- Apply a function to the unknown value stored in a `Semiquot α`. -/ def map (f : α → β) (q : Semiquot α) : Semiquot β := ⟨f '' q.1, q.2.map fun x => ⟨f x.1, Set.mem_image_of_mem _ x.2⟩⟩ @[simp] theorem mem_map (f : α → β) (q : Semiquot α) (b : β) : b ∈ map f q ↔ ∃ a, a ∈ q ∧ f a = b := Set.mem_image _ _ _ /-- Apply a function returning a `Semiquot` to a `Semiquot`. -/ def bind (q : Semiquot α) (f : α → Semiquot β) : Semiquot β := ⟨⋃ a ∈ q.1, (f a).1, q.2.bind fun a => (f a.1).2.map fun b => ⟨b.1, Set.mem_biUnion a.2 b.2⟩⟩ @[simp] theorem mem_bind (q : Semiquot α) (f : α → Semiquot β) (b : β) : b ∈ bind q f ↔ ∃ a ∈ q, b ∈ f a := by simp_rw [← exists_prop]; exact Set.mem_iUnion₂ instance : Monad Semiquot where pure := @Semiquot.pure map := @Semiquot.map bind := @Semiquot.bind @[simp] theorem map_def {β} : ((· <$> ·) : (α → β) → Semiquot α → Semiquot β) = map := rfl @[simp] theorem bind_def {β} : ((· >>= ·) : Semiquot α → (α → Semiquot β) → Semiquot β) = bind := rfl @[simp] theorem mem_pure {a b : α} : a ∈ (pure b : Semiquot α) ↔ a = b := Set.mem_singleton_iff theorem mem_pure_self (a : α) : a ∈ (pure a : Semiquot α) := Set.mem_singleton a @[simp] theorem pure_inj {a b : α} : (pure a : Semiquot α) = pure b ↔ a = b := ext_s.trans Set.singleton_eq_singleton_iff instance : LawfulMonad Semiquot := LawfulMonad.mk' (pure_bind := fun {α β} x f => ext.2 <| by simp) (bind_assoc := fun {α β} γ s f g => ext.2 <| by simp only [bind_def, mem_bind] exact fun c => ⟨fun ⟨b, ⟨a, as, bf⟩, cg⟩ => ⟨a, as, b, bf, cg⟩, fun ⟨a, as, b, bf, cg⟩ => ⟨b, ⟨a, as, bf⟩, cg⟩⟩) (id_map := fun {α} q => ext.2 <| by simp) (bind_pure_comp := fun {α β} f s => ext.2 <| by simp [eq_comm]) instance : LE (Semiquot α) := ⟨fun s t => s.s ⊆ t.s⟩ instance partialOrder : PartialOrder (Semiquot α) where le s t := ∀ ⦃x⦄, x ∈ s → x ∈ t le_refl s := Set.Subset.refl _ le_trans s t u := Set.Subset.trans le_antisymm s t h₁ h₂ := ext_s.2 (Set.Subset.antisymm h₁ h₂) instance : SemilatticeSup (Semiquot α) := { Semiquot.partialOrder with sup := fun s => blur s.s le_sup_left := fun _ _ => Set.subset_union_left le_sup_right := fun _ _ => Set.subset_union_right sup_le := fun _ _ _ => Set.union_subset } @[simp] theorem pure_le {a : α} {s : Semiquot α} : pure a ≤ s ↔ a ∈ s := Set.singleton_subset_iff /-- Assert that a `Semiquot` contains only one possible value. -/ def IsPure (q : Semiquot α) : Prop := ∀ a ∈ q, ∀ b ∈ q, a = b /-- Extract the value from an `IsPure` semiquotient. -/ def get (q : Semiquot α) (h : q.IsPure) : α := liftOn q id h theorem get_mem {q : Semiquot α} (p) : get q p ∈ q := by let ⟨a, h⟩ := exists_mem q unfold get; rw [liftOn_ofMem q _ _ a h]; exact h theorem eq_pure {q : Semiquot α} (p) : q = pure (get q p) := ext.2 fun a => by simpa using ⟨fun h => p _ h _ (get_mem _), fun e => e.symm ▸ get_mem _⟩ @[simp] theorem pure_isPure (a : α) : IsPure (pure a) | b, ab, c, ac => by rw [mem_pure] at ab ac rwa [← ac] at ab theorem isPure_iff {s : Semiquot α} : IsPure s ↔ ∃ a, s = pure a := ⟨fun h => ⟨_, eq_pure h⟩, fun ⟨_, e⟩ => e.symm ▸ pure_isPure _⟩ theorem IsPure.mono {s t : Semiquot α} (st : s ≤ t) (h : IsPure t) : IsPure s | _, as, _, bs => h _ (st as) _ (st bs) theorem IsPure.min {s t : Semiquot α} (h : IsPure t) : s ≤ t ↔ s = t := ⟨fun st => le_antisymm st <| by rw [eq_pure h, eq_pure (h.mono st)]; simpa using h _ (get_mem _) _ (st <| get_mem _), le_of_eq⟩ theorem isPure_of_subsingleton [Subsingleton α] (q : Semiquot α) : IsPure q | _, _, _, _ => Subsingleton.elim _ _ /-- `univ : Semiquot α` represents an unspecified element of `univ : Set α`. -/ def univ [Inhabited α] : Semiquot α := mk <| Set.mem_univ default instance [Inhabited α] : Inhabited (Semiquot α) := ⟨univ⟩ @[simp] theorem mem_univ [Inhabited α] : ∀ a, a ∈ @univ α _ := @Set.mem_univ α @[congr] theorem univ_unique (I J : Inhabited α) : @univ _ I = @univ _ J := ext.2 fun a => refl (a ∈ univ) @[simp] theorem isPure_univ [Inhabited α] : @IsPure α univ ↔ Subsingleton α := ⟨fun h => ⟨fun a b => h a trivial b trivial⟩, fun ⟨h⟩ a _ b _ => h a b⟩ instance [Inhabited α] : OrderTop (Semiquot α) where top := univ le_top _ := Set.subset_univ _ end Semiquot
Data\Sign.lean
/- Copyright (c) 2022 Eric Rodriguez. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Rodriguez -/ import Mathlib.Algebra.GroupWithZero.Units.Lemmas import Mathlib.Algebra.Order.BigOperators.Group.Finset import Mathlib.Data.Fintype.BigOperators /-! # Sign function This file defines the sign function for types with zero and a decidable less-than relation, and proves some basic theorems about it. -/ -- Porting note (#11081): cannot automatically derive Fintype, added manually /-- The type of signs. -/ inductive SignType | zero | neg | pos deriving DecidableEq, Inhabited -- Porting note: these lemmas are autogenerated by the inductive definition and are not -- in simple form due to the below `x_eq_x` lemmas attribute [nolint simpNF] SignType.zero.sizeOf_spec attribute [nolint simpNF] SignType.neg.sizeOf_spec attribute [nolint simpNF] SignType.pos.sizeOf_spec namespace SignType -- Porting note: Added Fintype SignType manually instance : Fintype SignType := Fintype.ofMultiset (zero :: neg :: pos :: List.nil) (fun x ↦ by cases x <;> simp) instance : Zero SignType := ⟨zero⟩ instance : One SignType := ⟨pos⟩ instance : Neg SignType := ⟨fun s => match s with | neg => pos | zero => zero | pos => neg⟩ @[simp] theorem zero_eq_zero : zero = 0 := rfl @[simp] theorem neg_eq_neg_one : neg = -1 := rfl @[simp] theorem pos_eq_one : pos = 1 := rfl instance : Mul SignType := ⟨fun x y => match x with | neg => -y | zero => zero | pos => y⟩ /-- The less-than-or-equal relation on signs. -/ protected inductive LE : SignType → SignType → Prop | of_neg (a) : SignType.LE neg a | zero : SignType.LE zero zero | of_pos (a) : SignType.LE a pos instance : LE SignType := ⟨SignType.LE⟩ instance LE.decidableRel : DecidableRel SignType.LE := fun a b => by cases a <;> cases b <;> first | exact isTrue (by constructor)| exact isFalse (by rintro ⟨_⟩) instance decidableEq : DecidableEq SignType := fun a b => by cases a <;> cases b <;> first | exact isTrue (by constructor)| exact isFalse (by rintro ⟨_⟩) private lemma mul_comm : ∀ (a b : SignType), a * b = b * a := by rintro ⟨⟩ ⟨⟩ <;> rfl private lemma mul_assoc : ∀ (a b c : SignType), (a * b) * c = a * (b * c) := by rintro ⟨⟩ ⟨⟩ ⟨⟩ <;> rfl /- We can define a `Field` instance on `SignType`, but it's not mathematically sensible, so we only define the `CommGroupWithZero`. -/ instance : CommGroupWithZero SignType where zero := 0 one := 1 mul := (· * ·) inv := id mul_zero a := by cases a <;> rfl zero_mul a := by cases a <;> rfl mul_one a := by cases a <;> rfl one_mul a := by cases a <;> rfl mul_inv_cancel a ha := by cases a <;> trivial mul_comm := mul_comm mul_assoc := mul_assoc exists_pair_ne := ⟨0, 1, by rintro ⟨_⟩⟩ inv_zero := rfl private lemma le_antisymm (a b : SignType) (_ : a ≤ b) (_ : b ≤ a) : a = b := by cases a <;> cases b <;> trivial private lemma le_trans (a b c : SignType) (_ : a ≤ b) (_ : b ≤ c) : a ≤ c := by cases a <;> cases b <;> cases c <;> tauto instance : LinearOrder SignType where le := (· ≤ ·) le_refl a := by cases a <;> constructor le_total a b := by cases a <;> cases b <;> first | left; constructor | right; constructor le_antisymm := le_antisymm le_trans := le_trans decidableLE := LE.decidableRel decidableEq := SignType.decidableEq instance : BoundedOrder SignType where top := 1 le_top := LE.of_pos bot := -1 bot_le := LE.of_neg instance : HasDistribNeg SignType := { neg_neg := fun x => by cases x <;> rfl neg_mul := fun x y => by cases x <;> cases y <;> rfl mul_neg := fun x y => by cases x <;> cases y <;> rfl } /-- `SignType` is equivalent to `Fin 3`. -/ def fin3Equiv : SignType ≃* Fin 3 where toFun a := match a with | 0 => ⟨0, by simp⟩ | 1 => ⟨1, by simp⟩ | -1 => ⟨2, by simp⟩ invFun a := match a with | ⟨0, _⟩ => 0 | ⟨1, _⟩ => 1 | ⟨2, _⟩ => -1 left_inv a := by cases a <;> rfl right_inv a := match a with | ⟨0, _⟩ => by simp | ⟨1, _⟩ => by simp | ⟨2, _⟩ => by simp map_mul' a b := by cases a <;> cases b <;> rfl section CaseBashing -- Porting note: a lot of these thms used to use decide! which is not implemented yet theorem nonneg_iff {a : SignType} : 0 ≤ a ↔ a = 0 ∨ a = 1 := by cases a <;> decide theorem nonneg_iff_ne_neg_one {a : SignType} : 0 ≤ a ↔ a ≠ -1 := by cases a <;> decide theorem neg_one_lt_iff {a : SignType} : -1 < a ↔ 0 ≤ a := by cases a <;> decide theorem nonpos_iff {a : SignType} : a ≤ 0 ↔ a = -1 ∨ a = 0 := by cases a <;> decide theorem nonpos_iff_ne_one {a : SignType} : a ≤ 0 ↔ a ≠ 1 := by cases a <;> decide theorem lt_one_iff {a : SignType} : a < 1 ↔ a ≤ 0 := by cases a <;> decide @[simp] theorem neg_iff {a : SignType} : a < 0 ↔ a = -1 := by cases a <;> decide @[simp] theorem le_neg_one_iff {a : SignType} : a ≤ -1 ↔ a = -1 := le_bot_iff @[simp] theorem pos_iff {a : SignType} : 0 < a ↔ a = 1 := by cases a <;> decide @[simp] theorem one_le_iff {a : SignType} : 1 ≤ a ↔ a = 1 := top_le_iff @[simp] theorem neg_one_le (a : SignType) : -1 ≤ a := bot_le @[simp] theorem le_one (a : SignType) : a ≤ 1 := le_top @[simp] theorem not_lt_neg_one (a : SignType) : ¬a < -1 := not_lt_bot @[simp] theorem not_one_lt (a : SignType) : ¬1 < a := not_top_lt @[simp] theorem self_eq_neg_iff (a : SignType) : a = -a ↔ a = 0 := by cases a <;> decide @[simp] theorem neg_eq_self_iff (a : SignType) : -a = a ↔ a = 0 := by cases a <;> decide @[simp] theorem neg_one_lt_one : (-1 : SignType) < 1 := bot_lt_top end CaseBashing section cast variable {α : Type*} [Zero α] [One α] [Neg α] /-- Turn a `SignType` into zero, one, or minus one. This is a coercion instance, but note it is only a `CoeTC` instance: see note [use has_coe_t]. -/ @[coe] def cast : SignType → α | zero => 0 | pos => 1 | neg => -1 -- Porting note: Translated has_coe_t to CoeTC instance : CoeTC SignType α := ⟨cast⟩ -- Porting note: `cast_eq_coe` removed, syntactic equality /-- Casting out of `SignType` respects composition with functions preserving `0, 1, -1`. -/ lemma map_cast' {β : Type*} [One β] [Neg β] [Zero β] (f : α → β) (h₁ : f 1 = 1) (h₂ : f 0 = 0) (h₃ : f (-1) = -1) (s : SignType) : f s = s := by cases s <;> simp only [SignType.cast, h₁, h₂, h₃] /-- Casting out of `SignType` respects composition with suitable bundled homomorphism types. -/ lemma map_cast {α β F : Type*} [AddGroupWithOne α] [One β] [SubtractionMonoid β] [FunLike F α β] [AddMonoidHomClass F α β] [OneHomClass F α β] (f : F) (s : SignType) : f s = s := by apply map_cast' <;> simp @[simp] theorem coe_zero : ↑(0 : SignType) = (0 : α) := rfl @[simp] theorem coe_one : ↑(1 : SignType) = (1 : α) := rfl @[simp] theorem coe_neg_one : ↑(-1 : SignType) = (-1 : α) := rfl @[simp, norm_cast] lemma coe_neg {α : Type*} [One α] [SubtractionMonoid α] (s : SignType) : (↑(-s) : α) = -↑s := by cases s <;> simp /-- Casting `SignType → ℤ → α` is the same as casting directly `SignType → α`. -/ @[simp, norm_cast] lemma intCast_cast {α : Type*} [AddGroupWithOne α] (s : SignType) : ((s : ℤ) : α) = s := map_cast' _ Int.cast_one Int.cast_zero (@Int.cast_one α _ ▸ Int.cast_neg 1) _ end cast /-- `SignType.cast` as a `MulWithZeroHom`. -/ @[simps] def castHom {α} [MulZeroOneClass α] [HasDistribNeg α] : SignType →*₀ α where toFun := cast map_zero' := rfl map_one' := rfl map_mul' x y := by cases x <;> cases y <;> simp [zero_eq_zero, pos_eq_one, neg_eq_neg_one] theorem univ_eq : (Finset.univ : Finset SignType) = {0, -1, 1} := by decide theorem range_eq {α} (f : SignType → α) : Set.range f = {f zero, f neg, f pos} := by classical rw [← Fintype.coe_image_univ, univ_eq] classical simp [Finset.coe_insert] @[simp, norm_cast] lemma coe_mul {α} [MulZeroOneClass α] [HasDistribNeg α] (a b : SignType) : ↑(a * b) = (a : α) * b := map_mul SignType.castHom _ _ @[simp, norm_cast] lemma coe_pow {α} [MonoidWithZero α] [HasDistribNeg α] (a : SignType) (k : ℕ) : ↑(a ^ k) = (a : α) ^ k := map_pow SignType.castHom _ _ @[simp, norm_cast] lemma coe_zpow {α} [GroupWithZero α] [HasDistribNeg α] (a : SignType) (k : ℤ) : ↑(a ^ k) = (a : α) ^ k := map_zpow₀ SignType.castHom _ _ end SignType variable {α : Type*} open SignType section Preorder variable [Zero α] [Preorder α] [DecidableRel ((· < ·) : α → α → Prop)] {a : α} -- Porting note: needed to rename this from sign to SignType.sign to avoid ambiguity with Int.sign /-- The sign of an element is 1 if it's positive, -1 if negative, 0 otherwise. -/ def SignType.sign : α →o SignType := ⟨fun a => if 0 < a then 1 else if a < 0 then -1 else 0, fun a b h => by dsimp split_ifs with h₁ h₂ h₃ h₄ _ _ h₂ h₃ <;> try constructor · cases lt_irrefl 0 (h₁.trans <| h.trans_lt h₃) · cases h₂ (h₁.trans_le h) · cases h₄ (h.trans_lt h₃)⟩ theorem sign_apply : sign a = ite (0 < a) 1 (ite (a < 0) (-1) 0) := rfl @[simp] theorem sign_zero : sign (0 : α) = 0 := by simp [sign_apply] @[simp] theorem sign_pos (ha : 0 < a) : sign a = 1 := by rwa [sign_apply, if_pos] @[simp] theorem sign_neg (ha : a < 0) : sign a = -1 := by rwa [sign_apply, if_neg <| asymm ha, if_pos] theorem sign_eq_one_iff : sign a = 1 ↔ 0 < a := by refine ⟨fun h => ?_, fun h => sign_pos h⟩ by_contra hn rw [sign_apply, if_neg hn] at h split_ifs at h theorem sign_eq_neg_one_iff : sign a = -1 ↔ a < 0 := by refine ⟨fun h => ?_, fun h => sign_neg h⟩ rw [sign_apply] at h split_ifs at h assumption end Preorder section LinearOrder variable [Zero α] [LinearOrder α] {a : α} /-- `SignType.sign` respects strictly monotone zero-preserving maps. -/ lemma StrictMono.sign_comp {β F : Type*} [Zero β] [Preorder β] [DecidableRel ((· < ·) : β → β → _)] [FunLike F α β] [ZeroHomClass F α β] {f : F} (hf : StrictMono f) (a : α) : sign (f a) = sign a := by simp only [sign_apply, ← map_zero f, hf.lt_iff_lt] @[simp] theorem sign_eq_zero_iff : sign a = 0 ↔ a = 0 := by refine ⟨fun h => ?_, fun h => h.symm ▸ sign_zero⟩ rw [sign_apply] at h split_ifs at h with h_1 h_2 cases' h exact (le_of_not_lt h_1).eq_of_not_lt h_2 theorem sign_ne_zero : sign a ≠ 0 ↔ a ≠ 0 := sign_eq_zero_iff.not @[simp] theorem sign_nonneg_iff : 0 ≤ sign a ↔ 0 ≤ a := by rcases lt_trichotomy 0 a with (h | h | h) · simp [h, h.le] · simp [← h] · simp [h, h.not_le] @[simp] theorem sign_nonpos_iff : sign a ≤ 0 ↔ a ≤ 0 := by rcases lt_trichotomy 0 a with (h | h | h) · simp [h, h.not_le] · simp [← h] · simp [h, h.le] end LinearOrder section OrderedSemiring variable [OrderedSemiring α] [DecidableRel ((· < ·) : α → α → Prop)] [Nontrivial α] -- @[simp] -- Porting note (#10618): simp can prove this theorem sign_one : sign (1 : α) = 1 := sign_pos zero_lt_one end OrderedSemiring section OrderedRing @[simp] lemma sign_intCast {α : Type*} [OrderedRing α] [Nontrivial α] [DecidableRel ((· < ·) : α → α → Prop)] (n : ℤ) : sign (n : α) = sign n := by simp only [sign_apply, Int.cast_pos, Int.cast_lt_zero] end OrderedRing section LinearOrderedRing variable [LinearOrderedRing α] {a b : α} theorem sign_mul (x y : α) : sign (x * y) = sign x * sign y := by rcases lt_trichotomy x 0 with (hx | hx | hx) <;> rcases lt_trichotomy y 0 with (hy | hy | hy) <;> simp [hx, hy, mul_pos_of_neg_of_neg, mul_neg_of_neg_of_pos, mul_neg_of_pos_of_neg] @[simp] theorem sign_mul_abs (x : α) : (sign x * |x| : α) = x := by rcases lt_trichotomy x 0 with hx | rfl | hx <;> simp [*, abs_of_pos, abs_of_neg] @[simp] theorem abs_mul_sign (x : α) : (|x| * sign x : α) = x := by rcases lt_trichotomy x 0 with hx | rfl | hx <;> simp [*, abs_of_pos, abs_of_neg] @[simp] theorem sign_mul_self (x : α) : sign x * x = |x| := by rcases lt_trichotomy x 0 with hx | rfl | hx <;> simp [*, abs_of_pos, abs_of_neg] @[simp] theorem self_mul_sign (x : α) : x * sign x = |x| := by rcases lt_trichotomy x 0 with hx | rfl | hx <;> simp [*, abs_of_pos, abs_of_neg] /-- `SignType.sign` as a `MonoidWithZeroHom` for a nontrivial ordered semiring. Note that linearity is required; consider ℂ with the order `z ≤ w` iff they have the same imaginary part and `z - w ≤ 0` in the reals; then `1 + I` and `1 - I` are incomparable to zero, and thus we have: `0 * 0 = SignType.sign (1 + I) * SignType.sign (1 - I) ≠ SignType.sign 2 = 1`. (`Complex.orderedCommRing`) -/ def signHom : α →*₀ SignType where toFun := sign map_zero' := sign_zero map_one' := sign_one map_mul' := sign_mul theorem sign_pow (x : α) (n : ℕ) : sign (x ^ n) = sign x ^ n := map_pow signHom x n end LinearOrderedRing section AddGroup variable [AddGroup α] [Preorder α] [DecidableRel ((· < ·) : α → α → Prop)] theorem Left.sign_neg [CovariantClass α α (· + ·) (· < ·)] (a : α) : sign (-a) = -sign a := by simp_rw [sign_apply, Left.neg_pos_iff, Left.neg_neg_iff] split_ifs with h h' · exact False.elim (lt_asymm h h') · simp · simp · simp theorem Right.sign_neg [CovariantClass α α (Function.swap (· + ·)) (· < ·)] (a : α) : sign (-a) = -sign a := by simp_rw [sign_apply, Right.neg_pos_iff, Right.neg_neg_iff] split_ifs with h h' · exact False.elim (lt_asymm h h') · simp · simp · simp end AddGroup section LinearOrderedAddCommGroup variable [LinearOrderedAddCommGroup α] /- I'm not sure why this is necessary, see https://leanprover.zulipchat.com/#narrow/stream/113488-general/topic/Decidable.20vs.20decidable_rel -/ attribute [local instance] LinearOrderedAddCommGroup.decidableLT theorem sign_sum {ι : Type*} {s : Finset ι} {f : ι → α} (hs : s.Nonempty) (t : SignType) (h : ∀ i ∈ s, sign (f i) = t) : sign (∑ i ∈ s, f i) = t := by cases t · simp_rw [zero_eq_zero, sign_eq_zero_iff] at h ⊢ exact Finset.sum_eq_zero h · simp_rw [neg_eq_neg_one, sign_eq_neg_one_iff] at h ⊢ exact Finset.sum_neg h hs · simp_rw [pos_eq_one, sign_eq_one_iff] at h ⊢ exact Finset.sum_pos h hs end LinearOrderedAddCommGroup namespace Int theorem sign_eq_sign (n : ℤ) : Int.sign n = SignType.sign n := by obtain (n | _) | _ := n <;> simp [sign, Int.sign_neg, negSucc_lt_zero] end Int open Finset Nat /- Porting note: For all the following theorems, needed to add {α : Type u_1} to the assumptions because lean4 infers α to live in a different universe u_2 otherwise -/ private theorem exists_signed_sum_aux {α : Type u_1} [DecidableEq α] (s : Finset α) (f : α → ℤ) : ∃ (β : Type u_1) (t : Finset β) (sgn : β → SignType) (g : β → α), (∀ b, g b ∈ s) ∧ (t.card = ∑ a ∈ s, (f a).natAbs) ∧ ∀ a ∈ s, (∑ b ∈ t, if g b = a then (sgn b : ℤ) else 0) = f a := by refine ⟨(Σ _ : { x // x ∈ s }, ℕ), Finset.univ.sigma fun a => range (f a).natAbs, fun a => sign (f a.1), fun a => a.1, fun a => a.1.2, ?_, ?_⟩ · simp [sum_attach (f := fun a => (f a).natAbs)] · intro x hx simp [sum_sigma, hx, ← Int.sign_eq_sign, Int.sign_mul_abs, mul_comm |f _|, sum_attach (s := s) (f := fun y => if y = x then f y else 0)] /-- We can decompose a sum of absolute value `n` into a sum of `n` signs. -/ theorem exists_signed_sum {α : Type u_1} [DecidableEq α] (s : Finset α) (f : α → ℤ) : ∃ (β : Type u_1) (_ : Fintype β) (sgn : β → SignType) (g : β → α), (∀ b, g b ∈ s) ∧ (Fintype.card β = ∑ a ∈ s, (f a).natAbs) ∧ ∀ a ∈ s, (∑ b, if g b = a then (sgn b : ℤ) else 0) = f a := let ⟨β, t, sgn, g, hg, ht, hf⟩ := exists_signed_sum_aux s f ⟨t, inferInstance, fun b => sgn b, fun b => g b, fun b => hg b, by simp [ht], fun a ha => (sum_attach t fun b ↦ ite (g b = a) (sgn b : ℤ) 0).trans <| hf _ ha⟩ /-- We can decompose a sum of absolute value less than `n` into a sum of at most `n` signs. -/ theorem exists_signed_sum' {α : Type u_1} [Nonempty α] [DecidableEq α] (s : Finset α) (f : α → ℤ) (n : ℕ) (h : (∑ i ∈ s, (f i).natAbs) ≤ n) : ∃ (β : Type u_1) (_ : Fintype β) (sgn : β → SignType) (g : β → α), (∀ b, g b ∉ s → sgn b = 0) ∧ Fintype.card β = n ∧ ∀ a ∈ s, (∑ i, if g i = a then (sgn i : ℤ) else 0) = f a := by obtain ⟨β, _, sgn, g, hg, hβ, hf⟩ := exists_signed_sum s f refine ⟨β ⊕ (Fin (n - ∑ i ∈ s, (f i).natAbs)), inferInstance, Sum.elim sgn 0, Sum.elim g (Classical.arbitrary (Fin (n - Finset.sum s fun i => Int.natAbs (f i)) → α)), ?_, by simp [hβ, h], fun a ha => by simp [hf _ ha]⟩ rintro (b | b) hb · cases hb (hg _) · rfl
Data\SProd.lean
/- Copyright (c) 2023 Miyahara Kō. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Miyahara Kō -/ import Mathlib.Tactic.FBinop /-! # Set Product Notation This file provides notation for a product of sets, and other similar types. ## Main Definitions * `SProd α β γ` for a binary operation `(· ×ˢ ·) : α → β → γ`. ## Notation We introduce the notation `x ×ˢ y` for the `sprod` of any `SProd` structure. Ideally, `x × y` notation is desirable but this notation is defined in core for `Prod` so replacing `x ×ˢ y` with `x × y` seems difficult. -/ universe u v w /-- Notation type class for the set product `×ˢ`. -/ class SProd (α : Type u) (β : Type v) (γ : outParam (Type w)) where /-- The cartesian product `s ×ˢ t` is the set of `(a, b)` such that `a ∈ s` and `b ∈ t`. -/ sprod : α → β → γ -- This notation binds more strongly than (pre)images, unions and intersections. @[inherit_doc SProd.sprod] infixr:82 " ×ˢ " => SProd.sprod macro_rules | `($x ×ˢ $y) => `(fbinop% SProd.sprod $x $y)
Data\Subtype.lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import Mathlib.Logic.Function.Basic import Mathlib.Tactic.AdaptationNote /-! # Subtypes This file provides basic API for subtypes, which are defined in core. A subtype is a type made from restricting another type, say `α`, to its elements that satisfy some predicate, say `p : α → Prop`. Specifically, it is the type of pairs `⟨val, property⟩` where `val : α` and `property : p val`. It is denoted `Subtype p` and notation `{val : α // p val}` is available. A subtype has a natural coercion to the parent type, by coercing `⟨val, property⟩` to `val`. As such, subtypes can be thought of as bundled sets, the difference being that elements of a set are still of type `α` while elements of a subtype aren't. -/ open Function namespace Subtype variable {α β γ : Sort*} {p q : α → Prop} attribute [coe] Subtype.val initialize_simps_projections Subtype (val → coe) /-- A version of `x.property` or `x.2` where `p` is syntactically applied to the coercion of `x` instead of `x.1`. A similar result is `Subtype.mem` in `Data.Set.Basic`. -/ theorem prop (x : Subtype p) : p x := x.2 /-- An alternative version of `Subtype.forall`. This one is useful if Lean cannot figure out `q` when using `Subtype.forall` from right to left. -/ protected theorem forall' {q : ∀ x, p x → Prop} : (∀ x h, q x h) ↔ ∀ x : { a // p a }, q x x.2 := (@Subtype.forall _ _ fun x ↦ q x.1 x.2).symm /-- An alternative version of `Subtype.exists`. This one is useful if Lean cannot figure out `q` when using `Subtype.exists` from right to left. -/ protected theorem exists' {q : ∀ x, p x → Prop} : (∃ x h, q x h) ↔ ∃ x : { a // p a }, q x x.2 := (@Subtype.exists _ _ fun x ↦ q x.1 x.2).symm theorem heq_iff_coe_eq (h : ∀ x, p x ↔ q x) {a1 : { x // p x }} {a2 : { x // q x }} : HEq a1 a2 ↔ (a1 : α) = (a2 : α) := Eq.rec (motive := fun (pp : (α → Prop)) _ ↦ ∀ a2' : {x // pp x}, HEq a1 a2' ↔ (a1 : α) = (a2' : α)) (fun _ ↦ heq_iff_eq.trans Subtype.ext_iff) (funext <| fun x ↦ propext (h x)) a2 lemma heq_iff_coe_heq {α β : Sort _} {p : α → Prop} {q : β → Prop} {a : {x // p x}} {b : {y // q y}} (h : α = β) (h' : HEq p q) : HEq a b ↔ HEq (a : α) (b : β) := by subst h subst h' rw [heq_iff_eq, heq_iff_eq, Subtype.ext_iff] theorem ext_val {a1 a2 : { x // p x }} : a1.1 = a2.1 → a1 = a2 := Subtype.ext theorem ext_iff_val {a1 a2 : { x // p x }} : a1 = a2 ↔ a1.1 = a2.1 := Subtype.ext_iff @[simp] theorem coe_eta (a : { a // p a }) (h : p a) : mk (↑a) h = a := Subtype.ext rfl theorem coe_mk (a h) : (@mk α p a h : α) = a := rfl -- Porting note: comment out `@[simp, nolint simp_nf]` -- Porting note: not clear if "built-in reduction doesn't always work" is still relevant -- built-in reduction doesn't always work -- @[simp, nolint simp_nf] theorem mk_eq_mk {a h a' h'} : @mk α p a h = @mk α p a' h' ↔ a = a' := Subtype.ext_iff theorem coe_eq_of_eq_mk {a : { a // p a }} {b : α} (h : ↑a = b) : a = ⟨b, h ▸ a.2⟩ := Subtype.ext h theorem coe_eq_iff {a : { a // p a }} {b : α} : ↑a = b ↔ ∃ h, a = ⟨b, h⟩ := ⟨fun h ↦ h ▸ ⟨a.2, (coe_eta _ _).symm⟩, fun ⟨_, ha⟩ ↦ ha.symm ▸ rfl⟩ theorem coe_injective : Injective (fun (a : Subtype p) ↦ (a : α)) := fun _ _ ↦ Subtype.ext theorem val_injective : Injective (@val _ p) := coe_injective theorem coe_inj {a b : Subtype p} : (a : α) = b ↔ a = b := coe_injective.eq_iff theorem val_inj {a b : Subtype p} : a.val = b.val ↔ a = b := coe_inj lemma coe_ne_coe {a b : Subtype p} : (a : α) ≠ b ↔ a ≠ b := coe_injective.ne_iff @[deprecated (since := "2024-04-04")] alias ⟨ne_of_val_ne, _⟩ := coe_ne_coe -- Porting note: it is unclear why the linter doesn't like this. -- If you understand why, please replace this comment with an explanation, or resolve. @[simp, nolint simpNF] theorem _root_.exists_eq_subtype_mk_iff {a : Subtype p} {b : α} : (∃ h : p b, a = Subtype.mk b h) ↔ ↑a = b := coe_eq_iff.symm -- Porting note: it is unclear why the linter doesn't like this. -- If you understand why, please replace this comment with an explanation, or resolve. @[simp, nolint simpNF] theorem _root_.exists_subtype_mk_eq_iff {a : Subtype p} {b : α} : (∃ h : p b, Subtype.mk b h = a) ↔ b = a := by simp only [@eq_comm _ b, exists_eq_subtype_mk_iff, @eq_comm _ _ a] /-- Restrict a (dependent) function to a subtype -/ def restrict {α} {β : α → Type*} (p : α → Prop) (f : ∀ x, β x) (x : Subtype p) : β x.1 := f x theorem restrict_apply {α} {β : α → Type*} (f : ∀ x, β x) (p : α → Prop) (x : Subtype p) : restrict p f x = f x.1 := by rfl theorem restrict_def {α β} (f : α → β) (p : α → Prop) : restrict p f = f ∘ (fun (a : Subtype p) ↦ a) := rfl theorem restrict_injective {α β} {f : α → β} (p : α → Prop) (h : Injective f) : Injective (restrict p f) := h.comp coe_injective theorem surjective_restrict {α} {β : α → Type*} [ne : ∀ a, Nonempty (β a)] (p : α → Prop) : Surjective fun f : ∀ x, β x ↦ restrict p f := by letI := Classical.decPred p refine fun f ↦ ⟨fun x ↦ if h : p x then f ⟨x, h⟩ else Nonempty.some (ne x), funext <| ?_⟩ rintro ⟨x, hx⟩ exact dif_pos hx /-- Defining a map into a subtype, this can be seen as a "coinduction principle" of `Subtype`-/ @[simps] def coind {α β} (f : α → β) {p : β → Prop} (h : ∀ a, p (f a)) : α → Subtype p := fun a ↦ ⟨f a, h a⟩ theorem coind_injective {α β} {f : α → β} {p : β → Prop} (h : ∀ a, p (f a)) (hf : Injective f) : Injective (coind f h) := fun x y hxy ↦ hf <| by apply congr_arg Subtype.val hxy theorem coind_surjective {α β} {f : α → β} {p : β → Prop} (h : ∀ a, p (f a)) (hf : Surjective f) : Surjective (coind f h) := fun x ↦ let ⟨a, ha⟩ := hf x ⟨a, coe_injective ha⟩ theorem coind_bijective {α β} {f : α → β} {p : β → Prop} (h : ∀ a, p (f a)) (hf : Bijective f) : Bijective (coind f h) := ⟨coind_injective h hf.1, coind_surjective h hf.2⟩ /-- Restriction of a function to a function on subtypes. -/ @[simps] def map {p : α → Prop} {q : β → Prop} (f : α → β) (h : ∀ a, p a → q (f a)) : Subtype p → Subtype q := fun x ↦ ⟨f x, h x x.prop⟩ #adaptation_note /-- nightly-2024-03-16: added to replace simp [Subtype.map] -/ theorem map_def {p : α → Prop} {q : β → Prop} (f : α → β) (h : ∀ a, p a → q (f a)) : map f h = fun x ↦ ⟨f x, h x x.prop⟩ := rfl 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) (fun a ha ↦ l (f a) <| h a ha) x := rfl theorem map_id {p : α → Prop} {h : ∀ a, p a → p (id a)} : map (@id α) h = id := funext fun _ ↦ rfl theorem map_injective {p : α → Prop} {q : β → Prop} {f : α → β} (h : ∀ a, p a → q (f a)) (hf : Injective f) : Injective (map f h) := coind_injective _ <| hf.comp coe_injective theorem map_involutive {p : α → Prop} {f : α → α} (h : ∀ a, p a → p (f a)) (hf : Involutive f) : Involutive (map f h) := fun x ↦ Subtype.ext (hf x) instance [HasEquiv α] (p : α → Prop) : HasEquiv (Subtype p) := ⟨fun s t ↦ (s : α) ≈ (t : α)⟩ theorem equiv_iff [HasEquiv α] {p : α → Prop} {s t : Subtype p} : s ≈ t ↔ (s : α) ≈ (t : α) := Iff.rfl variable [Setoid α] protected theorem refl (s : Subtype p) : s ≈ s := Setoid.refl _ protected theorem symm {s t : Subtype p} (h : s ≈ t) : t ≈ s := Setoid.symm h protected theorem trans {s t u : Subtype p} (h₁ : s ≈ t) (h₂ : t ≈ u) : s ≈ u := Setoid.trans h₁ h₂ theorem equivalence (p : α → Prop) : Equivalence (@HasEquiv.Equiv (Subtype p) _) := .mk (Subtype.refl) (@Subtype.symm _ p _) (@Subtype.trans _ p _) instance (p : α → Prop) : Setoid (Subtype p) := Setoid.mk (· ≈ ·) (equivalence p) end Subtype namespace Subtype /-! Some facts about sets, which require that `α` is a type. -/ variable {α β γ : Type*} {p : α → Prop} @[simp] theorem coe_prop {S : Set α} (a : { a // a ∈ S }) : ↑a ∈ S := a.prop theorem val_prop {S : Set α} (a : { a // a ∈ S }) : a.val ∈ S := a.property end Subtype
Data\TwoPointing.lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import Mathlib.Logic.Nontrivial.Defs import Mathlib.Logic.Nonempty import Batteries.Data.Sum.Lemmas /-! # Two-pointings This file defines `TwoPointing α`, the type of two pointings of `α`. A two-pointing is the data of two distinct terms. This is morally a Type-valued `Nontrivial`. Another type which is quite close in essence is `Sym2`. Categorically speaking, `prod` is a cospan in the category of types. This forms the category of bipointed types. Two-pointed types form a full subcategory of those. ## References * [nLab, *Coalgebra of the real interval*] (https://ncatlab.org/nlab/show/coalgebra+of+the+real+interval) -/ open Function variable {α β : Type*} /-- Two-pointing of a type. This is a Type-valued termed `Nontrivial`. -/ @[ext] structure TwoPointing (α : Type*) extends α × α where /-- `fst` and `snd` are distinct terms -/ fst_ne_snd : fst ≠ snd deriving DecidableEq initialize_simps_projections TwoPointing (+toProd, -fst, -snd) namespace TwoPointing variable (p : TwoPointing α) (q : TwoPointing β) theorem snd_ne_fst : p.snd ≠ p.fst := p.fst_ne_snd.symm /-- Swaps the two pointed elements. -/ @[simps] def swap : TwoPointing α := ⟨(p.snd, p.fst), p.snd_ne_fst⟩ theorem swap_fst : p.swap.fst = p.snd := rfl theorem swap_snd : p.swap.snd = p.fst := rfl @[simp] theorem swap_swap : p.swap.swap = p := rfl theorem to_nontrivial : Nontrivial α := ⟨⟨p.fst, p.snd, p.fst_ne_snd⟩⟩ instance [Nontrivial α] : Nonempty (TwoPointing α) := let ⟨a, b, h⟩ := exists_pair_ne α ⟨⟨(a, b), h⟩⟩ @[simp] theorem nonempty_two_pointing_iff : Nonempty (TwoPointing α) ↔ Nontrivial α := ⟨fun ⟨p⟩ ↦ p.to_nontrivial, fun _ => inferInstance⟩ section Pi variable (α) [Nonempty α] /-- The two-pointing of constant functions. -/ def pi : TwoPointing (α → β) where fst _ := q.fst snd _ := q.snd fst_ne_snd h := q.fst_ne_snd (congr_fun h (Classical.arbitrary α)) @[simp] theorem pi_fst : (q.pi α).fst = const α q.fst := rfl @[simp] theorem pi_snd : (q.pi α).snd = const α q.snd := rfl end Pi /-- The product of two two-pointings. -/ def prod : TwoPointing (α × β) where fst := (p.fst, q.fst) snd := (p.snd, q.snd) fst_ne_snd h := p.fst_ne_snd (congr_arg Prod.fst h) @[simp] theorem prod_fst : (p.prod q).fst = (p.fst, q.fst) := rfl @[simp] theorem prod_snd : (p.prod q).snd = (p.snd, q.snd) := rfl /-- The sum of two pointings. Keeps the first point from the left and the second point from the right. -/ protected def sum : TwoPointing (α ⊕ β) := ⟨(Sum.inl p.fst, Sum.inr q.snd), Sum.inl_ne_inr⟩ @[simp] theorem sum_fst : (p.sum q).fst = Sum.inl p.fst := rfl @[simp] theorem sum_snd : (p.sum q).snd = Sum.inr q.snd := rfl /-- The `false`, `true` two-pointing of `Bool`. -/ protected def bool : TwoPointing Bool := ⟨(false, true), Bool.false_ne_true⟩ @[simp] theorem bool_fst : TwoPointing.bool.fst = false := rfl @[simp] theorem bool_snd : TwoPointing.bool.snd = true := rfl instance : Inhabited (TwoPointing Bool) := ⟨TwoPointing.bool⟩ /-- The `False`, `True` two-pointing of `Prop`. -/ protected def prop : TwoPointing Prop := ⟨(False, True), false_ne_true⟩ @[simp] theorem prop_fst : TwoPointing.prop.fst = False := rfl @[simp] theorem prop_snd : TwoPointing.prop.snd = True := rfl end TwoPointing
Data\TypeMax.lean
/- Copyright (c) 2023 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Tactic.ToAdditive /-! # Workaround for changes in universe unification Universe inequalities in Mathlib 3 are expressed through use of `max u v`. Unfortunately, this leads to unbound universes which cannot be solved for during unification, eg `max u v =?= max v ?`. The current solution is to wrap `Type max u v` (and other concrete categories) in `TypeMax.{u,v}` to expose both universe parameters directly. See also https://leanprover.zulipchat.com/#narrow/stream/287929-mathlib4/topic/!4.233463.20universe.20constraint.20issues Note: we mark it as `to_additive` so that `to_additive` doesn't think that types involving this cannot be additivized. This is just to help with the heuristic `to_additive` uses, and doesn't indicate that `TypeMax` has any algebraic operations associated to it. -/ /-- An alias for `Type max u v`, to deal around unification issues. -/ @[nolint checkUnivs, to_additive existing TypeMax] abbrev TypeMax.{u, v} := Type max u v
Data\TypeVec.lean
/- Copyright (c) 2018 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Mario Carneiro, Simon Hudon -/ import Mathlib.Data.Fin.Fin2 import Mathlib.Logic.Function.Basic import Mathlib.Tactic.Common /-! # Tuples of types, and their categorical structure. ## Features * `TypeVec n` - n-tuples of types * `α ⟹ β` - n-tuples of maps * `f ⊚ g` - composition Also, support functions for operating with n-tuples of types, such as: * `append1 α β` - append type `β` to n-tuple `α` to obtain an (n+1)-tuple * `drop α` - drops the last element of an (n+1)-tuple * `last α` - returns the last element of an (n+1)-tuple * `appendFun f g` - appends a function g to an n-tuple of functions * `dropFun f` - drops the last function from an n+1-tuple * `lastFun f` - returns the last function of a tuple. Since e.g. `append1 α.drop α.last` is propositionally equal to `α` but not definitionally equal to it, we need support functions and lemmas to mediate between constructions. -/ universe u v w /-- n-tuples of types, as a category -/ @[pp_with_univ] def TypeVec (n : ℕ) := Fin2 n → Type* instance {n} : Inhabited (TypeVec.{u} n) := ⟨fun _ => PUnit⟩ namespace TypeVec variable {n : ℕ} /-- arrow in the category of `TypeVec` -/ def Arrow (α β : TypeVec n) := ∀ i : Fin2 n, α i → β i @[inherit_doc] scoped[MvFunctor] infixl:40 " ⟹ " => TypeVec.Arrow open MvFunctor /-- Extensionality for arrows -/ @[ext] theorem Arrow.ext {α β : TypeVec n} (f g : α ⟹ β) : (∀ i, f i = g i) → f = g := by intro h; funext i; apply h instance Arrow.inhabited (α β : TypeVec n) [∀ i, Inhabited (β i)] : Inhabited (α ⟹ β) := ⟨fun _ _ => default⟩ /-- identity of arrow composition -/ def id {α : TypeVec n} : α ⟹ α := fun _ x => x /-- arrow composition in the category of `TypeVec` -/ def comp {α β γ : TypeVec n} (g : β ⟹ γ) (f : α ⟹ β) : α ⟹ γ := fun i x => g i (f i x) @[inherit_doc] scoped[MvFunctor] infixr:80 " ⊚ " => TypeVec.comp -- type as \oo @[simp] theorem id_comp {α β : TypeVec n} (f : α ⟹ β) : id ⊚ f = f := rfl @[simp] theorem comp_id {α β : TypeVec n} (f : α ⟹ β) : f ⊚ id = f := rfl theorem comp_assoc {α β γ δ : TypeVec n} (h : γ ⟹ δ) (g : β ⟹ γ) (f : α ⟹ β) : (h ⊚ g) ⊚ f = h ⊚ g ⊚ f := rfl /-- Support for extending a `TypeVec` by one element. -/ def append1 (α : TypeVec n) (β : Type*) : TypeVec (n + 1) | Fin2.fs i => α i | Fin2.fz => β @[inherit_doc] infixl:67 " ::: " => append1 /-- retain only a `n-length` prefix of the argument -/ def drop (α : TypeVec.{u} (n + 1)) : TypeVec n := fun i => α i.fs /-- take the last value of a `(n+1)-length` vector -/ def last (α : TypeVec.{u} (n + 1)) : Type _ := α Fin2.fz instance last.inhabited (α : TypeVec (n + 1)) [Inhabited (α Fin2.fz)] : Inhabited (last α) := ⟨show α Fin2.fz from default⟩ theorem drop_append1 {α : TypeVec n} {β : Type*} {i : Fin2 n} : drop (append1 α β) i = α i := rfl theorem drop_append1' {α : TypeVec n} {β : Type*} : drop (append1 α β) = α := funext fun _ => drop_append1 theorem last_append1 {α : TypeVec n} {β : Type*} : last (append1 α β) = β := rfl @[simp] theorem append1_drop_last (α : TypeVec (n + 1)) : append1 (drop α) (last α) = α := funext fun i => by cases i <;> rfl /-- cases on `(n+1)-length` vectors -/ @[elab_as_elim] def append1Cases {C : TypeVec (n + 1) → Sort u} (H : ∀ α β, C (append1 α β)) (γ) : C γ := by rw [← @append1_drop_last _ γ]; apply H @[simp] theorem append1_cases_append1 {C : TypeVec (n + 1) → Sort u} (H : ∀ α β, C (append1 α β)) (α β) : @append1Cases _ C H (append1 α β) = H α β := rfl /-- append an arrow and a function for arbitrary source and target type vectors -/ def splitFun {α α' : TypeVec (n + 1)} (f : drop α ⟹ drop α') (g : last α → last α') : α ⟹ α' | Fin2.fs i => f i | Fin2.fz => g /-- append an arrow and a function as well as their respective source and target types / typevecs -/ def appendFun {α α' : TypeVec n} {β β' : Type*} (f : α ⟹ α') (g : β → β') : append1 α β ⟹ append1 α' β' := splitFun f g @[inherit_doc] infixl:0 " ::: " => appendFun /-- split off the prefix of an arrow -/ def dropFun {α β : TypeVec (n + 1)} (f : α ⟹ β) : drop α ⟹ drop β := fun i => f i.fs /-- split off the last function of an arrow -/ def lastFun {α β : TypeVec (n + 1)} (f : α ⟹ β) : last α → last β := f Fin2.fz -- Porting note: Lean wasn't able to infer the motive in term mode /-- arrow in the category of `0-length` vectors -/ def nilFun {α : TypeVec 0} {β : TypeVec 0} : α ⟹ β := fun i => by apply Fin2.elim0 i theorem eq_of_drop_last_eq {α β : TypeVec (n + 1)} {f g : α ⟹ β} (h₀ : dropFun f = dropFun g) (h₁ : lastFun f = lastFun g) : f = g := by -- Porting note: FIXME: congr_fun h₀ <;> ext1 ⟨⟩ <;> apply_assumption refine funext (fun x => ?_) cases x · apply h₁ · apply congr_fun h₀ @[simp] theorem dropFun_splitFun {α α' : TypeVec (n + 1)} (f : drop α ⟹ drop α') (g : last α → last α') : dropFun (splitFun f g) = f := rfl /-- turn an equality into an arrow -/ def Arrow.mp {α β : TypeVec n} (h : α = β) : α ⟹ β | _ => Eq.mp (congr_fun h _) /-- turn an equality into an arrow, with reverse direction -/ def Arrow.mpr {α β : TypeVec n} (h : α = β) : β ⟹ α | _ => Eq.mpr (congr_fun h _) /-- decompose a vector into its prefix appended with its last element -/ def toAppend1DropLast {α : TypeVec (n + 1)} : α ⟹ (drop α ::: last α) := Arrow.mpr (append1_drop_last _) /-- stitch two bits of a vector back together -/ def fromAppend1DropLast {α : TypeVec (n + 1)} : (drop α ::: last α) ⟹ α := Arrow.mp (append1_drop_last _) @[simp] theorem lastFun_splitFun {α α' : TypeVec (n + 1)} (f : drop α ⟹ drop α') (g : last α → last α') : lastFun (splitFun f g) = g := rfl @[simp] theorem dropFun_appendFun {α α' : TypeVec n} {β β' : Type*} (f : α ⟹ α') (g : β → β') : dropFun (f ::: g) = f := rfl @[simp] theorem lastFun_appendFun {α α' : TypeVec n} {β β' : Type*} (f : α ⟹ α') (g : β → β') : lastFun (f ::: g) = g := rfl theorem split_dropFun_lastFun {α α' : TypeVec (n + 1)} (f : α ⟹ α') : splitFun (dropFun f) (lastFun f) = f := eq_of_drop_last_eq rfl rfl theorem splitFun_inj {α α' : TypeVec (n + 1)} {f f' : drop α ⟹ drop α'} {g g' : last α → last α'} (H : splitFun f g = splitFun f' g') : f = f' ∧ g = g' := by rw [← dropFun_splitFun f g, H, ← lastFun_splitFun f g, H]; simp theorem appendFun_inj {α α' : TypeVec n} {β β' : Type*} {f f' : α ⟹ α'} {g g' : β → β'} : (f ::: g : (α ::: β) ⟹ _) = (f' ::: g' : (α ::: β) ⟹ _) → f = f' ∧ g = g' := splitFun_inj theorem splitFun_comp {α₀ α₁ α₂ : TypeVec (n + 1)} (f₀ : drop α₀ ⟹ drop α₁) (f₁ : drop α₁ ⟹ drop α₂) (g₀ : last α₀ → last α₁) (g₁ : last α₁ → last α₂) : splitFun (f₁ ⊚ f₀) (g₁ ∘ g₀) = splitFun f₁ g₁ ⊚ splitFun f₀ g₀ := eq_of_drop_last_eq rfl rfl theorem appendFun_comp_splitFun {α γ : TypeVec n} {β δ : Type*} {ε : TypeVec (n + 1)} (f₀ : drop ε ⟹ α) (f₁ : α ⟹ γ) (g₀ : last ε → β) (g₁ : β → δ) : appendFun f₁ g₁ ⊚ splitFun f₀ g₀ = splitFun (α' := γ.append1 δ) (f₁ ⊚ f₀) (g₁ ∘ g₀) := (splitFun_comp _ _ _ _).symm theorem appendFun_comp {α₀ α₁ α₂ : TypeVec n} {β₀ β₁ β₂ : Type*} (f₀ : α₀ ⟹ α₁) (f₁ : α₁ ⟹ α₂) (g₀ : β₀ → β₁) (g₁ : β₁ → β₂) : (f₁ ⊚ f₀ ::: g₁ ∘ g₀) = (f₁ ::: g₁) ⊚ (f₀ ::: g₀) := eq_of_drop_last_eq rfl rfl theorem appendFun_comp' {α₀ α₁ α₂ : TypeVec n} {β₀ β₁ β₂ : Type*} (f₀ : α₀ ⟹ α₁) (f₁ : α₁ ⟹ α₂) (g₀ : β₀ → β₁) (g₁ : β₁ → β₂) : (f₁ ::: g₁) ⊚ (f₀ ::: g₀) = (f₁ ⊚ f₀ ::: g₁ ∘ g₀) := eq_of_drop_last_eq rfl rfl theorem nilFun_comp {α₀ : TypeVec 0} (f₀ : α₀ ⟹ Fin2.elim0) : nilFun ⊚ f₀ = f₀ := funext fun x => by apply Fin2.elim0 x -- Porting note: `by apply` is necessary? theorem appendFun_comp_id {α : TypeVec n} {β₀ β₁ β₂ : Type u} (g₀ : β₀ → β₁) (g₁ : β₁ → β₂) : (@id _ α ::: g₁ ∘ g₀) = (id ::: g₁) ⊚ (id ::: g₀) := eq_of_drop_last_eq rfl rfl @[simp] theorem dropFun_comp {α₀ α₁ α₂ : TypeVec (n + 1)} (f₀ : α₀ ⟹ α₁) (f₁ : α₁ ⟹ α₂) : dropFun (f₁ ⊚ f₀) = dropFun f₁ ⊚ dropFun f₀ := rfl @[simp] theorem lastFun_comp {α₀ α₁ α₂ : TypeVec (n + 1)} (f₀ : α₀ ⟹ α₁) (f₁ : α₁ ⟹ α₂) : lastFun (f₁ ⊚ f₀) = lastFun f₁ ∘ lastFun f₀ := rfl theorem appendFun_aux {α α' : TypeVec n} {β β' : Type*} (f : (α ::: β) ⟹ (α' ::: β')) : (dropFun f ::: lastFun f) = f := eq_of_drop_last_eq rfl rfl theorem appendFun_id_id {α : TypeVec n} {β : Type*} : (@TypeVec.id n α ::: @_root_.id β) = TypeVec.id := eq_of_drop_last_eq rfl rfl instance subsingleton0 : Subsingleton (TypeVec 0) := ⟨fun a b => funext fun a => by apply Fin2.elim0 a⟩ -- Porting note: `by apply` necessary? -- Porting note: `simp` attribute `TypeVec` moved to file `Tactic/Attr/Register.lean` /-- cases distinction for 0-length type vector -/ protected def casesNil {β : TypeVec 0 → Sort*} (f : β Fin2.elim0) : ∀ v, β v := fun v => cast (by congr; funext i; cases i) f /-- cases distinction for (n+1)-length type vector -/ protected def casesCons (n : ℕ) {β : TypeVec (n + 1) → Sort*} (f : ∀ (t) (v : TypeVec n), β (v ::: t)) : ∀ v, β v := fun v : TypeVec (n + 1) => cast (by simp) (f v.last v.drop) protected theorem casesNil_append1 {β : TypeVec 0 → Sort*} (f : β Fin2.elim0) : TypeVec.casesNil f Fin2.elim0 = f := rfl protected theorem casesCons_append1 (n : ℕ) {β : TypeVec (n + 1) → Sort*} (f : ∀ (t) (v : TypeVec n), β (v ::: t)) (v : TypeVec n) (α) : TypeVec.casesCons n f (v ::: α) = f α v := rfl /-- cases distinction for an arrow in the category of 0-length type vectors -/ def typevecCasesNil₃ {β : ∀ v v' : TypeVec 0, v ⟹ v' → Sort*} (f : β Fin2.elim0 Fin2.elim0 nilFun) : ∀ v v' fs, β v v' fs := fun v v' fs => by refine cast ?_ f have eq₁ : v = Fin2.elim0 := by funext i; contradiction have eq₂ : v' = Fin2.elim0 := by funext i; contradiction have eq₃ : fs = nilFun := by funext i; contradiction cases eq₁; cases eq₂; cases eq₃; rfl /-- cases distinction for an arrow in the category of (n+1)-length type vectors -/ def typevecCasesCons₃ (n : ℕ) {β : ∀ v v' : TypeVec (n + 1), v ⟹ v' → Sort*} (F : ∀ (t t') (f : t → t') (v v' : TypeVec n) (fs : v ⟹ v'), β (v ::: t) (v' ::: t') (fs ::: f)) : ∀ v v' fs, β v v' fs := by intro v v' rw [← append1_drop_last v, ← append1_drop_last v'] intro fs rw [← split_dropFun_lastFun fs] apply F /-- specialized cases distinction for an arrow in the category of 0-length type vectors -/ def typevecCasesNil₂ {β : Fin2.elim0 ⟹ Fin2.elim0 → Sort*} (f : β nilFun) : ∀ f, β f := by intro g suffices g = nilFun by rwa [this] ext ⟨⟩ /-- specialized cases distinction for an arrow in the category of (n+1)-length type vectors -/ def typevecCasesCons₂ (n : ℕ) (t t' : Type*) (v v' : TypeVec n) {β : (v ::: t) ⟹ (v' ::: t') → Sort*} (F : ∀ (f : t → t') (fs : v ⟹ v'), β (fs ::: f)) : ∀ fs, β fs := by intro fs rw [← split_dropFun_lastFun fs] apply F theorem typevecCasesNil₂_appendFun {β : Fin2.elim0 ⟹ Fin2.elim0 → Sort*} (f : β nilFun) : typevecCasesNil₂ f nilFun = f := rfl theorem typevecCasesCons₂_appendFun (n : ℕ) (t t' : Type*) (v v' : TypeVec n) {β : (v ::: t) ⟹ (v' ::: t') → Sort*} (F : ∀ (f : t → t') (fs : v ⟹ v'), β (fs ::: f)) (f fs) : typevecCasesCons₂ n t t' v v' F (fs ::: f) = F f fs := rfl -- for lifting predicates and relations /-- `PredLast α p x` predicates `p` of the last element of `x : α.append1 β`. -/ def PredLast (α : TypeVec n) {β : Type*} (p : β → Prop) : ∀ ⦃i⦄, (α.append1 β) i → Prop | Fin2.fs _ => fun _ => True | Fin2.fz => p /-- `RelLast α r x y` says that `p` the last elements of `x y : α.append1 β` are related by `r` and all the other elements are equal. -/ def RelLast (α : TypeVec n) {β γ : Type u} (r : β → γ → Prop) : ∀ ⦃i⦄, (α.append1 β) i → (α.append1 γ) i → Prop | Fin2.fs _ => Eq | Fin2.fz => r section Liftp' open Nat /-- `repeat n t` is a `n-length` type vector that contains `n` occurrences of `t` -/ def «repeat» : ∀ (n : ℕ), Sort _ → TypeVec n | 0, _ => Fin2.elim0 | Nat.succ i, t => append1 («repeat» i t) t /-- `prod α β` is the pointwise product of the components of `α` and `β` -/ def prod : ∀ {n}, TypeVec.{u} n → TypeVec.{u} n → TypeVec n | 0, _, _ => Fin2.elim0 | n + 1, α, β => (@prod n (drop α) (drop β)) ::: (last α × last β) @[inherit_doc] scoped[MvFunctor] infixl:45 " ⊗ " => TypeVec.prod /- porting note: the order of universes in `const` is reversed w.r.t. mathlib3 -/ /-- `const x α` is an arrow that ignores its source and constructs a `TypeVec` that contains nothing but `x` -/ protected def const {β} (x : β) : ∀ {n} (α : TypeVec n), α ⟹ «repeat» _ β | succ _, α, Fin2.fs _ => TypeVec.const x (drop α) _ | succ _, _, Fin2.fz => fun _ => x open Function (uncurry) /-- vector of equality on a product of vectors -/ def repeatEq : ∀ {n} (α : TypeVec n), (α ⊗ α) ⟹ «repeat» _ Prop | 0, _ => nilFun | succ _, α => repeatEq (drop α) ::: uncurry Eq theorem const_append1 {β γ} (x : γ) {n} (α : TypeVec n) : TypeVec.const x (α ::: β) = appendFun (TypeVec.const x α) fun _ => x := by ext i : 1; cases i <;> rfl theorem eq_nilFun {α β : TypeVec 0} (f : α ⟹ β) : f = nilFun := by ext x; cases x theorem id_eq_nilFun {α : TypeVec 0} : @id _ α = nilFun := by ext x; cases x theorem const_nil {β} (x : β) (α : TypeVec 0) : TypeVec.const x α = nilFun := by ext i : 1; cases i @[typevec] theorem repeat_eq_append1 {β} {n} (α : TypeVec n) : repeatEq (α ::: β) = splitFun (α := (α ⊗ α) ::: _ ) (α' := («repeat» n Prop) ::: _) (repeatEq α) (uncurry Eq) := by induction n <;> rfl @[typevec] theorem repeat_eq_nil (α : TypeVec 0) : repeatEq α = nilFun := by ext i; cases i /-- predicate on a type vector to constrain only the last object -/ def PredLast' (α : TypeVec n) {β : Type*} (p : β → Prop) : (α ::: β) ⟹ «repeat» (n + 1) Prop := splitFun (TypeVec.const True α) p /-- predicate on the product of two type vectors to constrain only their last object -/ def RelLast' (α : TypeVec n) {β : Type*} (p : β → β → Prop) : (α ::: β) ⊗ (α ::: β) ⟹ «repeat» (n + 1) Prop := splitFun (repeatEq α) (uncurry p) /-- given `F : TypeVec.{u} (n+1) → Type u`, `curry F : Type u → TypeVec.{u} → Type u`, i.e. its first argument can be fed in separately from the rest of the vector of arguments -/ def Curry (F : TypeVec.{u} (n + 1) → Type*) (α : Type u) (β : TypeVec.{u} n) : Type _ := F (β ::: α) instance Curry.inhabited (F : TypeVec.{u} (n + 1) → Type*) (α : Type u) (β : TypeVec.{u} n) [I : Inhabited (F <| (β ::: α))] : Inhabited (Curry F α β) := I /-- arrow to remove one element of a `repeat` vector -/ def dropRepeat (α : Type*) : ∀ {n}, drop («repeat» (succ n) α) ⟹ «repeat» n α | succ _, Fin2.fs i => dropRepeat α i | succ _, Fin2.fz => fun (a : α) => a /-- projection for a repeat vector -/ def ofRepeat {α : Sort _} : ∀ {n i}, «repeat» n α i → α | _, Fin2.fz => fun (a : α) => a | _, Fin2.fs i => @ofRepeat _ _ i theorem const_iff_true {α : TypeVec n} {i x p} : ofRepeat (TypeVec.const p α i x) ↔ p := by induction i with | fz => rfl | fs _ ih => erw [TypeVec.const, @ih (drop α) x] section variable {α β γ : TypeVec.{u} n} variable (p : α ⟹ «repeat» n Prop) (r : α ⊗ α ⟹ «repeat» n Prop) /-- left projection of a `prod` vector -/ def prod.fst : ∀ {n} {α β : TypeVec.{u} n}, α ⊗ β ⟹ α | succ _, α, β, Fin2.fs i => @prod.fst _ (drop α) (drop β) i | succ _, _, _, Fin2.fz => Prod.fst /-- right projection of a `prod` vector -/ def prod.snd : ∀ {n} {α β : TypeVec.{u} n}, α ⊗ β ⟹ β | succ _, α, β, Fin2.fs i => @prod.snd _ (drop α) (drop β) i | succ _, _, _, Fin2.fz => Prod.snd /-- introduce a product where both components are the same -/ def prod.diag : ∀ {n} {α : TypeVec.{u} n}, α ⟹ α ⊗ α | succ _, α, Fin2.fs _, x => @prod.diag _ (drop α) _ x | succ _, _, Fin2.fz, x => (x, x) /-- constructor for `prod` -/ def prod.mk : ∀ {n} {α β : TypeVec.{u} n} (i : Fin2 n), α i → β i → (α ⊗ β) i | succ _, α, β, Fin2.fs i => mk (α := fun i => α i.fs) (β := fun i => β i.fs) i | succ _, _, _, Fin2.fz => Prod.mk end @[simp] theorem prod_fst_mk {α β : TypeVec n} (i : Fin2 n) (a : α i) (b : β i) : TypeVec.prod.fst i (prod.mk i a b) = a := by induction' i with _ _ _ i_ih · simp_all only [prod.fst, prod.mk] apply i_ih @[simp] theorem prod_snd_mk {α β : TypeVec n} (i : Fin2 n) (a : α i) (b : β i) : TypeVec.prod.snd i (prod.mk i a b) = b := by induction' i with _ _ _ i_ih · simp_all [prod.snd, prod.mk] apply i_ih /-- `prod` is functorial -/ protected def prod.map : ∀ {n} {α α' β β' : TypeVec.{u} n}, α ⟹ β → α' ⟹ β' → α ⊗ α' ⟹ β ⊗ β' | succ _, α, α', β, β', x, y, Fin2.fs _, a => @prod.map _ (drop α) (drop α') (drop β) (drop β') (dropFun x) (dropFun y) _ a | succ _, _, _, _, _, x, y, Fin2.fz, a => (x _ a.1, y _ a.2) @[inherit_doc] scoped[MvFunctor] infixl:45 " ⊗' " => TypeVec.prod.map theorem fst_prod_mk {α α' β β' : TypeVec n} (f : α ⟹ β) (g : α' ⟹ β') : TypeVec.prod.fst ⊚ (f ⊗' g) = f ⊚ TypeVec.prod.fst := by funext i; induction i with | fz => rfl | fs _ i_ih => apply i_ih theorem snd_prod_mk {α α' β β' : TypeVec n} (f : α ⟹ β) (g : α' ⟹ β') : TypeVec.prod.snd ⊚ (f ⊗' g) = g ⊚ TypeVec.prod.snd := by funext i; induction i with | fz => rfl | fs _ i_ih => apply i_ih theorem fst_diag {α : TypeVec n} : TypeVec.prod.fst ⊚ (prod.diag : α ⟹ _) = id := by funext i; induction i with | fz => rfl | fs _ i_ih => apply i_ih theorem snd_diag {α : TypeVec n} : TypeVec.prod.snd ⊚ (prod.diag : α ⟹ _) = id := by funext i; induction i with | fz => rfl | fs _ i_ih => apply i_ih theorem repeatEq_iff_eq {α : TypeVec n} {i x y} : ofRepeat (repeatEq α i (prod.mk _ x y)) ↔ x = y := by induction' i with _ _ _ i_ih · rfl erw [repeatEq, i_ih] /-- given a predicate vector `p` over vector `α`, `Subtype_ p` is the type of vectors that contain an `α` that satisfies `p` -/ def Subtype_ : ∀ {n} {α : TypeVec.{u} n}, (α ⟹ «repeat» n Prop) → TypeVec n | _, _, p, Fin2.fz => Subtype fun x => p Fin2.fz x | _, _, p, Fin2.fs i => Subtype_ (dropFun p) i /-- projection on `Subtype_` -/ def subtypeVal : ∀ {n} {α : TypeVec.{u} n} (p : α ⟹ «repeat» n Prop), Subtype_ p ⟹ α | succ n, _, _, Fin2.fs i => @subtypeVal n _ _ i | succ _, _, _, Fin2.fz => Subtype.val /-- arrow that rearranges the type of `Subtype_` to turn a subtype of vector into a vector of subtypes -/ def toSubtype : ∀ {n} {α : TypeVec.{u} n} (p : α ⟹ «repeat» n Prop), (fun i : Fin2 n => { x // ofRepeat <| p i x }) ⟹ Subtype_ p | succ _, _, p, Fin2.fs i, x => toSubtype (dropFun p) i x | succ _, _, _, Fin2.fz, x => x /-- arrow that rearranges the type of `Subtype_` to turn a vector of subtypes into a subtype of vector -/ def ofSubtype {n} {α : TypeVec.{u} n} (p : α ⟹ «repeat» n Prop) : Subtype_ p ⟹ fun i : Fin2 n => { x // ofRepeat <| p i x } | Fin2.fs i, x => ofSubtype _ i x | Fin2.fz, x => x /-- similar to `toSubtype` adapted to relations (i.e. predicate on product) -/ def toSubtype' {n} {α : TypeVec.{u} n} (p : α ⊗ α ⟹ «repeat» n Prop) : (fun i : Fin2 n => { x : α i × α i // ofRepeat <| p i (prod.mk _ x.1 x.2) }) ⟹ Subtype_ p | Fin2.fs i, x => toSubtype' (dropFun p) i x | Fin2.fz, x => ⟨x.val, cast (by congr) x.property⟩ /-- similar to `of_subtype` adapted to relations (i.e. predicate on product) -/ def ofSubtype' {n} {α : TypeVec.{u} n} (p : α ⊗ α ⟹ «repeat» n Prop) : Subtype_ p ⟹ fun i : Fin2 n => { x : α i × α i // ofRepeat <| p i (prod.mk _ x.1 x.2) } | Fin2.fs i, x => ofSubtype' _ i x | Fin2.fz, x => ⟨x.val, cast (by congr) x.property⟩ /-- similar to `diag` but the target vector is a `Subtype_` guaranteeing the equality of the components -/ def diagSub {n} {α : TypeVec.{u} n} : α ⟹ Subtype_ (repeatEq α) | Fin2.fs _, x => @diagSub _ (drop α) _ x | Fin2.fz, x => ⟨(x, x), rfl⟩ theorem subtypeVal_nil {α : TypeVec.{u} 0} (ps : α ⟹ «repeat» 0 Prop) : TypeVec.subtypeVal ps = nilFun := funext <| by rintro ⟨⟩ theorem diag_sub_val {n} {α : TypeVec.{u} n} : subtypeVal (repeatEq α) ⊚ diagSub = prod.diag := by ext i x induction' i with _ _ _ i_ih · simp only [comp, subtypeVal, repeatEq.eq_2, diagSub, prod.diag] apply @i_ih (drop α) theorem prod_id : ∀ {n} {α β : TypeVec.{u} n}, (id ⊗' id) = (id : α ⊗ β ⟹ _) := by intros ext i a induction' i with _ _ _ i_ih · cases a rfl · apply i_ih theorem append_prod_appendFun {n} {α α' β β' : TypeVec.{u} n} {φ φ' ψ ψ' : Type u} {f₀ : α ⟹ α'} {g₀ : β ⟹ β'} {f₁ : φ → φ'} {g₁ : ψ → ψ'} : ((f₀ ⊗' g₀) ::: (_root_.Prod.map f₁ g₁)) = ((f₀ ::: f₁) ⊗' (g₀ ::: g₁)) := by ext i a cases i · cases a rfl · rfl end Liftp' @[simp] theorem dropFun_diag {α} : dropFun (@prod.diag (n + 1) α) = prod.diag := by ext i : 2 induction i <;> simp [dropFun, *] <;> rfl @[simp] theorem dropFun_subtypeVal {α} (p : α ⟹ «repeat» (n + 1) Prop) : dropFun (subtypeVal p) = subtypeVal _ := rfl @[simp] theorem lastFun_subtypeVal {α} (p : α ⟹ «repeat» (n + 1) Prop) : lastFun (subtypeVal p) = Subtype.val := rfl @[simp] theorem dropFun_toSubtype {α} (p : α ⟹ «repeat» (n + 1) Prop) : dropFun (toSubtype p) = toSubtype _ := by ext i induction i <;> simp [dropFun, *] <;> rfl @[simp] theorem lastFun_toSubtype {α} (p : α ⟹ «repeat» (n + 1) Prop) : lastFun (toSubtype p) = _root_.id := by ext i : 2 induction i; simp [dropFun, *]; rfl @[simp] theorem dropFun_of_subtype {α} (p : α ⟹ «repeat» (n + 1) Prop) : dropFun (ofSubtype p) = ofSubtype _ := by ext i : 2 induction i <;> simp [dropFun, *] <;> rfl @[simp] theorem lastFun_of_subtype {α} (p : α ⟹ «repeat» (n + 1) Prop) : lastFun (ofSubtype p) = _root_.id := by ext i : 2 induction i; simp [dropFun, *]; rfl @[simp] theorem dropFun_RelLast' {α : TypeVec n} {β} (R : β → β → Prop) : dropFun (RelLast' α R) = repeatEq α := rfl attribute [simp] drop_append1' open MvFunctor @[simp] theorem dropFun_prod {α α' β β' : TypeVec (n + 1)} (f : α ⟹ β) (f' : α' ⟹ β') : dropFun (f ⊗' f') = (dropFun f ⊗' dropFun f') := by ext i : 2 induction i <;> simp [dropFun, *] <;> rfl @[simp] theorem lastFun_prod {α α' β β' : TypeVec (n + 1)} (f : α ⟹ β) (f' : α' ⟹ β') : lastFun (f ⊗' f') = Prod.map (lastFun f) (lastFun f') := by ext i : 1 induction i; simp [lastFun, *]; rfl @[simp] theorem dropFun_from_append1_drop_last {α : TypeVec (n + 1)} : dropFun (@fromAppend1DropLast _ α) = id := rfl @[simp] theorem lastFun_from_append1_drop_last {α : TypeVec (n + 1)} : lastFun (@fromAppend1DropLast _ α) = _root_.id := rfl @[simp] theorem dropFun_id {α : TypeVec (n + 1)} : dropFun (@TypeVec.id _ α) = id := rfl @[simp] theorem prod_map_id {α β : TypeVec n} : (@TypeVec.id _ α ⊗' @TypeVec.id _ β) = id := by ext i x : 2 induction i <;> simp only [TypeVec.prod.map, *, dropFun_id] cases x · rfl · rfl @[simp] theorem subtypeVal_diagSub {α : TypeVec n} : subtypeVal (repeatEq α) ⊚ diagSub = prod.diag := by ext i x induction' i with _ _ _ i_ih · simp [comp, diagSub, subtypeVal, prod.diag] · simp only [comp, subtypeVal, diagSub, prod.diag] at * apply i_ih @[simp] theorem toSubtype_of_subtype {α : TypeVec n} (p : α ⟹ «repeat» n Prop) : toSubtype p ⊚ ofSubtype p = id := by ext i x induction i <;> dsimp only [id, toSubtype, comp, ofSubtype] at * simp [*] @[simp] theorem subtypeVal_toSubtype {α : TypeVec n} (p : α ⟹ «repeat» n Prop) : subtypeVal p ⊚ toSubtype p = fun _ => Subtype.val := by ext i x induction i <;> dsimp only [toSubtype, comp, subtypeVal] at * simp [*] @[simp] theorem toSubtype_of_subtype_assoc {α β : TypeVec n} (p : α ⟹ «repeat» n Prop) (f : β ⟹ Subtype_ p) : @toSubtype n _ p ⊚ ofSubtype _ ⊚ f = f := by rw [← comp_assoc, toSubtype_of_subtype]; simp @[simp] theorem toSubtype'_of_subtype' {α : TypeVec n} (r : α ⊗ α ⟹ «repeat» n Prop) : toSubtype' r ⊚ ofSubtype' r = id := by ext i x induction i <;> dsimp only [id, toSubtype', comp, ofSubtype'] at * <;> simp [Subtype.eta, *] theorem subtypeVal_toSubtype' {α : TypeVec n} (r : α ⊗ α ⟹ «repeat» n Prop) : subtypeVal r ⊚ toSubtype' r = fun i x => prod.mk i x.1.fst x.1.snd := by ext i x induction i <;> dsimp only [id, toSubtype', comp, subtypeVal, prod.mk] at * simp [*] end TypeVec
Data\UInt.lean
/- Copyright (c) 2021 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Data.ZMod.Defs /-! # Adds Mathlib specific instances to the `UIntX` data types. The `CommRing` instances (and the `NatCast` and `IntCast` instances from which they is built) are scoped in the `UIntX.CommRing` namespace, rather than available globally. As a result, the `ring` tactic will not work on `UIntX` types without `open scoped UIntX.Ring`. This is because the presence of these casting operations contradicts assumptions made by the expression tree elaborator, namely that coercions do not form a cycle. The UInt version also interferes more with software-verification use-cases, which is reason to be more cautious here. -/ example : (0 : UInt8) = ⟨0⟩ := rfl set_option hygiene false in run_cmd for typeName' in [`UInt8, `UInt16, `UInt32, `UInt64, `USize] do let typeName := Lean.mkIdent typeName' Lean.Elab.Command.elabCommand (← `( namespace $typeName instance neZero : NeZero size := ⟨by decide⟩ instance : Neg $typeName where neg a := mk (-a.val) instance : Pow $typeName ℕ where pow a n := mk (a.val ^ n) instance : SMul ℕ $typeName where smul n a := mk (n • a.val) instance : SMul ℤ $typeName where smul z a := mk (z • a.val) lemma neg_def (a : $typeName) : -a = ⟨-a.val⟩ := rfl lemma pow_def (a : $typeName) (n : ℕ) : a ^ n = ⟨a.val ^ n⟩ := rfl lemma nsmul_def (n : ℕ) (a : $typeName) : n • a = ⟨n • a.val⟩ := rfl lemma zsmul_def (z : ℤ) (a : $typeName) : z • a = ⟨z • a.val⟩ := rfl open $typeName (eq_of_val_eq) in lemma val_injective : Function.Injective val := @eq_of_val_eq instance instCommMonoid : CommMonoid $typeName := Function.Injective.commMonoid val val_injective rfl (fun _ _ => rfl) (fun _ _ => rfl) instance instNonUnitalCommRing : NonUnitalCommRing $typeName := Function.Injective.nonUnitalCommRing val val_injective rfl (fun _ _ => rfl) (fun _ _ => rfl) (fun _ => rfl) (fun _ _ => rfl) (fun _ _ => rfl) (fun _ _ => rfl) local instance instNatCast : NatCast $typeName where natCast n := mk n local instance instIntCast : IntCast $typeName where intCast z := mk z lemma natCast_def (n : ℕ) : (n : $typeName) = ⟨n⟩ := rfl lemma intCast_def (z : ℤ) : (z : $typeName) = ⟨z⟩ := rfl local instance instCommRing : CommRing $typeName := Function.Injective.commRing val val_injective rfl rfl (fun _ _ => rfl) (fun _ _ => rfl) (fun _ => rfl) (fun _ _ => rfl) (fun _ _ => rfl) (fun _ _ => rfl) (fun _ _ => rfl) (fun _ => rfl) (fun _ => rfl) namespace CommRing attribute [scoped instance] instCommRing instNatCast instIntCast end CommRing end $typeName )) -- interpolating docstrings above is more trouble than it's worth let docString := s!"To use this instance, use `open scoped {typeName'}.CommRing`.\n\n" ++ "See the module docstring for an explanation" Lean.addDocString (typeName'.mkStr "instCommRing") docString Lean.addDocString (typeName'.mkStr "instNatCast") docString Lean.addDocString (typeName'.mkStr "instIntCast") docString namespace UInt8 /-- Is this an uppercase ASCII letter? -/ def isASCIIUpper (c : UInt8) : Bool := c ≥ 65 && c ≤ 90 /-- Is this a lowercase ASCII letter? -/ def isASCIILower (c : UInt8) : Bool := c ≥ 97 && c ≤ 122 /-- Is this an alphabetic ASCII character? -/ def isASCIIAlpha (c : UInt8) : Bool := c.isASCIIUpper || c.isASCIILower /-- Is this an ASCII digit character? -/ def isASCIIDigit (c : UInt8) : Bool := c ≥ 48 && c ≤ 57 /-- Is this an alphanumeric ASCII character? -/ def isASCIIAlphanum (c : UInt8) : Bool := c.isASCIIAlpha || c.isASCIIDigit @[deprecated (since := "2024-06-06")] alias isUpper := isASCIIUpper @[deprecated (since := "2024-06-06")] alias isLower := isASCIILower @[deprecated (since := "2024-06-06")] alias isAlpha := isASCIIAlpha @[deprecated (since := "2024-06-06")] alias isDigit := isASCIIDigit @[deprecated (since := "2024-06-06")] alias isAlphanum := isASCIIAlphanum /-- The numbers from 0 to 256 are all valid UTF-8 characters, so we can embed one in the other. -/ def toChar (n : UInt8) : Char := ⟨n.toUInt32, .inl (n.1.2.trans (by decide))⟩ end UInt8
Data\ULift.lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import Mathlib.Control.ULift import Mathlib.Logic.Equiv.Basic /-! # Extra lemmas about `ULift` and `PLift` In this file we provide `Subsingleton`, `Unique`, `DecidableEq`, and `isEmpty` instances for `ULift α` and `PLift α`. We also prove `ULift.forall`, `ULift.exists`, `PLift.forall`, and `PLift.exists`. -/ universe u v u' v' open Function namespace PLift variable {α : Sort u} {β : Sort v} {f : α → β} instance [Subsingleton α] : Subsingleton (PLift α) := Equiv.plift.subsingleton instance [Nonempty α] : Nonempty (PLift α) := Equiv.plift.nonempty instance [Unique α] : Unique (PLift α) := Equiv.plift.unique instance [DecidableEq α] : DecidableEq (PLift α) := Equiv.plift.decidableEq instance [IsEmpty α] : IsEmpty (PLift α) := Equiv.plift.isEmpty theorem up_injective : Injective (@up α) := Equiv.plift.symm.injective theorem up_surjective : Surjective (@up α) := Equiv.plift.symm.surjective theorem up_bijective : Bijective (@up α) := Equiv.plift.symm.bijective @[simp] theorem up_inj {x y : α} : up x = up y ↔ x = y := up_injective.eq_iff theorem down_surjective : Surjective (@down α) := Equiv.plift.surjective theorem down_bijective : Bijective (@down α) := Equiv.plift.bijective @[simp] theorem «forall» {p : PLift α → Prop} : (∀ x, p x) ↔ ∀ x : α, p (PLift.up x) := up_surjective.forall @[simp] theorem «exists» {p : PLift α → Prop} : (∃ x, p x) ↔ ∃ x : α, p (PLift.up x) := up_surjective.exists @[simp] lemma map_injective : Injective (PLift.map f) ↔ Injective f := (Injective.of_comp_iff' _ down_bijective).trans <| up_injective.of_comp_iff _ @[simp] lemma map_surjective : Surjective (PLift.map f) ↔ Surjective f := (down_surjective.of_comp_iff _).trans <| Surjective.of_comp_iff' up_bijective _ @[simp] lemma map_bijective : Bijective (PLift.map f) ↔ Bijective f := (down_bijective.of_comp_iff _).trans <| Bijective.of_comp_iff' up_bijective _ end PLift namespace ULift variable {α : Type u} {β : Type v} {f : α → β} instance [Subsingleton α] : Subsingleton (ULift α) := Equiv.ulift.subsingleton instance [Nonempty α] : Nonempty (ULift α) := Equiv.ulift.nonempty instance [Unique α] : Unique (ULift α) := Equiv.ulift.unique instance [DecidableEq α] : DecidableEq (ULift α) := Equiv.ulift.decidableEq instance [IsEmpty α] : IsEmpty (ULift α) := Equiv.ulift.isEmpty theorem up_injective : Injective (@up α) := Equiv.ulift.symm.injective theorem up_surjective : Surjective (@up α) := Equiv.ulift.symm.surjective theorem up_bijective : Bijective (@up α) := Equiv.ulift.symm.bijective @[simp] theorem up_inj {x y : α} : up x = up y ↔ x = y := up_injective.eq_iff theorem down_surjective : Surjective (@down α) := Equiv.ulift.surjective theorem down_bijective : Bijective (@down α) := Equiv.ulift.bijective @[simp] theorem «forall» {p : ULift α → Prop} : (∀ x, p x) ↔ ∀ x : α, p (ULift.up x) := up_surjective.forall @[simp] theorem «exists» {p : ULift α → Prop} : (∃ x, p x) ↔ ∃ x : α, p (ULift.up x) := up_surjective.exists @[simp] lemma map_injective : Injective (ULift.map f : ULift.{u'} α → ULift.{v'} β) ↔ Injective f := (Injective.of_comp_iff' _ down_bijective).trans <| up_injective.of_comp_iff _ @[simp] lemma map_surjective : Surjective (ULift.map f : ULift.{u'} α → ULift.{v'} β) ↔ Surjective f := (down_surjective.of_comp_iff _).trans <| Surjective.of_comp_iff' up_bijective _ @[simp] lemma map_bijective : Bijective (ULift.map f : ULift.{u'} α → ULift.{v'} β) ↔ Bijective f := (down_bijective.of_comp_iff _).trans <| Bijective.of_comp_iff' up_bijective _ @[ext] theorem ext (x y : ULift α) (h : x.down = y.down) : x = y := congrArg up h end ULift
Data\Vector3.lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Data.Fin.Fin2 import Mathlib.Init.Logic import Mathlib.Mathport.Notation import Mathlib.Tactic.TypeStar /-! # Alternate definition of `Vector` in terms of `Fin2` This file provides a locale `Vector3` which overrides the `[a, b, c]` notation to create a `Vector3` instead of a `List`. The `::` notation is also overloaded by this file to mean `Vector3.cons`. -/ open Fin2 Nat universe u variable {α : Type*} {m n : ℕ} /-- Alternate definition of `Vector` based on `Fin2`. -/ def Vector3 (α : Type u) (n : ℕ) : Type u := Fin2 n → α instance [Inhabited α] : Inhabited (Vector3 α n) where default := fun _ => default namespace Vector3 /-- The empty vector -/ @[match_pattern] def nil : Vector3 α 0 := nofun /-- The vector cons operation -/ @[match_pattern] def cons (a : α) (v : Vector3 α n) : Vector3 α (n + 1) := fun i => by refine i.cases' ?_ ?_ · exact a · exact v section open Lean -- Porting note: was -- scoped notation3 "["(l", "* => foldr (h t => cons h t) nil)"]" => l scoped macro_rules | `([$l,*]) => `(expand_foldr% (h t => cons h t) nil [$(.ofElems l),*]) -- this is copied from `src/Init/NotationExtra.lean` @[app_unexpander Vector3.nil] def unexpandNil : Lean.PrettyPrinter.Unexpander | `($(_)) => `([]) -- this is copied from `src/Init/NotationExtra.lean` @[app_unexpander Vector3.cons] def unexpandCons : Lean.PrettyPrinter.Unexpander | `($(_) $x []) => `([$x]) | `($(_) $x [$xs,*]) => `([$x, $xs,*]) | _ => throw () end -- Overloading the usual `::` notation for `List.cons` with `Vector3.cons`. @[inherit_doc] scoped notation a " :: " b => cons a b @[simp] theorem cons_fz (a : α) (v : Vector3 α n) : (a :: v) fz = a := rfl @[simp] theorem cons_fs (a : α) (v : Vector3 α n) (i) : (a :: v) (fs i) = v i := rfl /-- Get the `i`th element of a vector -/ abbrev nth (i : Fin2 n) (v : Vector3 α n) : α := v i /-- Construct a vector from a function on `Fin2`. -/ abbrev ofFn (f : Fin2 n → α) : Vector3 α n := f /-- Get the head of a nonempty vector. -/ def head (v : Vector3 α (n + 1)) : α := v fz /-- Get the tail of a nonempty vector. -/ def tail (v : Vector3 α (n + 1)) : Vector3 α n := fun i => v (fs i) theorem eq_nil (v : Vector3 α 0) : v = [] := funext fun i => nomatch i theorem cons_head_tail (v : Vector3 α (n + 1)) : (head v :: tail v) = v := funext fun i => Fin2.cases' rfl (fun _ => rfl) i /-- Eliminator for an empty vector. -/ @[elab_as_elim] -- Porting note: add `elab_as_elim` def nilElim {C : Vector3 α 0 → Sort u} (H : C []) (v : Vector3 α 0) : C v := by rw [eq_nil v]; apply H /-- Recursion principle for a nonempty vector. -/ @[elab_as_elim] -- Porting note: add `elab_as_elim` def consElim {C : Vector3 α (n + 1) → Sort u} (H : ∀ (a : α) (t : Vector3 α n), C (a :: t)) (v : Vector3 α (n + 1)) : C v := by rw [← cons_head_tail v]; apply H @[simp] theorem consElim_cons {C H a t} : @consElim α n C H (a :: t) = H a t := rfl /-- Recursion principle with the vector as first argument. -/ @[elab_as_elim] protected def recOn {C : ∀ {n}, Vector3 α n → Sort u} {n} (v : Vector3 α n) (H0 : C []) (Hs : ∀ {n} (a) (w : Vector3 α n), C w → C (a :: w)) : C v := match n with | 0 => v.nilElim H0 | _ + 1 => v.consElim fun a t => Hs a t (Vector3.recOn t H0 Hs) @[simp] theorem recOn_nil {C H0 Hs} : @Vector3.recOn α (@C) 0 [] H0 @Hs = H0 := rfl @[simp] theorem recOn_cons {C H0 Hs n a v} : @Vector3.recOn α (@C) (n + 1) (a :: v) H0 @Hs = Hs a v (@Vector3.recOn α (@C) n v H0 @Hs) := rfl /-- Append two vectors -/ def append (v : Vector3 α m) (w : Vector3 α n) : Vector3 α (n + m) := v.recOn w (fun a _ IH => a :: IH) /-- A local infix notation for `Vector3.append` -/ local infixl:65 " +-+ " => Vector3.append @[simp] theorem append_nil (w : Vector3 α n) : [] +-+ w = w := rfl @[simp] theorem append_cons (a : α) (v : Vector3 α m) (w : Vector3 α n) : (a :: v) +-+ w = a :: v +-+ w := rfl @[simp] theorem append_left : ∀ {m} (i : Fin2 m) (v : Vector3 α m) {n} (w : Vector3 α n), (v +-+ w) (left n i) = v i | _, @fz m, v, n, w => v.consElim fun a _t => by simp [*, left] | _, @fs m i, v, n, w => v.consElim fun _a t => by simp [append_left, left] @[simp] theorem append_add : ∀ {m} (v : Vector3 α m) {n} (w : Vector3 α n) (i : Fin2 n), (v +-+ w) (add i m) = w i | 0, v, n, w, i => rfl | m + 1, v, n, w, i => v.consElim fun _a t => by simp [append_add, add] /-- Insert `a` into `v` at index `i`. -/ def insert (a : α) (v : Vector3 α n) (i : Fin2 (n + 1)) : Vector3 α (n + 1) := fun j => (a :: v) (insertPerm i j) @[simp] theorem insert_fz (a : α) (v : Vector3 α n) : insert a v fz = a :: v := by refine funext fun j => j.cases' ?_ ?_ <;> intros <;> rfl @[simp] theorem insert_fs (a : α) (b : α) (v : Vector3 α n) (i : Fin2 (n + 1)) : insert a (b :: v) (fs i) = b :: insert a v i := funext fun j => by refine j.cases' ?_ fun j => ?_ <;> simp [insert, insertPerm] refine Fin2.cases' ?_ ?_ (insertPerm i j) <;> simp [insertPerm] theorem append_insert (a : α) (t : Vector3 α m) (v : Vector3 α n) (i : Fin2 (n + 1)) (e : (n + 1) + m = (n + m) + 1) : insert a (t +-+ v) (Eq.recOn e (i.add m)) = Eq.recOn e (t +-+ insert a v i) := by refine Vector3.recOn t (fun e => ?_) (@fun k b t IH _ => ?_) e · rfl have e' : (n + 1) + k = (n + k) + 1 := by omega change insert a (b :: t +-+ v) (Eq.recOn (congr_arg (· + 1) e' : _ + 1 = _) (fs (add i k))) = Eq.recOn (congr_arg (· + 1) e' : _ + 1 = _) (b :: t +-+ insert a v i) rw [← (Eq.recOn e' rfl : fs (Eq.recOn e' (i.add k) : Fin2 ((n + k) + 1)) = Eq.recOn (congr_arg (· + 1) e' : _ + 1 = _) (fs (i.add k)))] simpa [IH] using Eq.recOn e' rfl end Vector3 section Vector3 open Vector3 /-- "Curried" exists, i.e. `∃ x₁ ... xₙ, f [x₁, ..., xₙ]`. -/ def VectorEx : ∀ k, (Vector3 α k → Prop) → Prop | 0, f => f [] | succ k, f => ∃ x : α, VectorEx k fun v => f (x :: v) /-- "Curried" forall, i.e. `∀ x₁ ... xₙ, f [x₁, ..., xₙ]`. -/ def VectorAll : ∀ k, (Vector3 α k → Prop) → Prop | 0, f => f [] | succ k, f => ∀ x : α, VectorAll k fun v => f (x :: v) theorem exists_vector_zero (f : Vector3 α 0 → Prop) : Exists f ↔ f [] := ⟨fun ⟨v, fv⟩ => by rw [← eq_nil v]; exact fv, fun f0 => ⟨[], f0⟩⟩ theorem exists_vector_succ (f : Vector3 α (succ n) → Prop) : Exists f ↔ ∃ x v, f (x :: v) := ⟨fun ⟨v, fv⟩ => ⟨_, _, by rw [cons_head_tail v]; exact fv⟩, fun ⟨x, v, fxv⟩ => ⟨_, fxv⟩⟩ theorem vectorEx_iff_exists : ∀ {n} (f : Vector3 α n → Prop), VectorEx n f ↔ Exists f | 0, f => (exists_vector_zero f).symm | succ _, f => Iff.trans (exists_congr fun _ => vectorEx_iff_exists _) (exists_vector_succ f).symm theorem vectorAll_iff_forall : ∀ {n} (f : Vector3 α n → Prop), VectorAll n f ↔ ∀ v, f v | 0, _ => ⟨fun f0 v => v.nilElim f0, fun al => al []⟩ | succ _, f => (forall_congr' fun x => vectorAll_iff_forall fun v => f (x :: v)).trans ⟨fun al v => v.consElim al, fun al x v => al (x :: v)⟩ /-- `VectorAllP p v` is equivalent to `∀ i, p (v i)`, but unfolds directly to a conjunction, i.e. `VectorAllP p [0, 1, 2] = p 0 ∧ p 1 ∧ p 2`. -/ def VectorAllP (p : α → Prop) (v : Vector3 α n) : Prop := Vector3.recOn v True fun a v IH => @Vector3.recOn _ (fun _ => Prop) _ v (p a) fun _ _ _ => p a ∧ IH @[simp] theorem vectorAllP_nil (p : α → Prop) : VectorAllP p [] = True := rfl @[simp] theorem vectorAllP_singleton (p : α → Prop) (x : α) : VectorAllP p (cons x []) = p x := rfl @[simp] theorem vectorAllP_cons (p : α → Prop) (x : α) (v : Vector3 α n) : VectorAllP p (x :: v) ↔ p x ∧ VectorAllP p v := Vector3.recOn v (and_true_iff _).symm fun _ _ _ => Iff.rfl theorem vectorAllP_iff_forall (p : α → Prop) (v : Vector3 α n) : VectorAllP p v ↔ ∀ i, p (v i) := by refine v.recOn ?_ ?_ · exact ⟨fun _ => Fin2.elim0, fun _ => trivial⟩ · simp only [vectorAllP_cons] refine fun {n} a v IH => (and_congr_right fun _ => IH).trans ⟨fun ⟨pa, h⟩ i => by refine i.cases' ?_ ?_ exacts [pa, h], fun h => ⟨?_, fun i => ?_⟩⟩ · simpa using h fz · simpa using h (fs i) theorem VectorAllP.imp {p q : α → Prop} (h : ∀ x, p x → q x) {v : Vector3 α n} (al : VectorAllP p v) : VectorAllP q v := (vectorAllP_iff_forall _ _).2 fun _ => h _ <| (vectorAllP_iff_forall _ _).1 al _ end Vector3
Data\Analysis\Filter.lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Order.Filter.Cofinite /-! # Computational realization of filters (experimental) This file provides infrastructure to compute with filters. ## Main declarations * `CFilter`: Realization of a filter base. Note that this is in the generality of filters on lattices, while `Filter` is filters of sets (so corresponding to `CFilter (Set α) σ`). * `Filter.Realizer`: Realization of a `Filter`. `CFilter` that generates the given filter. -/ open Set Filter -- Porting note (#11215): TODO write doc strings /-- A `CFilter α σ` is a realization of a filter (base) on `α`, represented by a type `σ` together with operations for the top element and the binary `inf` operation. -/ structure CFilter (α σ : Type*) [PartialOrder α] where f : σ → α pt : σ inf : σ → σ → σ inf_le_left : ∀ a b : σ, f (inf a b) ≤ f a inf_le_right : ∀ a b : σ, f (inf a b) ≤ f b variable {α : Type*} {β : Type*} {σ : Type*} {τ : Type*} instance [Inhabited α] [SemilatticeInf α] : Inhabited (CFilter α α) := ⟨{ f := id pt := default inf := (· ⊓ ·) inf_le_left := fun _ _ ↦ inf_le_left inf_le_right := fun _ _ ↦ inf_le_right }⟩ namespace CFilter section variable [PartialOrder α] (F : CFilter α σ) instance : CoeFun (CFilter α σ) fun _ ↦ σ → α := ⟨CFilter.f⟩ /- Porting note: Due to the CoeFun instance, the lhs of this lemma has a variable (f) as its head symbol (simpnf linter problem). Replacing it with a DFunLike instance would not be mathematically meaningful here, since the coercion to f cannot be injective, hence need to remove @[simp]. -/ -- @[simp] theorem coe_mk (f pt inf h₁ h₂ a) : (@CFilter.mk α σ _ f pt inf h₁ h₂) a = f a := rfl /-- Map a `CFilter` to an equivalent representation type. -/ def ofEquiv (E : σ ≃ τ) : CFilter α σ → CFilter α τ | ⟨f, p, g, h₁, h₂⟩ => { f := fun a ↦ f (E.symm a) pt := E p inf := fun a b ↦ E (g (E.symm a) (E.symm b)) inf_le_left := fun a b ↦ by simpa using h₁ (E.symm a) (E.symm b) inf_le_right := fun a b ↦ by simpa using h₂ (E.symm a) (E.symm b) } @[simp] theorem ofEquiv_val (E : σ ≃ τ) (F : CFilter α σ) (a : τ) : F.ofEquiv E a = F (E.symm a) := by cases F; rfl end /-- The filter represented by a `CFilter` is the collection of supersets of elements of the filter base. -/ def toFilter (F : CFilter (Set α) σ) : Filter α where sets := { a | ∃ b, F b ⊆ a } univ_sets := ⟨F.pt, subset_univ _⟩ sets_of_superset := fun ⟨b, h⟩ s ↦ ⟨b, Subset.trans h s⟩ inter_sets := fun ⟨a, h₁⟩ ⟨b, h₂⟩ ↦ ⟨F.inf a b, subset_inter (Subset.trans (F.inf_le_left _ _) h₁) (Subset.trans (F.inf_le_right _ _) h₂)⟩ @[simp] theorem mem_toFilter_sets (F : CFilter (Set α) σ) {a : Set α} : a ∈ F.toFilter ↔ ∃ b, F b ⊆ a := Iff.rfl end CFilter -- Porting note (#11215): TODO write doc strings /-- A realizer for filter `f` is a cfilter which generates `f`. -/ structure Filter.Realizer (f : Filter α) where σ : Type* F : CFilter (Set α) σ eq : F.toFilter = f /-- A `CFilter` realizes the filter it generates. -/ protected def CFilter.toRealizer (F : CFilter (Set α) σ) : F.toFilter.Realizer := ⟨σ, F, rfl⟩ namespace Filter.Realizer theorem mem_sets {f : Filter α} (F : f.Realizer) {a : Set α} : a ∈ f ↔ ∃ b, F.F b ⊆ a := by cases F; subst f; rfl /-- Transfer a realizer along an equality of filter. This has better definitional equalities than the `Eq.rec` proof. -/ def ofEq {f g : Filter α} (e : f = g) (F : f.Realizer) : g.Realizer := ⟨F.σ, F.F, F.eq.trans e⟩ /-- A filter realizes itself. -/ def ofFilter (f : Filter α) : f.Realizer := ⟨f.sets, { f := Subtype.val pt := ⟨univ, univ_mem⟩ inf := fun ⟨_, h₁⟩ ⟨_, h₂⟩ ↦ ⟨_, inter_mem h₁ h₂⟩ inf_le_left := fun ⟨x, _⟩ ⟨y, _⟩ ↦ inter_subset_left inf_le_right := fun ⟨x, _⟩ ⟨y, _⟩ ↦ inter_subset_right }, filter_eq <| Set.ext fun _ ↦ by simp [exists_mem_subset_iff]⟩ /-- Transfer a filter realizer to another realizer on a different base type. -/ def ofEquiv {f : Filter α} (F : f.Realizer) (E : F.σ ≃ τ) : f.Realizer := ⟨τ, F.F.ofEquiv E, by refine Eq.trans ?_ F.eq exact filter_eq (Set.ext fun _ ↦ ⟨fun ⟨s, h⟩ ↦ ⟨E.symm s, by simpa using h⟩, fun ⟨t, h⟩ ↦ ⟨E t, by simp [h]⟩⟩)⟩ @[simp] theorem ofEquiv_σ {f : Filter α} (F : f.Realizer) (E : F.σ ≃ τ) : (F.ofEquiv E).σ = τ := rfl @[simp] theorem ofEquiv_F {f : Filter α} (F : f.Realizer) (E : F.σ ≃ τ) (s : τ) : (F.ofEquiv E).F s = F.F (E.symm s) := rfl /-- `Unit` is a realizer for the principal filter -/ protected def principal (s : Set α) : (principal s).Realizer := ⟨Unit, { f := fun _ ↦ s pt := () inf := fun _ _ ↦ () inf_le_left := fun _ _ ↦ le_rfl inf_le_right := fun _ _ ↦ le_rfl }, filter_eq <| Set.ext fun _ ↦ ⟨fun ⟨_, s⟩ ↦ s, fun h ↦ ⟨(), h⟩⟩⟩ @[simp] theorem principal_σ (s : Set α) : (Realizer.principal s).σ = Unit := rfl @[simp] theorem principal_F (s : Set α) (u : Unit) : (Realizer.principal s).F u = s := rfl instance (s : Set α) : Inhabited (principal s).Realizer := ⟨Realizer.principal s⟩ /-- `Unit` is a realizer for the top filter -/ protected def top : (⊤ : Filter α).Realizer := (Realizer.principal _).ofEq principal_univ @[simp] theorem top_σ : (@Realizer.top α).σ = Unit := rfl @[simp] theorem top_F (u : Unit) : (@Realizer.top α).F u = univ := rfl /-- `Unit` is a realizer for the bottom filter -/ protected def bot : (⊥ : Filter α).Realizer := (Realizer.principal _).ofEq principal_empty @[simp] theorem bot_σ : (@Realizer.bot α).σ = Unit := rfl @[simp] theorem bot_F (u : Unit) : (@Realizer.bot α).F u = ∅ := rfl /-- Construct a realizer for `map m f` given a realizer for `f` -/ protected def map (m : α → β) {f : Filter α} (F : f.Realizer) : (map m f).Realizer := ⟨F.σ, { f := fun s ↦ image m (F.F s) pt := F.F.pt inf := F.F.inf inf_le_left := fun _ _ ↦ image_subset _ (F.F.inf_le_left _ _) inf_le_right := fun _ _ ↦ image_subset _ (F.F.inf_le_right _ _) }, filter_eq <| Set.ext fun _ ↦ by simp only [CFilter.toFilter, image_subset_iff, mem_setOf_eq, Filter.mem_sets, mem_map] rw [F.mem_sets]⟩ @[simp] theorem map_σ (m : α → β) {f : Filter α} (F : f.Realizer) : (F.map m).σ = F.σ := rfl @[simp] theorem map_F (m : α → β) {f : Filter α} (F : f.Realizer) (s) : (F.map m).F s = image m (F.F s) := rfl /-- Construct a realizer for `comap m f` given a realizer for `f` -/ protected def comap (m : α → β) {f : Filter β} (F : f.Realizer) : (comap m f).Realizer := ⟨F.σ, { f := fun s ↦ preimage m (F.F s) pt := F.F.pt inf := F.F.inf inf_le_left := fun _ _ ↦ preimage_mono (F.F.inf_le_left _ _) inf_le_right := fun _ _ ↦ preimage_mono (F.F.inf_le_right _ _) }, filter_eq <| Set.ext fun _ ↦ by cases F; subst f exact ⟨fun ⟨s, h⟩ ↦ ⟨_, ⟨s, Subset.refl _⟩, h⟩, fun ⟨_, ⟨s, h⟩, h₂⟩ ↦ ⟨s, Subset.trans (preimage_mono h) h₂⟩⟩⟩ /-- Construct a realizer for the sup of two filters -/ protected def sup {f g : Filter α} (F : f.Realizer) (G : g.Realizer) : (f ⊔ g).Realizer := ⟨F.σ × G.σ, { f := fun ⟨s, t⟩ ↦ F.F s ∪ G.F t pt := (F.F.pt, G.F.pt) inf := fun ⟨a, a'⟩ ⟨b, b'⟩ ↦ (F.F.inf a b, G.F.inf a' b') inf_le_left := fun _ _ ↦ union_subset_union (F.F.inf_le_left _ _) (G.F.inf_le_left _ _) inf_le_right := fun _ _ ↦ union_subset_union (F.F.inf_le_right _ _) (G.F.inf_le_right _ _) }, filter_eq <| Set.ext fun _ ↦ by cases F; cases G; substs f g; simp [CFilter.toFilter]⟩ /-- Construct a realizer for the inf of two filters -/ protected def inf {f g : Filter α} (F : f.Realizer) (G : g.Realizer) : (f ⊓ g).Realizer := ⟨F.σ × G.σ, { f := fun ⟨s, t⟩ ↦ F.F s ∩ G.F t pt := (F.F.pt, G.F.pt) inf := fun ⟨a, a'⟩ ⟨b, b'⟩ ↦ (F.F.inf a b, G.F.inf a' b') inf_le_left := fun _ _ ↦ inter_subset_inter (F.F.inf_le_left _ _) (G.F.inf_le_left _ _) inf_le_right := fun _ _ ↦ inter_subset_inter (F.F.inf_le_right _ _) (G.F.inf_le_right _ _) }, by cases F; cases G; substs f g; simp only [CFilter.toFilter, Prod.exists]; ext constructor · rintro ⟨s, t, h⟩ apply mem_inf_of_inter _ _ h · use s · use t · rintro ⟨_, ⟨a, ha⟩, _, ⟨b, hb⟩, rfl⟩ exact ⟨a, b, inter_subset_inter ha hb⟩⟩ /-- Construct a realizer for the cofinite filter -/ protected def cofinite [DecidableEq α] : (@cofinite α).Realizer := ⟨Finset α, { f := fun s ↦ { a | a ∉ s } pt := ∅ inf := (· ∪ ·) inf_le_left := fun _ _ _ ↦ mt (Finset.mem_union_left _) inf_le_right := fun _ _ _ ↦ mt (Finset.mem_union_right _) }, filter_eq <| Set.ext fun _ ↦ ⟨fun ⟨s, h⟩ ↦ s.finite_toSet.subset (compl_subset_comm.1 h), fun h ↦ ⟨h.toFinset, by simp [Subset.rfl]⟩⟩⟩ /-- Construct a realizer for filter bind -/ protected def bind {f : Filter α} {m : α → Filter β} (F : f.Realizer) (G : ∀ i, (m i).Realizer) : (f.bind m).Realizer := ⟨Σs : F.σ, ∀ i ∈ F.F s, (G i).σ, { f := fun ⟨s, f⟩ ↦ ⋃ i ∈ F.F s, (G i).F (f i (by assumption)) pt := ⟨F.F.pt, fun i _ ↦ (G i).F.pt⟩ inf := fun ⟨a, f⟩ ⟨b, f'⟩ ↦ ⟨F.F.inf a b, fun i h ↦ (G i).F.inf (f i (F.F.inf_le_left _ _ h)) (f' i (F.F.inf_le_right _ _ h))⟩ inf_le_left := fun _ _ _ ↦ by simp only [mem_iUnion, forall_exists_index] exact fun i h₁ h₂ ↦ ⟨i, F.F.inf_le_left _ _ h₁, (G i).F.inf_le_left _ _ h₂⟩ inf_le_right := fun _ _ _ ↦ by simp only [mem_iUnion, forall_exists_index] exact fun i h₁ h₂ ↦ ⟨i, F.F.inf_le_right _ _ h₁, (G i).F.inf_le_right _ _ h₂⟩ }, filter_eq <| Set.ext fun _ ↦ by cases' F with _ F _; subst f simp only [CFilter.toFilter, iUnion_subset_iff, Sigma.exists, Filter.mem_sets, mem_bind] exact ⟨fun ⟨s, f, h⟩ ↦ ⟨F s, ⟨s, Subset.refl _⟩, fun i H ↦ (G i).mem_sets.2 ⟨f i H, fun _ h' ↦ h i H h'⟩⟩, fun ⟨_, ⟨s, h⟩, f⟩ ↦ let ⟨f', h'⟩ := Classical.axiom_of_choice fun i : F s ↦ (G i).mem_sets.1 (f i (h i.2)) ⟨s, fun i h ↦ f' ⟨i, h⟩, fun _ H _ m ↦ h' ⟨_, H⟩ m⟩⟩⟩ /-- Construct a realizer for indexed supremum -/ protected def iSup {f : α → Filter β} (F : ∀ i, (f i).Realizer) : (⨆ i, f i).Realizer := let F' : (⨆ i, f i).Realizer := (Realizer.bind Realizer.top F).ofEq <| filter_eq <| Set.ext <| by simp [Filter.bind, eq_univ_iff_forall, iSup_sets_eq] F'.ofEquiv <| show (Σ_ : Unit, ∀ i : α, True → (F i).σ) ≃ ∀ i, (F i).σ from ⟨fun ⟨_, f⟩ i ↦ f i ⟨⟩, fun f ↦ ⟨(), fun i _ ↦ f i⟩, fun _ ↦ rfl, fun _ ↦ rfl⟩ /-- Construct a realizer for the product of filters -/ protected def prod {f g : Filter α} (F : f.Realizer) (G : g.Realizer) : (f.prod g).Realizer := (F.comap _).inf (G.comap _) theorem le_iff {f g : Filter α} (F : f.Realizer) (G : g.Realizer) : f ≤ g ↔ ∀ b : G.σ, ∃ a : F.σ, F.F a ≤ G.F b := ⟨fun H t ↦ F.mem_sets.1 (H (G.mem_sets.2 ⟨t, Subset.refl _⟩)), fun H _ h ↦ F.mem_sets.2 <| let ⟨s, h₁⟩ := G.mem_sets.1 h let ⟨t, h₂⟩ := H s ⟨t, Subset.trans h₂ h₁⟩⟩ theorem tendsto_iff (f : α → β) {l₁ : Filter α} {l₂ : Filter β} (L₁ : l₁.Realizer) (L₂ : l₂.Realizer) : Tendsto f l₁ l₂ ↔ ∀ b, ∃ a, ∀ x ∈ L₁.F a, f x ∈ L₂.F b := (le_iff (L₁.map f) L₂).trans <| forall_congr' fun _ ↦ exists_congr fun _ ↦ image_subset_iff theorem ne_bot_iff {f : Filter α} (F : f.Realizer) : f ≠ ⊥ ↔ ∀ a : F.σ, (F.F a).Nonempty := by rw [not_iff_comm, ← le_bot_iff, F.le_iff Realizer.bot, not_forall] simp only [Set.not_nonempty_iff_eq_empty] exact ⟨fun ⟨x, e⟩ _ ↦ ⟨x, le_of_eq e⟩, fun h ↦ let ⟨x, h⟩ := h () ⟨x, le_bot_iff.1 h⟩⟩ end Filter.Realizer
Data\Analysis\Topology.lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Data.Analysis.Filter import Mathlib.Topology.Bases import Mathlib.Topology.LocallyFinite /-! # Computational realization of topological spaces (experimental) This file provides infrastructure to compute with topological spaces. ## Main declarations * `Ctop`: Realization of a topology basis. * `Ctop.Realizer`: Realization of a topological space. `Ctop` that generates the given topology. * `LocallyFinite.Realizer`: Realization of the local finiteness of an indexed family of sets. * `Compact.Realizer`: Realization of the compactness of a set. -/ open Set open Filter hiding Realizer open Topology /-- A `Ctop α σ` is a realization of a topology (basis) on `α`, represented by a type `σ` together with operations for the top element and the intersection operation. -/ structure Ctop (α σ : Type*) where f : σ → Set α top : α → σ top_mem : ∀ x : α, x ∈ f (top x) inter : ∀ (a b) (x : α), x ∈ f a ∩ f b → σ inter_mem : ∀ a b x h, x ∈ f (inter a b x h) inter_sub : ∀ a b x h, f (inter a b x h) ⊆ f a ∩ f b variable {α : Type*} {β : Type*} {σ : Type*} {τ : Type*} instance : Inhabited (Ctop α (Set α)) := ⟨{ f := id top := singleton top_mem := mem_singleton inter := fun s t _ _ ↦ s ∩ t inter_mem := fun _s _t _a ↦ id inter_sub := fun _s _t _a _ha ↦ Subset.rfl }⟩ namespace Ctop section variable (F : Ctop α σ) instance : CoeFun (Ctop α σ) fun _ ↦ σ → Set α := ⟨Ctop.f⟩ -- @[simp] -- Porting note (#10685): dsimp can prove this theorem coe_mk (f T h₁ I h₂ h₃ a) : (@Ctop.mk α σ f T h₁ I h₂ h₃) a = f a := rfl /-- Map a Ctop to an equivalent representation type. -/ def ofEquiv (E : σ ≃ τ) : Ctop α σ → Ctop α τ | ⟨f, T, h₁, I, h₂, h₃⟩ => { f := fun a ↦ f (E.symm a) top := fun x ↦ E (T x) top_mem := fun x ↦ by simpa using h₁ x inter := fun a b x h ↦ E (I (E.symm a) (E.symm b) x h) inter_mem := fun a b x h ↦ by simpa using h₂ (E.symm a) (E.symm b) x h inter_sub := fun a b x h ↦ by simpa using h₃ (E.symm a) (E.symm b) x h } @[simp] theorem ofEquiv_val (E : σ ≃ τ) (F : Ctop α σ) (a : τ) : F.ofEquiv E a = F (E.symm a) := by cases F; rfl end /-- Every `Ctop` is a topological space. -/ def toTopsp (F : Ctop α σ) : TopologicalSpace α := TopologicalSpace.generateFrom (Set.range F.f) theorem toTopsp_isTopologicalBasis (F : Ctop α σ) : @TopologicalSpace.IsTopologicalBasis _ F.toTopsp (Set.range F.f) := letI := F.toTopsp ⟨fun _u ⟨a, e₁⟩ _v ⟨b, e₂⟩ ↦ e₁ ▸ e₂ ▸ fun x h ↦ ⟨_, ⟨_, rfl⟩, F.inter_mem a b x h, F.inter_sub a b x h⟩, eq_univ_iff_forall.2 fun x ↦ ⟨_, ⟨_, rfl⟩, F.top_mem x⟩, rfl⟩ @[simp] theorem mem_nhds_toTopsp (F : Ctop α σ) {s : Set α} {a : α} : s ∈ @nhds _ F.toTopsp a ↔ ∃ b, a ∈ F b ∧ F b ⊆ s := (@TopologicalSpace.IsTopologicalBasis.mem_nhds_iff _ F.toTopsp _ _ _ F.toTopsp_isTopologicalBasis).trans <| ⟨fun ⟨_, ⟨x, rfl⟩, h⟩ ↦ ⟨x, h⟩, fun ⟨x, h⟩ ↦ ⟨_, ⟨x, rfl⟩, h⟩⟩ end Ctop /-- A `Ctop` realizer for the topological space `T` is a `Ctop` which generates `T`. -/ structure Ctop.Realizer (α) [T : TopologicalSpace α] where σ : Type* F : Ctop α σ eq : F.toTopsp = T open Ctop /-- A `Ctop` realizes the topological space it generates. -/ protected def Ctop.toRealizer (F : Ctop α σ) : @Ctop.Realizer _ F.toTopsp := @Ctop.Realizer.mk _ F.toTopsp σ F rfl instance (F : Ctop α σ) : Inhabited (@Ctop.Realizer _ F.toTopsp) := ⟨F.toRealizer⟩ namespace Ctop.Realizer protected theorem is_basis [T : TopologicalSpace α] (F : Realizer α) : TopologicalSpace.IsTopologicalBasis (Set.range F.F.f) := by have := toTopsp_isTopologicalBasis F.F; rwa [F.eq] at this protected theorem mem_nhds [T : TopologicalSpace α] (F : Realizer α) {s : Set α} {a : α} : s ∈ 𝓝 a ↔ ∃ b, a ∈ F.F b ∧ F.F b ⊆ s := by have := @mem_nhds_toTopsp _ _ F.F s a; rwa [F.eq] at this theorem isOpen_iff [TopologicalSpace α] (F : Realizer α) {s : Set α} : IsOpen s ↔ ∀ a ∈ s, ∃ b, a ∈ F.F b ∧ F.F b ⊆ s := isOpen_iff_mem_nhds.trans <| forall₂_congr fun _a _h ↦ F.mem_nhds theorem isClosed_iff [TopologicalSpace α] (F : Realizer α) {s : Set α} : IsClosed s ↔ ∀ a, (∀ b, a ∈ F.F b → ∃ z, z ∈ F.F b ∩ s) → a ∈ s := isOpen_compl_iff.symm.trans <| F.isOpen_iff.trans <| forall_congr' fun a ↦ show (a ∉ s → ∃ b : F.σ, a ∈ F.F b ∧ ∀ z ∈ F.F b, z ∉ s) ↔ _ by haveI := Classical.propDecidable; rw [not_imp_comm] simp [not_exists, not_and, not_forall, and_comm] theorem mem_interior_iff [TopologicalSpace α] (F : Realizer α) {s : Set α} {a : α} : a ∈ interior s ↔ ∃ b, a ∈ F.F b ∧ F.F b ⊆ s := mem_interior_iff_mem_nhds.trans F.mem_nhds protected theorem isOpen [TopologicalSpace α] (F : Realizer α) (s : F.σ) : IsOpen (F.F s) := isOpen_iff_nhds.2 fun a m ↦ by simpa using F.mem_nhds.2 ⟨s, m, Subset.refl _⟩ theorem ext' [T : TopologicalSpace α] {σ : Type*} {F : Ctop α σ} (H : ∀ a s, s ∈ 𝓝 a ↔ ∃ b, a ∈ F b ∧ F b ⊆ s) : F.toTopsp = T := by refine TopologicalSpace.ext_nhds fun x ↦ ?_ ext s rw [mem_nhds_toTopsp, H] theorem ext [T : TopologicalSpace α] {σ : Type*} {F : Ctop α σ} (H₁ : ∀ a, IsOpen (F a)) (H₂ : ∀ a s, s ∈ 𝓝 a → ∃ b, a ∈ F b ∧ F b ⊆ s) : F.toTopsp = T := ext' fun a s ↦ ⟨H₂ a s, fun ⟨_b, h₁, h₂⟩ ↦ mem_nhds_iff.2 ⟨_, h₂, H₁ _, h₁⟩⟩ variable [TopologicalSpace α] /-- The topological space realizer made of the open sets. -/ protected def id : Realizer α := ⟨{ x : Set α // IsOpen x }, { f := Subtype.val top := fun _ ↦ ⟨univ, isOpen_univ⟩ top_mem := mem_univ inter := fun ⟨_x, h₁⟩ ⟨_y, h₂⟩ _a _h₃ ↦ ⟨_, h₁.inter h₂⟩ inter_mem := fun ⟨_x, _h₁⟩ ⟨_y, _h₂⟩ _a ↦ id inter_sub := fun ⟨_x, _h₁⟩ ⟨_y, _h₂⟩ _a _h₃ ↦ Subset.refl _ }, ext Subtype.property fun _x _s h ↦ let ⟨t, h, o, m⟩ := mem_nhds_iff.1 h ⟨⟨t, o⟩, m, h⟩⟩ /-- Replace the representation type of a `Ctop` realizer. -/ def ofEquiv (F : Realizer α) (E : F.σ ≃ τ) : Realizer α := ⟨τ, F.F.ofEquiv E, ext' fun a s ↦ F.mem_nhds.trans <| ⟨fun ⟨s, h⟩ ↦ ⟨E s, by simpa using h⟩, fun ⟨t, h⟩ ↦ ⟨E.symm t, by simpa using h⟩⟩⟩ @[simp] theorem ofEquiv_σ (F : Realizer α) (E : F.σ ≃ τ) : (F.ofEquiv E).σ = τ := rfl @[simp] theorem ofEquiv_F (F : Realizer α) (E : F.σ ≃ τ) (s : τ) : (F.ofEquiv E).F s = F.F (E.symm s) := by delta ofEquiv; simp /-- A realizer of the neighborhood of a point. -/ protected def nhds (F : Realizer α) (a : α) : (𝓝 a).Realizer := ⟨{ s : F.σ // a ∈ F.F s }, { f := fun s ↦ F.F s.1 pt := ⟨_, F.F.top_mem a⟩ inf := fun ⟨x, h₁⟩ ⟨y, h₂⟩ ↦ ⟨_, F.F.inter_mem x y a ⟨h₁, h₂⟩⟩ inf_le_left := fun ⟨x, h₁⟩ ⟨y, h₂⟩ _z h ↦ (F.F.inter_sub x y a ⟨h₁, h₂⟩ h).1 inf_le_right := fun ⟨x, h₁⟩ ⟨y, h₂⟩ _z h ↦ (F.F.inter_sub x y a ⟨h₁, h₂⟩ h).2 }, filter_eq <| Set.ext fun _x ↦ ⟨fun ⟨⟨_s, as⟩, h⟩ ↦ mem_nhds_iff.2 ⟨_, h, F.isOpen _, as⟩, fun h ↦ let ⟨s, h, as⟩ := F.mem_nhds.1 h ⟨⟨s, h⟩, as⟩⟩⟩ @[simp] theorem nhds_σ (F : Realizer α) (a : α) : (F.nhds a).σ = { s : F.σ // a ∈ F.F s } := rfl @[simp] theorem nhds_F (F : Realizer α) (a : α) (s) : (F.nhds a).F s = F.F s.1 := rfl theorem tendsto_nhds_iff {m : β → α} {f : Filter β} (F : f.Realizer) (R : Realizer α) {a : α} : Tendsto m f (𝓝 a) ↔ ∀ t, a ∈ R.F t → ∃ s, ∀ x ∈ F.F s, m x ∈ R.F t := (F.tendsto_iff _ (R.nhds a)).trans Subtype.forall end Ctop.Realizer /-- A `LocallyFinite.Realizer F f` is a realization that `f` is locally finite, namely it is a choice of open sets from the basis of `F` such that they intersect only finitely many of the values of `f`. -/ structure LocallyFinite.Realizer [TopologicalSpace α] (F : Ctop.Realizer α) (f : β → Set α) where bas : ∀ a, { s // a ∈ F.F s } sets : ∀ x : α, Fintype { i | (f i ∩ F.F (bas x)).Nonempty } theorem LocallyFinite.Realizer.to_locallyFinite [TopologicalSpace α] {F : Ctop.Realizer α} {f : β → Set α} (R : LocallyFinite.Realizer F f) : LocallyFinite f := fun a ↦ ⟨_, F.mem_nhds.2 ⟨(R.bas a).1, (R.bas a).2, Subset.rfl⟩, have := R.sets a; Set.toFinite _⟩ theorem locallyFinite_iff_exists_realizer [TopologicalSpace α] (F : Ctop.Realizer α) {f : β → Set α} : LocallyFinite f ↔ Nonempty (LocallyFinite.Realizer F f) := ⟨fun h ↦ let ⟨g, h₁⟩ := Classical.axiom_of_choice h let ⟨g₂, h₂⟩ := Classical.axiom_of_choice fun x ↦ show ∃ b : F.σ, x ∈ F.F b ∧ F.F b ⊆ g x from let ⟨h, _h'⟩ := h₁ x F.mem_nhds.1 h ⟨⟨fun x ↦ ⟨g₂ x, (h₂ x).1⟩, fun x ↦ Finite.fintype <| let ⟨_h, h'⟩ := h₁ x h'.subset fun _i hi ↦ hi.mono (inter_subset_inter_right _ (h₂ x).2)⟩⟩, fun ⟨R⟩ ↦ R.to_locallyFinite⟩ instance [TopologicalSpace α] [Finite β] (F : Ctop.Realizer α) (f : β → Set α) : Nonempty (LocallyFinite.Realizer F f) := (locallyFinite_iff_exists_realizer _).1 <| locallyFinite_of_finite _ /-- A `Compact.Realizer s` is a realization that `s` is compact, namely it is a choice of finite open covers for each set family covering `s`. -/ def Compact.Realizer [TopologicalSpace α] (s : Set α) := ∀ {f : Filter α} (F : f.Realizer) (x : F.σ), f ≠ ⊥ → F.F x ⊆ s → { a // a ∈ s ∧ 𝓝 a ⊓ f ≠ ⊥ } instance [TopologicalSpace α] : Inhabited (Compact.Realizer (∅ : Set α)) := ⟨fun {f} F x h hF ↦ by suffices f = ⊥ from absurd this h rw [← F.eq, eq_bot_iff] exact fun s _ ↦ ⟨x, hF.trans s.empty_subset⟩⟩
Data\Array\Defs.lean
/- Copyright (c) 2021 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Arthur Paulino, Floris van Doorn -/ /-! ## Definitions on Arrays This file contains various definitions on `Array`. It does not contain proofs about these definitions, those are contained in other files in `Mathlib.Data.Array`. -/ namespace Array universe u variable {α : Type u} /-- Permute the array using a sequence of indices defining a cyclic permutation. If the list of indices `l = [i₁, i₂, ..., iₙ]` are all distinct then `(cyclicPermute! a l)[iₖ₊₁] = a[iₖ]` and `(cyclicPermute! a l)[i₀] = a[iₙ]` -/ def cyclicPermute! [Inhabited α] : Array α → List Nat → Array α | a, [] => a | a, i :: is => cyclicPermuteAux a is a[i]! i where cyclicPermuteAux : Array α → List Nat → α → Nat → Array α | a, [], x, i0 => a.set! i0 x | a, i :: is, x, i0 => let (y, a) := a.swapAt! i x cyclicPermuteAux a is y i0 /-- Permute the array using a list of cycles. -/ def permute! [Inhabited α] (a : Array α) (ls : List (List Nat)) : Array α := ls.foldl (init := a) (·.cyclicPermute! ·)
Data\Array\ExtractLemmas.lean
/- Copyright (c) 2024 Jiecheng Zhao. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jiecheng Zhao -/ /-! # Lemmas about `Array.extract` Some useful lemmas about Array.extract -/ universe u variable {α : Type u} {i : Nat} namespace Array @[simp] theorem extract_eq_nil_of_start_eq_end {a : Array α} : a.extract i i = #[] := by refine extract_empty_of_stop_le_start a ?h exact Nat.le_refl i theorem extract_append_left {a b : Array α} {i j : Nat} (h : j ≤ a.size) : (a ++ b).extract i j = a.extract i j := by apply ext · simp only [size_extract, size_append] omega · intro h1 h2 h3 rw [get_extract, get_append_left, get_extract] theorem extract_append_right {a b : Array α} {i j : Nat} (h : a.size ≤ i) : (a ++ b).extract i j = b.extract (i - a.size) (j - a.size) := by apply ext · rw [size_extract, size_extract, size_append] omega · intro k hi h2 rw [get_extract, get_extract, get_append_right (show size a ≤ i + k by omega)] congr omega theorem extract_eq_of_size_le_end {l p : Nat} {a : Array α} (h : a.size ≤ l) : a.extract p l = a.extract p a.size := by simp only [extract, Nat.min_eq_right h, Nat.sub_eq, mkEmpty_eq, Nat.min_self] theorem extract_extract {s1 e2 e1 s2 : Nat} {a : Array α} (h : s1 + e2 ≤ e1) : (a.extract s1 e1).extract s2 e2 = a.extract (s1 + s2) (s1 + e2) := by apply ext · simp only [size_extract] omega · intro i h1 h2 simp only [get_extract, Nat.add_assoc] end Array
Data\Array\Lemmas.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, Mario Carneiro -/ import Mathlib.Algebra.Group.Fin.Basic import Mathlib.Data.List.Basic /-! Porting note: Following the discussion on [Zulip](https://leanprover.zulipchat.com/#narrow/stream/287929- mathlib4/topic/porting.20.60.2Earray.60.20files.20whose.20PR's.20were.20closed.3F), these will wait until Batteries has finalized `DArray` and `Array'` types so we can translates apples to apples. `align` for lemmas about lean3/mathlib3 versions of d_array and array with mathport output -/ universe u v w namespace DArray -- variable {n : ℕ} {α : Fin n → Type u} -- instance [∀ i, Inhabited (α i)] : Inhabited (DArray n α) := -- ⟨⟨default⟩⟩ end DArray namespace Array' -- instance {n α} [Inhabited α] : Inhabited (Array' n α) := -- DArray.inhabited -- theorem toList_of_hEq {n₁ n₂ α} {a₁ : Array' n₁ α} {a₂ : Array' n₂ α} (hn : n₁ = n₂) -- (ha : HEq a₁ a₂) : a₁.toList = a₂.toList := by congr <;> assumption -- rev_list section RevList -- variable {n : ℕ} {α : Type u} {a : Array' n α} -- theorem rev_list_reverse_aux : -- ∀ (i) (h : i ≤ n) (t : List α), -- (a.iterateAux (fun _ => (· :: ·)) i h []).reverseAux t = -- a.revIterateAux (fun _ => (· :: ·)) i h t -- | 0, h, t => rfl -- | i + 1, h, t => rev_list_reverse_aux i _ _ -- @[simp] -- theorem revList_reverse : a.revList.reverse = a.toList := -- rev_list_reverse_aux _ _ _ -- @[simp] -- theorem toList_reverse : a.toList.reverse = a.revList := by -- rw [← rev_list_reverse, List.reverse_reverse] end RevList -- mem section Mem -- variable {n : ℕ} {α : Type u} {v : α} {a : Array' n α} -- theorem Mem.def : v ∈ a ↔ ∃ i, a.read i = v := -- Iff.rfl -- theorem mem_rev_list_aux : -- ∀ {i} (h : i ≤ n), -- (∃ j : Fin n, (j : ℕ) < i ∧ read a j = v) ↔ v ∈ a.iterateAux (fun _ => (· :: ·)) i h [] -- | 0, _ => ⟨fun ⟨i, n, _⟩ => absurd n i.val.not_lt_zero, False.elim⟩ -- | i + 1, h => -- let IH := mem_rev_list_aux (le_of_lt h) -- ⟨fun ⟨j, ji1, e⟩ => -- Or.elim (lt_or_eq_of_le <| Nat.le_of_succ_le_succ ji1) -- (fun ji => List.mem_cons_of_mem _ <| IH.1 ⟨j, ji, e⟩) fun je => by -- simp [DArray.iterateAux] <;> apply Or.inl <;> unfold read at e <;> -- have H : j = ⟨i, h⟩ := Fin.eq_of_veq je <;> -- rwa [← H, e], -- fun m => by -- simp [DArray.iterateAux, List.Mem] at m -- cases' m with e m' -- exact ⟨⟨i, h⟩, Nat.lt_succ_self _, Eq.symm e⟩ -- exact -- let ⟨j, ji, e⟩ := IH.2 m' -- ⟨j, Nat.le_succ_of_le ji, e⟩⟩ -- @[simp] -- theorem mem_revList : v ∈ a.revList ↔ v ∈ a := -- Iff.symm <| -- Iff.trans -- (exists_congr fun j => -- Iff.symm <| show j.1 < n ∧ read a j = v ↔ read a j = v from and_iff_right j.2) -- (mem_rev_list_aux _) -- @[simp] -- theorem mem_toList : v ∈ a.toList ↔ v ∈ a := by -- rw [← rev_list_reverse] <;> exact list.mem_reverse.trans mem_rev_list end Mem -- foldr section Foldr -- variable {n : ℕ} {α : Type u} {β : Type w} {b : β} {f : α → β → β} {a : Array' n α} -- theorem rev_list_foldr_aux : -- ∀ {i} (h : i ≤ n), -- (DArray.iterateAux a (fun _ => (· :: ·)) i h []).foldr f b = -- DArray.iterateAux a (fun _ => f) i h b -- | 0, h => rfl -- | j + 1, h => congr_arg (f (read a ⟨j, h⟩)) (rev_list_foldr_aux _) -- theorem revList_foldr : a.revList.foldr f b = a.foldl b f := -- rev_list_foldr_aux _ end Foldr -- foldl section Foldl -- variable {n : ℕ} {α : Type u} {β : Type w} {b : β} {f : β → α → β} {a : Array' n α} -- theorem toList_foldl : a.toList.foldl f b = a.foldl b (Function.swap f) := by -- rw [← rev_list_reverse, List.foldl_reverse, rev_list_foldr] end Foldl -- length section Length -- variable {n : ℕ} {α : Type u} -- theorem rev_list_length_aux (a : Array' n α) (i h) : -- (a.iterateAux (fun _ => (· :: ·)) i h []).length = i := by -- induction i <;> simp [*, DArray.iterateAux] -- @[simp] -- theorem revList_length (a : Array' n α) : a.revList.length = n := -- rev_list_length_aux a _ _ -- @[simp] -- theorem toList_length (a : Array' n α) : a.toList.length = n := by -- rw [← rev_list_reverse, List.length_reverse, rev_list_length] end Length -- nth section Nth -- variable {n : ℕ} {α : Type u} {a : Array' n α} -- theorem to_list_nthLe_aux (i : ℕ) (ih : i < n) : -- ∀ (j) {jh t h'}, -- (∀ k tl, j + k = i → List.nthLe t k tl = a.read ⟨i, ih⟩) → -- (a.revIterateAux (fun _ => (· :: ·)) j jh t).nthLe i h' = a.read ⟨i, ih⟩ -- | 0, _, _, _, al => al i _ <| zero_add _ -- | j + 1, jh, t, h', al => -- to_list_nth_le_aux j fun k tl hjk => -- show List.nthLe (a.read ⟨j, jh⟩ :: t) k tl = a.read ⟨i, ih⟩ from -- match k, hjk, tl with -- | 0, e, tl => -- match i, e, ih with -- | _, rfl, _ => rfl -- | k' + 1, _, tl => by -- simp [List.nthLe] <;> exact al _ _ (by simp [add_comm, add_assoc, *] <;> cc) -- theorem toList_nthLe (i : ℕ) (h h') : List.nthLe a.toList i h' = a.read ⟨i, h⟩ := -- to_list_nthLe_aux _ _ _ fun k tl => absurd tl k.not_lt_zero -- @[simp] -- theorem toList_nth_le' (a : Array' n α) (i : Fin n) (h') : List.nthLe a.toList i h' -- = a.read i := by -- cases i <;> apply to_list_nth_le -- theorem toList_get? {i v} : List.get? a.toList i = some v ↔ ∃ h, a.read ⟨i, h⟩ = v := by -- rw [List.get?_eq_some'] -- have ll := to_list_length a -- constructor <;> intro h <;> cases' h with h e <;> subst v -- · exact ⟨ll ▸ h, (to_list_nth_le _ _ _).symm⟩ -- · exact ⟨ll.symm ▸ h, to_list_nth_le _ _ _⟩ -- theorem write_toList {i v} : (a.write i v).toList = a.toList.set i v := -- List.ext_nthLe (by simp) fun j h₁ h₂ => by -- have h₃ : j < n := by simpa using h₁ -- rw [to_list_nth_le _ h₃] -- refine' -- let ⟨_, e⟩ := List.get?_eq_some'.1 _ -- e.symm -- by_cases ij : (i : ℕ) = j -- · subst j -- rw [show (⟨(i : ℕ), h₃⟩ : Fin _) = i from Fin.eq_of_veq rfl, Array'.read_write, -- List.get?_set_eq_of_lt] -- simp [h₃] -- · rw [List.get?_set_ne _ _ ij, a.read_write_of_ne, to_list_nth.2 ⟨h₃, rfl⟩] -- exact Fin.ne_of_vne ij end Nth -- enum section Enum -- variable {n : ℕ} {α : Type u} {a : Array' n α} -- theorem mem_toList_enum {i v} : (i, v) ∈ a.toList.enum ↔ ∃ h, a.read ⟨i, h⟩ = v := by -- simp [List.mem_iff_get?, to_list_nth, and_comm, and_assoc, and_left_comm] end Enum -- to_array section ToArray -- variable {n : ℕ} {α : Type u} -- @[simp] -- theorem toList_toArray (a : Array' n α) : HEq a.toList.toArray a := -- hEq_of_hEq_of_eq -- (@Eq.drecOn -- (fun m (e : a.toList.length = m) => -- HEq (DArray.mk fun v => a.toList.nthLe v.1 v.2) -- (@DArray.mk m (fun _ => α) fun v => a.toList.nthLe v.1 <| e.symm ▸ v.2)) -- a.toList_length HEq.rfl) <| -- DArray.ext fun ⟨i, h⟩ => toList_nthLe i h _ -- @[simp] -- theorem toArray_toList (l : List α) : l.toArray.toList = l := -- List.ext_nthLe (toList_length _) fun n h1 h2 => toList_nthLe _ h2 _ end ToArray -- push_back section PushBack -- variable {n : ℕ} {α : Type u} {v : α} {a : Array' n α} -- theorem pushBack_rev_list_aux : -- ∀ i h h', -- DArray.iterateAux (a.pushBack v) (fun _ => (· :: ·)) i h [] = -- DArray.iterateAux a (fun _ => (· :: ·)) i h' [] -- | 0, h, h' => rfl -- | i + 1, h, h' => by -- simp [DArray.iterateAux] -- refine' ⟨_, push_back_rev_list_aux _ _ _⟩ -- dsimp [read, DArray.read, push_back] -- rw [dif_neg]; rfl -- exact ne_of_lt h' -- @[simp] -- theorem pushBack_revList : (a.pushBack v).revList = v :: a.revList := by -- unfold push_back rev_list foldl iterate DArray.iterate -- dsimp [DArray.iterateAux, read, DArray.read, push_back] -- rw [dif_pos (Eq.refl n)] -- apply congr_arg -- apply push_back_rev_list_aux -- @[simp] -- theorem pushBack_toList : (a.pushBack v).toList = a.toList ++ [v] := by -- rw [← rev_list_reverse, ← rev_list_reverse, push_back_rev_list, List.reverse_cons] -- @[simp] -- theorem read_pushBack_left (i : Fin n) : (a.pushBack v).read i.cast_succ = a.read i := by -- cases' i with i hi -- have : ¬i = n := ne_of_lt hi -- simp [push_back, this, Fin.castSucc, Fin.castAdd, Fin.castLe, Fin.castLt, read, DArray.read] -- @[simp] -- theorem read_pushBack_right : (a.pushBack v).read (Fin.last _) = v := by -- cases' hn : Fin.last n with k hk -- have : k = n := by simpa [Fin.ext_iff] using hn.symm -- simp [push_back, this, Fin.castSucc, Fin.castAdd, Fin.castLe, Fin.castLt, read, DArray.read] end PushBack -- foreach section Foreach -- variable {n : ℕ} {α : Type u} {β : Type v} {i : Fin n} {f : Fin n → α → β} {a : Array' n α} -- -- @[simp] -- theorem read_foreach : (foreach a f).read i = f i (a.read i) := -- rfl end Foreach -- map section Map -- variable {n : ℕ} {α : Type u} {β : Type v} {i : Fin n} {f : α → β} {a : Array' n α} -- -- theorem read_map : (a.map f).read i = f (a.read i) := -- read_foreach end Map -- map₂ section Map₂ -- variable {n : ℕ} {α : Type u} {i : Fin n} {f : α → α → α} {a₁ a₂ : Array' n α} -- -- @[simp] -- theorem read_map₂ : (map₂ f a₁ a₂).read i = f (a₁.read i) (a₂.read i) := -- read_foreach end Map₂ end Array'
Data\Bool\AllAny.lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Data.List.Basic /-! # Boolean quantifiers This proves a few properties about `List.all` and `List.any`, which are the `Bool` universal and existential quantifiers. Their definitions are in core Lean. -/ variable {α : Type*} {p : α → Prop} [DecidablePred p] {l : List α} {a : α} namespace List -- Porting note: in Batteries theorem all_iff_forall {p : α → Bool} : all l p ↔ ∀ a ∈ l, p a := by induction' l with a l ih · exact iff_of_true rfl (forall_mem_nil _) simp only [all_cons, Bool.and_eq_true_iff, ih, forall_mem_cons] theorem all_iff_forall_prop : (all l fun a => p a) ↔ ∀ a ∈ l, p a := by simp only [all_iff_forall, decide_eq_true_iff] -- Porting note: in Batteries theorem any_iff_exists {p : α → Bool} : any l p ↔ ∃ a ∈ l, p a := by induction' l with a l ih · exact iff_of_false Bool.false_ne_true (not_exists_mem_nil _) simp only [any_cons, Bool.or_eq_true_iff, ih, exists_mem_cons_iff] theorem any_iff_exists_prop : (any l fun a => p a) ↔ ∃ a ∈ l, p a := by simp [any_iff_exists] theorem any_of_mem {p : α → Bool} (h₁ : a ∈ l) (h₂ : p a) : any l p := any_iff_exists.2 ⟨_, h₁, h₂⟩ end List
Data\Bool\Basic.lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad -/ import Mathlib.Logic.Function.Defs import Mathlib.Order.Defs /-! # Booleans This file proves various trivial lemmas about booleans and their relation to decidable propositions. ## Tags bool, boolean, Bool, De Morgan -/ namespace Bool section /-! This section contains lemmas about booleans which were present in core Lean 3. The remainder of this file contains lemmas about booleans from mathlib 3. -/ theorem true_eq_false_eq_False : ¬true = false := by decide theorem false_eq_true_eq_False : ¬false = true := by decide theorem eq_false_eq_not_eq_true (b : Bool) : (¬b = true) = (b = false) := by simp theorem eq_true_eq_not_eq_false (b : Bool) : (¬b = false) = (b = true) := by simp theorem eq_false_of_not_eq_true {b : Bool} : ¬b = true → b = false := Eq.mp (eq_false_eq_not_eq_true b) theorem eq_true_of_not_eq_false {b : Bool} : ¬b = false → b = true := Eq.mp (eq_true_eq_not_eq_false b) theorem and_eq_true_eq_eq_true_and_eq_true (a b : Bool) : ((a && b) = true) = (a = true ∧ b = true) := by simp theorem or_eq_true_eq_eq_true_or_eq_true (a b : Bool) : ((a || b) = true) = (a = true ∨ b = true) := by simp theorem not_eq_true_eq_eq_false (a : Bool) : (not a = true) = (a = false) := by cases a <;> simp #adaptation_note /-- this is no longer a simp lemma, as after nightly-2024-03-05 the LHS simplifies. -/ theorem and_eq_false_eq_eq_false_or_eq_false (a b : Bool) : ((a && b) = false) = (a = false ∨ b = false) := by cases a <;> cases b <;> simp theorem or_eq_false_eq_eq_false_and_eq_false (a b : Bool) : ((a || b) = false) = (a = false ∧ b = false) := by cases a <;> cases b <;> simp theorem not_eq_false_eq_eq_true (a : Bool) : (not a = false) = (a = true) := by cases a <;> simp theorem coe_false : ↑false = False := by simp theorem coe_true : ↑true = True := by simp theorem coe_sort_false : (false : Prop) = False := by simp theorem coe_sort_true : (true : Prop) = True := by simp theorem decide_iff (p : Prop) [d : Decidable p] : decide p = true ↔ p := by simp theorem decide_true {p : Prop} [Decidable p] : p → decide p := (decide_iff p).2 theorem of_decide_true {p : Prop} [Decidable p] : decide p → p := (decide_iff p).1 theorem bool_iff_false {b : Bool} : ¬b ↔ b = false := by cases b <;> decide theorem bool_eq_false {b : Bool} : ¬b → b = false := bool_iff_false.1 theorem decide_false_iff (p : Prop) {_ : Decidable p} : decide p = false ↔ ¬p := bool_iff_false.symm.trans (not_congr (decide_iff _)) theorem decide_false {p : Prop} [Decidable p] : ¬p → decide p = false := (decide_false_iff p).2 theorem of_decide_false {p : Prop} [Decidable p] : decide p = false → ¬p := (decide_false_iff p).1 theorem decide_congr {p q : Prop} [Decidable p] [Decidable q] (h : p ↔ q) : decide p = decide q := decide_eq_decide.mpr h @[deprecated (since := "2024-06-07")] alias coe_or_iff := or_eq_true_iff @[deprecated (since := "2024-06-07")] alias coe_and_iff := and_eq_true_iff theorem coe_xor_iff (a b : Bool) : xor a b ↔ Xor' (a = true) (b = true) := by cases a <;> cases b <;> decide end @[deprecated (since := "2024-06-07")] alias decide_True := decide_true_eq_true @[deprecated (since := "2024-06-07")] alias decide_False := decide_false_eq_false @[deprecated (since := "2024-06-07")] alias coe_decide := decide_eq_true_iff @[deprecated decide_eq_true_iff (since := "2024-06-07")] alias of_decide_iff := decide_eq_true_iff @[deprecated (since := "2024-06-07")] alias decide_not := decide_not @[deprecated (since := "2024-06-07")] alias not_false' := false_ne_true @[deprecated (since := "2024-06-07")] alias eq_iff_eq_true_iff := eq_iff_iff theorem dichotomy (b : Bool) : b = false ∨ b = true := by cases b <;> simp theorem forall_bool' {p : Bool → Prop} (b : Bool) : (∀ x, p x) ↔ p b ∧ p !b := ⟨fun h ↦ ⟨h _, h _⟩, fun ⟨h₁, h₂⟩ x ↦ by cases b <;> cases x <;> assumption⟩ @[simp] theorem forall_bool {p : Bool → Prop} : (∀ b, p b) ↔ p false ∧ p true := forall_bool' false theorem exists_bool' {p : Bool → Prop} (b : Bool) : (∃ x, p x) ↔ p b ∨ p !b := ⟨fun ⟨x, hx⟩ ↦ by cases x <;> cases b <;> first | exact .inl ‹_› | exact .inr ‹_›, fun h ↦ by cases h <;> exact ⟨_, ‹_›⟩⟩ @[simp] theorem exists_bool {p : Bool → Prop} : (∃ b, p b) ↔ p false ∨ p true := exists_bool' false theorem not_ne_id : not ≠ id := fun h ↦ false_ne_true <| congrFun h true @[deprecated (since := "2024-06-07")] alias eq_true_of_ne_false := eq_true_of_ne_false @[deprecated (since := "2024-06-07")] alias eq_false_of_ne_true := eq_false_of_ne_true theorem or_inl {a b : Bool} (H : a) : a || b := by simp [H] theorem or_inr {a b : Bool} (H : b) : a || b := by cases a <;> simp [H] theorem and_elim_left : ∀ {a b : Bool}, a && b → a := by decide theorem and_intro : ∀ {a b : Bool}, a → b → a && b := by decide theorem and_elim_right : ∀ {a b : Bool}, a && b → b := by decide lemma eq_not_iff : ∀ {a b : Bool}, a = !b ↔ a ≠ b := by decide lemma not_eq_iff : ∀ {a b : Bool}, !a = b ↔ a ≠ b := by decide theorem ne_not {a b : Bool} : a ≠ !b ↔ a = b := not_eq_not @[deprecated (since := "2024-06-07")] alias not_ne := not_not_eq lemma not_ne_self : ∀ b : Bool, (!b) ≠ b := by decide lemma self_ne_not : ∀ b : Bool, b ≠ !b := by decide lemma eq_or_eq_not : ∀ a b, a = b ∨ a = !b := by decide -- Porting note: naming issue again: these two `not` are different. theorem not_iff_not : ∀ {b : Bool}, !b ↔ ¬b := by simp theorem eq_true_of_not_eq_false' {a : Bool} : !a = false → a = true := by cases a <;> decide theorem eq_false_of_not_eq_true' {a : Bool} : !a = true → a = false := by cases a <;> decide theorem bne_eq_xor : bne = xor := by funext a b; revert a b; decide attribute [simp] xor_assoc theorem xor_iff_ne : ∀ {x y : Bool}, xor x y = true ↔ x ≠ y := by decide /-! ### De Morgan's laws for booleans-/ instance linearOrder : LinearOrder Bool where le_refl := by decide le_trans := by decide le_antisymm := by decide le_total := by decide decidableLE := inferInstance decidableEq := inferInstance decidableLT := inferInstance lt_iff_le_not_le := by decide max_def := by decide min_def := by decide theorem lt_iff : ∀ {x y : Bool}, x < y ↔ x = false ∧ y = true := by decide @[simp] theorem false_lt_true : false < true := lt_iff.2 ⟨rfl, rfl⟩ theorem le_iff_imp : ∀ {x y : Bool}, x ≤ y ↔ x → y := by decide theorem and_le_left : ∀ x y : Bool, (x && y) ≤ x := by decide theorem and_le_right : ∀ x y : Bool, (x && y) ≤ y := by decide theorem le_and : ∀ {x y z : Bool}, x ≤ y → x ≤ z → x ≤ (y && z) := by decide theorem left_le_or : ∀ x y : Bool, x ≤ (x || y) := by decide theorem right_le_or : ∀ x y : Bool, y ≤ (x || y) := by decide theorem or_le : ∀ {x y z}, x ≤ z → y ≤ z → (x || y) ≤ z := by decide /-- convert a `ℕ` to a `Bool`, `0 -> false`, everything else -> `true` -/ def ofNat (n : Nat) : Bool := decide (n ≠ 0) @[simp] lemma toNat_beq_zero (b : Bool) : (b.toNat == 0) = !b := by cases b <;> rfl @[simp] lemma toNat_bne_zero (b : Bool) : (b.toNat != 0) = b := by simp [bne] @[simp] lemma toNat_beq_one (b : Bool) : (b.toNat == 1) = b := by cases b <;> rfl @[simp] lemma toNat_bne_one (b : Bool) : (b.toNat != 1) = !b := by simp [bne] theorem ofNat_le_ofNat {n m : Nat} (h : n ≤ m) : ofNat n ≤ ofNat m := by simp only [ofNat, ne_eq, _root_.decide_not] cases Nat.decEq n 0 with | isTrue hn => rw [_root_.decide_eq_true hn]; exact Bool.false_le _ | isFalse hn => cases Nat.decEq m 0 with | isFalse hm => rw [_root_.decide_eq_false hm]; exact Bool.le_true _ | isTrue hm => subst hm; have h := Nat.le_antisymm h (Nat.zero_le n); contradiction theorem toNat_le_toNat {b₀ b₁ : Bool} (h : b₀ ≤ b₁) : toNat b₀ ≤ toNat b₁ := by cases b₀ <;> cases b₁ <;> simp_all (config := { decide := true }) theorem ofNat_toNat (b : Bool) : ofNat (toNat b) = b := by cases b <;> rfl @[simp] theorem injective_iff {α : Sort*} {f : Bool → α} : Function.Injective f ↔ f false ≠ f true := ⟨fun Hinj Heq ↦ false_ne_true (Hinj Heq), fun H x y hxy ↦ by cases x <;> cases y exacts [rfl, (H hxy).elim, (H hxy.symm).elim, rfl]⟩ /-- **Kaminski's Equation** -/ theorem apply_apply_apply (f : Bool → Bool) (x : Bool) : f (f (f x)) = f x := by cases x <;> cases h₁ : f true <;> cases h₂ : f false <;> simp only [h₁, h₂] /-- `xor3 x y c` is `((x XOR y) XOR c)`. -/ protected def xor3 (x y c : Bool) := xor (xor x y) c /-- `carry x y c` is `x && y || x && c || y && c`. -/ protected def carry (x y c : Bool) := x && y || x && c || y && c end Bool
Data\Bool\Count.lean
/- Copyright (c) 2022 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import Mathlib.Algebra.Order.Ring.Nat import Mathlib.Data.List.Chain /-! # List of booleans In this file we prove lemmas about the number of `false`s and `true`s in a list of booleans. First we prove that the number of `false`s plus the number of `true` equals the length of the list. Then we prove that in a list with alternating `true`s and `false`s, the number of `true`s differs from the number of `false`s by at most one. We provide several versions of these statements. -/ namespace List @[simp] theorem count_not_add_count (l : List Bool) (b : Bool) : count (!b) l + count b l = length l := by -- Porting note: Proof re-written -- Old proof: simp only [length_eq_countP_add_countP (Eq (!b)), Bool.not_not_eq, count] simp only [length_eq_countP_add_countP (· == !b), count, add_right_inj] suffices (fun x => x == b) = (fun a => decide ¬(a == !b) = true) by rw [this] ext x; cases x <;> cases b <;> rfl @[simp] theorem count_add_count_not (l : List Bool) (b : Bool) : count b l + count (!b) l = length l := by rw [add_comm, count_not_add_count] @[simp] theorem count_false_add_count_true (l : List Bool) : count false l + count true l = length l := count_not_add_count l true @[simp] theorem count_true_add_count_false (l : List Bool) : count true l + count false l = length l := count_not_add_count l false theorem Chain.count_not : ∀ {b : Bool} {l : List Bool}, Chain (· ≠ ·) b l → count (!b) l = count b l + length l % 2 | b, [], _h => rfl | b, x :: l, h => by obtain rfl : b = !x := Bool.eq_not_iff.2 (rel_of_chain_cons h) rw [Bool.not_not, count_cons_self, count_cons_of_ne x.not_ne_self, Chain.count_not (chain_of_chain_cons h), length, add_assoc, Nat.mod_two_add_succ_mod_two] namespace Chain' variable {l : List Bool} theorem count_not_eq_count (hl : Chain' (· ≠ ·) l) (h2 : Even (length l)) (b : Bool) : count (!b) l = count b l := by cases' l with x l · rfl rw [length_cons, Nat.even_add_one, Nat.not_even_iff] at h2 suffices count (!x) (x :: l) = count x (x :: l) by -- Porting note: old proof is -- cases b <;> cases x <;> try exact this; cases b <;> cases x <;> revert this <;> simp only [Bool.not_false, Bool.not_true] <;> intro this <;> (try exact this) <;> exact this.symm rw [count_cons_of_ne x.not_ne_self, hl.count_not, h2, count_cons_self] theorem count_false_eq_count_true (hl : Chain' (· ≠ ·) l) (h2 : Even (length l)) : count false l = count true l := hl.count_not_eq_count h2 true theorem count_not_le_count_add_one (hl : Chain' (· ≠ ·) l) (b : Bool) : count (!b) l ≤ count b l + 1 := by cases' l with x l · exact zero_le _ obtain rfl | rfl : b = x ∨ b = !x := by simp only [Bool.eq_not_iff, em] · rw [count_cons_of_ne b.not_ne_self, count_cons_self, hl.count_not, add_assoc] exact add_le_add_left (Nat.mod_lt _ two_pos).le _ · rw [Bool.not_not, count_cons_self, count_cons_of_ne x.not_ne_self, hl.count_not] exact add_le_add_right (le_add_right le_rfl) _ theorem count_false_le_count_true_add_one (hl : Chain' (· ≠ ·) l) : count false l ≤ count true l + 1 := hl.count_not_le_count_add_one true theorem count_true_le_count_false_add_one (hl : Chain' (· ≠ ·) l) : count true l ≤ count false l + 1 := hl.count_not_le_count_add_one false theorem two_mul_count_bool_of_even (hl : Chain' (· ≠ ·) l) (h2 : Even (length l)) (b : Bool) : 2 * count b l = length l := by rw [← count_not_add_count l b, hl.count_not_eq_count h2, two_mul] theorem two_mul_count_bool_eq_ite (hl : Chain' (· ≠ ·) l) (b : Bool) : 2 * count b l = if Even (length l) then length l else if Option.some b == l.head? then length l + 1 else length l - 1 := by by_cases h2 : Even (length l) · rw [if_pos h2, hl.two_mul_count_bool_of_even h2] · cases' l with x l · exact (h2 even_zero).elim simp only [if_neg h2, count_cons, mul_add, head?, Option.mem_some_iff, @eq_comm _ x] rw [length_cons, Nat.even_add_one, not_not] at h2 replace hl : l.Chain' (· ≠ ·) := hl.tail rw [hl.two_mul_count_bool_of_even h2] cases b <;> cases x <;> split_ifs <;> simp <;> contradiction theorem length_sub_one_le_two_mul_count_bool (hl : Chain' (· ≠ ·) l) (b : Bool) : length l - 1 ≤ 2 * count b l := by rw [hl.two_mul_count_bool_eq_ite] split_ifs <;> simp [le_tsub_add, Nat.le_succ_of_le] theorem length_div_two_le_count_bool (hl : Chain' (· ≠ ·) l) (b : Bool) : length l / 2 ≤ count b l := by rw [Nat.div_le_iff_le_mul_add_pred two_pos, ← tsub_le_iff_right] exact length_sub_one_le_two_mul_count_bool hl b theorem two_mul_count_bool_le_length_add_one (hl : Chain' (· ≠ ·) l) (b : Bool) : 2 * count b l ≤ length l + 1 := by rw [hl.two_mul_count_bool_eq_ite] split_ifs <;> simp [Nat.le_succ_of_le] end Chain' end List
Data\Bool\Set.lean
/- Copyright (c) 2021 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import Mathlib.Data.Set.Image /-! # Booleans and set operations This file contains two trivial lemmas about `Bool`, `Set.univ`, and `Set.range`. -/ open Set namespace Bool @[simp] theorem univ_eq : (univ : Set Bool) = {false, true} := (eq_univ_of_forall Bool.dichotomy).symm @[simp] theorem range_eq {α : Type*} (f : Bool → α) : range f = {f false, f true} := by rw [← image_univ, univ_eq, image_pair] @[simp] theorem compl_singleton (b : Bool) : ({b}ᶜ : Set Bool) = {!b} := Set.ext fun _ => eq_not_iff.symm end Bool
Data\Complex\Abs.lean
/- Copyright (c) 2017 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, Mario Carneiro -/ import Mathlib.Data.Complex.Basic import Mathlib.Data.Real.Sqrt /-! # Absolute values of complex numbers -/ open Set ComplexConjugate namespace Complex /-! ### Absolute value -/ namespace AbsTheory -- We develop enough theory to bundle `abs` into an `AbsoluteValue` before making things public; -- this is so there's not two versions of it hanging around. local notation "abs" z => Real.sqrt (normSq z) private theorem mul_self_abs (z : ℂ) : ((abs z) * abs z) = normSq z := Real.mul_self_sqrt (normSq_nonneg _) private theorem abs_nonneg' (z : ℂ) : 0 ≤ abs z := Real.sqrt_nonneg _ theorem abs_conj (z : ℂ) : (abs conj z) = abs z := by simp private theorem abs_re_le_abs (z : ℂ) : |z.re| ≤ abs z := by rw [mul_self_le_mul_self_iff (abs_nonneg z.re) (abs_nonneg' _), abs_mul_abs_self, mul_self_abs] apply re_sq_le_normSq private theorem re_le_abs (z : ℂ) : z.re ≤ abs z := (abs_le.1 (abs_re_le_abs _)).2 private theorem abs_mul (z w : ℂ) : (abs z * w) = (abs z) * abs w := by rw [normSq_mul, Real.sqrt_mul (normSq_nonneg _)] private theorem abs_add (z w : ℂ) : (abs z + w) ≤ (abs z) + abs w := (mul_self_le_mul_self_iff (abs_nonneg' (z + w)) (add_nonneg (abs_nonneg' z) (abs_nonneg' w))).2 <| by rw [mul_self_abs, add_mul_self_eq, mul_self_abs, mul_self_abs, add_right_comm, normSq_add, add_le_add_iff_left, mul_assoc, mul_le_mul_left (zero_lt_two' ℝ), ← Real.sqrt_mul <| normSq_nonneg z, ← normSq_conj w, ← map_mul] exact re_le_abs (z * conj w) /-- The complex absolute value function, defined as the square root of the norm squared. -/ noncomputable def _root_.Complex.abs : AbsoluteValue ℂ ℝ where toFun x := abs x map_mul' := abs_mul nonneg' := abs_nonneg' eq_zero' _ := (Real.sqrt_eq_zero <| normSq_nonneg _).trans normSq_eq_zero add_le' := abs_add end AbsTheory theorem abs_def : (Complex.abs : ℂ → ℝ) = fun z => (normSq z).sqrt := rfl theorem abs_apply {z : ℂ} : Complex.abs z = (normSq z).sqrt := rfl @[simp, norm_cast] theorem abs_ofReal (r : ℝ) : Complex.abs r = |r| := by simp [Complex.abs, normSq_ofReal, Real.sqrt_mul_self_eq_abs] nonrec theorem abs_of_nonneg {r : ℝ} (h : 0 ≤ r) : Complex.abs r = r := (Complex.abs_ofReal _).trans (abs_of_nonneg h) -- Porting note: removed `norm_cast` attribute because the RHS can't start with `↑` @[simp] theorem abs_natCast (n : ℕ) : Complex.abs n = n := Complex.abs_of_nonneg (Nat.cast_nonneg n) -- See note [no_index around OfNat.ofNat] @[simp] theorem abs_ofNat (n : ℕ) [n.AtLeastTwo] : Complex.abs (no_index (OfNat.ofNat n : ℂ)) = OfNat.ofNat n := abs_natCast n theorem mul_self_abs (z : ℂ) : Complex.abs z * Complex.abs z = normSq z := Real.mul_self_sqrt (normSq_nonneg _) theorem sq_abs (z : ℂ) : Complex.abs z ^ 2 = normSq z := Real.sq_sqrt (normSq_nonneg _) @[simp] theorem sq_abs_sub_sq_re (z : ℂ) : Complex.abs z ^ 2 - z.re ^ 2 = z.im ^ 2 := by rw [sq_abs, normSq_apply, ← sq, ← sq, add_sub_cancel_left] @[simp] theorem sq_abs_sub_sq_im (z : ℂ) : Complex.abs z ^ 2 - z.im ^ 2 = z.re ^ 2 := by rw [← sq_abs_sub_sq_re, sub_sub_cancel] lemma abs_add_mul_I (x y : ℝ) : abs (x + y * I) = (x ^ 2 + y ^ 2).sqrt := by rw [← normSq_add_mul_I]; rfl lemma abs_eq_sqrt_sq_add_sq (z : ℂ) : abs z = (z.re ^ 2 + z.im ^ 2).sqrt := by rw [abs_apply, normSq_apply, sq, sq] @[simp] theorem abs_I : Complex.abs I = 1 := by simp [Complex.abs] theorem abs_two : Complex.abs 2 = 2 := abs_ofNat 2 @[simp] theorem range_abs : range Complex.abs = Ici 0 := Subset.antisymm (by simp only [range_subset_iff, Ici, mem_setOf_eq, apply_nonneg, forall_const]) (fun x hx => ⟨x, Complex.abs_of_nonneg hx⟩) @[simp] theorem abs_conj (z : ℂ) : Complex.abs (conj z) = Complex.abs z := AbsTheory.abs_conj z -- Porting note (#10618): @[simp] can prove it now theorem abs_prod {ι : Type*} (s : Finset ι) (f : ι → ℂ) : Complex.abs (s.prod f) = s.prod fun I => Complex.abs (f I) := map_prod Complex.abs _ _ -- @[simp] /- Porting note (#11119): `simp` attribute removed as linter reports this can be proved by `simp only [@map_pow]` -/ theorem abs_pow (z : ℂ) (n : ℕ) : Complex.abs (z ^ n) = Complex.abs z ^ n := map_pow Complex.abs z n -- @[simp] /- Porting note (#11119): `simp` attribute removed as linter reports this can be proved by `simp only [@map_zpow₀]` -/ theorem abs_zpow (z : ℂ) (n : ℤ) : Complex.abs (z ^ n) = Complex.abs z ^ n := map_zpow₀ Complex.abs z n @[bound] theorem abs_re_le_abs (z : ℂ) : |z.re| ≤ Complex.abs z := Real.abs_le_sqrt <| by rw [normSq_apply, ← sq] exact le_add_of_nonneg_right (mul_self_nonneg _) @[bound] theorem abs_im_le_abs (z : ℂ) : |z.im| ≤ Complex.abs z := Real.abs_le_sqrt <| by rw [normSq_apply, ← sq, ← sq] exact le_add_of_nonneg_left (sq_nonneg _) theorem re_le_abs (z : ℂ) : z.re ≤ Complex.abs z := (abs_le.1 (abs_re_le_abs _)).2 theorem im_le_abs (z : ℂ) : z.im ≤ Complex.abs z := (abs_le.1 (abs_im_le_abs _)).2 @[simp] theorem abs_re_lt_abs {z : ℂ} : |z.re| < Complex.abs z ↔ z.im ≠ 0 := by rw [Complex.abs, AbsoluteValue.coe_mk, MulHom.coe_mk, Real.lt_sqrt (abs_nonneg _), normSq_apply, _root_.sq_abs, ← sq, lt_add_iff_pos_right, mul_self_pos] @[simp] theorem abs_im_lt_abs {z : ℂ} : |z.im| < Complex.abs z ↔ z.re ≠ 0 := by simpa using @abs_re_lt_abs (z * I) @[simp] lemma abs_re_eq_abs {z : ℂ} : |z.re| = abs z ↔ z.im = 0 := not_iff_not.1 <| (abs_re_le_abs z).lt_iff_ne.symm.trans abs_re_lt_abs @[simp] lemma abs_im_eq_abs {z : ℂ} : |z.im| = abs z ↔ z.re = 0 := not_iff_not.1 <| (abs_im_le_abs z).lt_iff_ne.symm.trans abs_im_lt_abs @[simp] theorem abs_abs (z : ℂ) : |Complex.abs z| = Complex.abs z := _root_.abs_of_nonneg (AbsoluteValue.nonneg _ z) -- Porting note: probably should be golfed theorem abs_le_abs_re_add_abs_im (z : ℂ) : Complex.abs z ≤ |z.re| + |z.im| := by simpa [re_add_im] using Complex.abs.add_le z.re (z.im * I) -- Porting note: added so `two_pos` in the next proof works -- TODO: move somewhere else instance : NeZero (1 : ℝ) := ⟨by apply one_ne_zero⟩ theorem abs_le_sqrt_two_mul_max (z : ℂ) : Complex.abs z ≤ Real.sqrt 2 * max |z.re| |z.im| := by cases' z with x y simp only [abs_apply, normSq_mk, ← sq] by_cases hle : |x| ≤ |y| · calc Real.sqrt (x ^ 2 + y ^ 2) ≤ Real.sqrt (y ^ 2 + y ^ 2) := Real.sqrt_le_sqrt (add_le_add_right (sq_le_sq.2 hle) _) _ = Real.sqrt 2 * max |x| |y| := by rw [max_eq_right hle, ← two_mul, Real.sqrt_mul two_pos.le, Real.sqrt_sq_eq_abs] · have hle' := le_of_not_le hle rw [add_comm] calc Real.sqrt (y ^ 2 + x ^ 2) ≤ Real.sqrt (x ^ 2 + x ^ 2) := Real.sqrt_le_sqrt (add_le_add_right (sq_le_sq.2 hle') _) _ = Real.sqrt 2 * max |x| |y| := by rw [max_eq_left hle', ← two_mul, Real.sqrt_mul two_pos.le, Real.sqrt_sq_eq_abs] theorem abs_re_div_abs_le_one (z : ℂ) : |z.re / Complex.abs z| ≤ 1 := if hz : z = 0 then by simp [hz, zero_le_one] else by simp_rw [_root_.abs_div, abs_abs, div_le_iff (AbsoluteValue.pos Complex.abs hz), one_mul, abs_re_le_abs] theorem abs_im_div_abs_le_one (z : ℂ) : |z.im / Complex.abs z| ≤ 1 := if hz : z = 0 then by simp [hz, zero_le_one] else by simp_rw [_root_.abs_div, abs_abs, div_le_iff (AbsoluteValue.pos Complex.abs hz), one_mul, abs_im_le_abs] @[simp, norm_cast] lemma abs_intCast (n : ℤ) : abs n = |↑n| := by rw [← ofReal_intCast, abs_ofReal] @[deprecated (since := "2024-02-14")] lemma int_cast_abs (n : ℤ) : |↑n| = Complex.abs n := (abs_intCast _).symm theorem normSq_eq_abs (x : ℂ) : normSq x = (Complex.abs x) ^ 2 := by simp [abs, sq, abs_def, Real.mul_self_sqrt (normSq_nonneg _)] @[simp] theorem range_normSq : range normSq = Ici 0 := Subset.antisymm (range_subset_iff.2 normSq_nonneg) fun x hx => ⟨Real.sqrt x, by rw [normSq_ofReal, Real.mul_self_sqrt hx]⟩ /-! ### Cauchy sequences -/ local notation "abs'" => _root_.abs theorem isCauSeq_re (f : CauSeq ℂ Complex.abs) : IsCauSeq abs' fun n => (f n).re := fun ε ε0 => (f.cauchy ε0).imp fun i H j ij => lt_of_le_of_lt (by simpa using abs_re_le_abs (f j - f i)) (H _ ij) theorem isCauSeq_im (f : CauSeq ℂ Complex.abs) : IsCauSeq abs' fun n => (f n).im := fun ε ε0 => (f.cauchy ε0).imp fun i H j ij ↦ by simpa only [← ofReal_sub, abs_ofReal, sub_re] using (abs_im_le_abs _).trans_lt $ H _ ij /-- The real part of a complex Cauchy sequence, as a real Cauchy sequence. -/ noncomputable def cauSeqRe (f : CauSeq ℂ Complex.abs) : CauSeq ℝ abs' := ⟨_, isCauSeq_re f⟩ /-- The imaginary part of a complex Cauchy sequence, as a real Cauchy sequence. -/ noncomputable def cauSeqIm (f : CauSeq ℂ Complex.abs) : CauSeq ℝ abs' := ⟨_, isCauSeq_im f⟩ theorem isCauSeq_abs {f : ℕ → ℂ} (hf : IsCauSeq Complex.abs f) : IsCauSeq abs' (Complex.abs ∘ f) := fun ε ε0 => let ⟨i, hi⟩ := hf ε ε0 ⟨i, fun j hj => lt_of_le_of_lt (Complex.abs.abs_abv_sub_le_abv_sub _ _) (hi j hj)⟩ /-- The limit of a Cauchy sequence of complex numbers. -/ noncomputable def limAux (f : CauSeq ℂ Complex.abs) : ℂ := ⟨CauSeq.lim (cauSeqRe f), CauSeq.lim (cauSeqIm f)⟩ theorem equiv_limAux (f : CauSeq ℂ Complex.abs) : f ≈ CauSeq.const Complex.abs (limAux f) := fun ε ε0 => (exists_forall_ge_and (CauSeq.equiv_lim ⟨_, isCauSeq_re f⟩ _ (half_pos ε0)) (CauSeq.equiv_lim ⟨_, isCauSeq_im f⟩ _ (half_pos ε0))).imp fun i H j ij => by cases' H _ ij with H₁ H₂ apply lt_of_le_of_lt (abs_le_abs_re_add_abs_im _) dsimp [limAux] at * have := add_lt_add H₁ H₂ rwa [add_halves] at this instance instIsComplete : CauSeq.IsComplete ℂ Complex.abs := ⟨fun f => ⟨limAux f, equiv_limAux f⟩⟩ open CauSeq theorem lim_eq_lim_im_add_lim_re (f : CauSeq ℂ Complex.abs) : lim f = ↑(lim (cauSeqRe f)) + ↑(lim (cauSeqIm f)) * I := lim_eq_of_equiv_const <| calc f ≈ _ := equiv_limAux f _ = CauSeq.const Complex.abs (↑(lim (cauSeqRe f)) + ↑(lim (cauSeqIm f)) * I) := CauSeq.ext fun _ => Complex.ext (by simp [limAux, cauSeqRe, ofReal']) (by simp [limAux, cauSeqIm, ofReal']) theorem lim_re (f : CauSeq ℂ Complex.abs) : lim (cauSeqRe f) = (lim f).re := by rw [lim_eq_lim_im_add_lim_re]; simp [ofReal'] theorem lim_im (f : CauSeq ℂ Complex.abs) : lim (cauSeqIm f) = (lim f).im := by rw [lim_eq_lim_im_add_lim_re]; simp [ofReal'] theorem isCauSeq_conj (f : CauSeq ℂ Complex.abs) : IsCauSeq Complex.abs fun n => conj (f n) := fun ε ε0 => let ⟨i, hi⟩ := f.2 ε ε0 ⟨i, fun j hj => by rw [← RingHom.map_sub, abs_conj]; exact hi j hj⟩ /-- The complex conjugate of a complex Cauchy sequence, as a complex Cauchy sequence. -/ noncomputable def cauSeqConj (f : CauSeq ℂ Complex.abs) : CauSeq ℂ Complex.abs := ⟨_, isCauSeq_conj f⟩ theorem lim_conj (f : CauSeq ℂ Complex.abs) : lim (cauSeqConj f) = conj (lim f) := Complex.ext (by simp [cauSeqConj, (lim_re _).symm, cauSeqRe]) (by simp [cauSeqConj, (lim_im _).symm, cauSeqIm, (lim_neg _).symm]; rfl) /-- The absolute value of a complex Cauchy sequence, as a real Cauchy sequence. -/ noncomputable def cauSeqAbs (f : CauSeq ℂ Complex.abs) : CauSeq ℝ abs' := ⟨_, isCauSeq_abs f.2⟩ theorem lim_abs (f : CauSeq ℂ Complex.abs) : lim (cauSeqAbs f) = Complex.abs (lim f) := lim_eq_of_equiv_const fun ε ε0 => let ⟨i, hi⟩ := equiv_lim f ε ε0 ⟨i, fun j hj => lt_of_le_of_lt (Complex.abs.abs_abv_sub_le_abv_sub _ _) (hi j hj)⟩ lemma ne_zero_of_one_lt_re {s : ℂ} (hs : 1 < s.re) : s ≠ 0 := fun h ↦ ((zero_re ▸ h ▸ hs).trans zero_lt_one).false lemma re_neg_ne_zero_of_one_lt_re {s : ℂ} (hs : 1 < s.re) : (-s).re ≠ 0 := ne_iff_lt_or_gt.mpr <| Or.inl <| neg_re s ▸ by linarith end Complex
Data\Complex\Basic.lean
/- Copyright (c) 2017 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, Mario Carneiro -/ import Mathlib.Algebra.CharZero.Lemmas import Mathlib.Algebra.GroupWithZero.Divisibility import Mathlib.Algebra.Star.Basic import Mathlib.Data.Real.Basic import Mathlib.Data.Set.Image import Mathlib.Tactic.Ring /-! # The complex numbers The complex numbers are modelled as ℝ^2 in the obvious way and it is shown that they form a field of characteristic zero. The result that the complex numbers are algebraically closed, see `FieldTheory.AlgebraicClosure`. -/ open Set Function /-! ### Definition and basic arithmetic -/ /-- Complex numbers consist of two `Real`s: a real part `re` and an imaginary part `im`. -/ structure Complex : Type where /-- The real part of a complex number. -/ re : ℝ /-- The imaginary part of a complex number. -/ im : ℝ @[inherit_doc] notation "ℂ" => Complex namespace Complex open ComplexConjugate noncomputable instance : DecidableEq ℂ := Classical.decEq _ /-- The equivalence between the complex numbers and `ℝ × ℝ`. -/ @[simps apply] def equivRealProd : ℂ ≃ ℝ × ℝ where toFun z := ⟨z.re, z.im⟩ invFun p := ⟨p.1, p.2⟩ left_inv := fun ⟨_, _⟩ => rfl right_inv := fun ⟨_, _⟩ => rfl @[simp] theorem eta : ∀ z : ℂ, Complex.mk z.re z.im = z | ⟨_, _⟩ => rfl -- We only mark this lemma with `ext` *locally* to avoid it applying whenever terms of `ℂ` appear. theorem ext : ∀ {z w : ℂ}, z.re = w.re → z.im = w.im → z = w | ⟨_, _⟩, ⟨_, _⟩, rfl, rfl => rfl attribute [local ext] Complex.ext theorem re_surjective : Surjective re := fun x => ⟨⟨x, 0⟩, rfl⟩ theorem im_surjective : Surjective im := fun y => ⟨⟨0, y⟩, rfl⟩ @[simp] theorem range_re : range re = univ := re_surjective.range_eq @[simp] theorem range_im : range im = univ := im_surjective.range_eq -- Porting note: refactored instance to allow `norm_cast` to work /-- The natural inclusion of the real numbers into the complex numbers. The name `Complex.ofReal` is reserved for the bundled homomorphism. -/ @[coe] def ofReal' (r : ℝ) : ℂ := ⟨r, 0⟩ instance : Coe ℝ ℂ := ⟨ofReal'⟩ @[simp, norm_cast] theorem ofReal_re (r : ℝ) : Complex.re (r : ℂ) = r := rfl @[simp, norm_cast] theorem ofReal_im (r : ℝ) : (r : ℂ).im = 0 := rfl theorem ofReal_def (r : ℝ) : (r : ℂ) = ⟨r, 0⟩ := rfl @[simp, norm_cast] theorem ofReal_inj {z w : ℝ} : (z : ℂ) = w ↔ z = w := ⟨congrArg re, by apply congrArg⟩ -- Porting note: made coercion explicit theorem ofReal_injective : Function.Injective ((↑) : ℝ → ℂ) := fun _ _ => congrArg re -- Porting note: made coercion explicit instance canLift : CanLift ℂ ℝ (↑) fun z => z.im = 0 where prf z hz := ⟨z.re, ext rfl hz.symm⟩ /-- The product of a set on the real axis and a set on the imaginary axis of the complex plane, denoted by `s ×ℂ t`. -/ def Set.reProdIm (s t : Set ℝ) : Set ℂ := re ⁻¹' s ∩ im ⁻¹' t @[inherit_doc] infixl:72 " ×ℂ " => Set.reProdIm theorem mem_reProdIm {z : ℂ} {s t : Set ℝ} : z ∈ s ×ℂ t ↔ z.re ∈ s ∧ z.im ∈ t := Iff.rfl instance : Zero ℂ := ⟨(0 : ℝ)⟩ instance : Inhabited ℂ := ⟨0⟩ @[simp] theorem zero_re : (0 : ℂ).re = 0 := rfl @[simp] theorem zero_im : (0 : ℂ).im = 0 := rfl @[simp, norm_cast] theorem ofReal_zero : ((0 : ℝ) : ℂ) = 0 := rfl @[simp] theorem ofReal_eq_zero {z : ℝ} : (z : ℂ) = 0 ↔ z = 0 := ofReal_inj theorem ofReal_ne_zero {z : ℝ} : (z : ℂ) ≠ 0 ↔ z ≠ 0 := not_congr ofReal_eq_zero instance : One ℂ := ⟨(1 : ℝ)⟩ @[simp] theorem one_re : (1 : ℂ).re = 1 := rfl @[simp] theorem one_im : (1 : ℂ).im = 0 := rfl @[simp, norm_cast] theorem ofReal_one : ((1 : ℝ) : ℂ) = 1 := rfl @[simp] theorem ofReal_eq_one {z : ℝ} : (z : ℂ) = 1 ↔ z = 1 := ofReal_inj theorem ofReal_ne_one {z : ℝ} : (z : ℂ) ≠ 1 ↔ z ≠ 1 := not_congr ofReal_eq_one instance : Add ℂ := ⟨fun z w => ⟨z.re + w.re, z.im + w.im⟩⟩ @[simp] theorem add_re (z w : ℂ) : (z + w).re = z.re + w.re := rfl @[simp] theorem add_im (z w : ℂ) : (z + w).im = z.im + w.im := rfl -- replaced by `re_ofNat` -- replaced by `im_ofNat` @[simp, norm_cast] theorem ofReal_add (r s : ℝ) : ((r + s : ℝ) : ℂ) = r + s := Complex.ext_iff.2 <| by simp [ofReal'] -- replaced by `Complex.ofReal_ofNat` instance : Neg ℂ := ⟨fun z => ⟨-z.re, -z.im⟩⟩ @[simp] theorem neg_re (z : ℂ) : (-z).re = -z.re := rfl @[simp] theorem neg_im (z : ℂ) : (-z).im = -z.im := rfl @[simp, norm_cast] theorem ofReal_neg (r : ℝ) : ((-r : ℝ) : ℂ) = -r := Complex.ext_iff.2 <| by simp [ofReal'] instance : Sub ℂ := ⟨fun z w => ⟨z.re - w.re, z.im - w.im⟩⟩ instance : Mul ℂ := ⟨fun z w => ⟨z.re * w.re - z.im * w.im, z.re * w.im + z.im * w.re⟩⟩ @[simp] theorem mul_re (z w : ℂ) : (z * w).re = z.re * w.re - z.im * w.im := rfl @[simp] theorem mul_im (z w : ℂ) : (z * w).im = z.re * w.im + z.im * w.re := rfl @[simp, norm_cast] theorem ofReal_mul (r s : ℝ) : ((r * s : ℝ) : ℂ) = r * s := Complex.ext_iff.2 <| by simp [ofReal'] theorem re_ofReal_mul (r : ℝ) (z : ℂ) : (r * z).re = r * z.re := by simp [ofReal'] theorem im_ofReal_mul (r : ℝ) (z : ℂ) : (r * z).im = r * z.im := by simp [ofReal'] lemma re_mul_ofReal (z : ℂ) (r : ℝ) : (z * r).re = z.re * r := by simp [ofReal'] lemma im_mul_ofReal (z : ℂ) (r : ℝ) : (z * r).im = z.im * r := by simp [ofReal'] theorem ofReal_mul' (r : ℝ) (z : ℂ) : ↑r * z = ⟨r * z.re, r * z.im⟩ := ext (re_ofReal_mul _ _) (im_ofReal_mul _ _) /-! ### The imaginary unit, `I` -/ /-- The imaginary unit. -/ def I : ℂ := ⟨0, 1⟩ @[simp] theorem I_re : I.re = 0 := rfl @[simp] theorem I_im : I.im = 1 := rfl @[simp] theorem I_mul_I : I * I = -1 := Complex.ext_iff.2 <| by simp theorem I_mul (z : ℂ) : I * z = ⟨-z.im, z.re⟩ := Complex.ext_iff.2 <| by simp @[simp] lemma I_ne_zero : (I : ℂ) ≠ 0 := mt (congr_arg im) zero_ne_one.symm theorem mk_eq_add_mul_I (a b : ℝ) : Complex.mk a b = a + b * I := Complex.ext_iff.2 <| by simp [ofReal'] @[simp] theorem re_add_im (z : ℂ) : (z.re : ℂ) + z.im * I = z := Complex.ext_iff.2 <| by simp [ofReal'] theorem mul_I_re (z : ℂ) : (z * I).re = -z.im := by simp theorem mul_I_im (z : ℂ) : (z * I).im = z.re := by simp theorem I_mul_re (z : ℂ) : (I * z).re = -z.im := by simp theorem I_mul_im (z : ℂ) : (I * z).im = z.re := by simp @[simp] theorem equivRealProd_symm_apply (p : ℝ × ℝ) : equivRealProd.symm p = p.1 + p.2 * I := by ext <;> simp [Complex.equivRealProd, ofReal'] /-- The natural `AddEquiv` from `ℂ` to `ℝ × ℝ`. -/ @[simps! (config := { simpRhs := true }) apply symm_apply_re symm_apply_im] def equivRealProdAddHom : ℂ ≃+ ℝ × ℝ := { equivRealProd with map_add' := by simp } theorem equivRealProdAddHom_symm_apply (p : ℝ × ℝ) : equivRealProdAddHom.symm p = p.1 + p.2 * I := equivRealProd_symm_apply p /-! ### Commutative ring instance and lemmas -/ /- We use a nonstandard formula for the `ℕ` and `ℤ` actions to make sure there is no diamond from the other actions they inherit through the `ℝ`-action on `ℂ` and action transitivity defined in `Data.Complex.Module`. -/ instance : Nontrivial ℂ := pullback_nonzero re rfl rfl -- Porting note: moved from `Module/Data/Complex/Basic.lean` namespace SMul -- The useless `0` multiplication in `smul` is to make sure that -- `RestrictScalars.module ℝ ℂ ℂ = Complex.module` definitionally. -- instance made scoped to avoid situations like instance synthesis -- of `SMul ℂ ℂ` trying to proceed via `SMul ℂ ℝ`. /-- Scalar multiplication by `R` on `ℝ` extends to `ℂ`. This is used here and in `Matlib.Data.Complex.Module` to transfer instances from `ℝ` to `ℂ`, but is not needed outside, so we make it scoped. -/ scoped instance instSMulRealComplex {R : Type*} [SMul R ℝ] : SMul R ℂ where smul r x := ⟨r • x.re - 0 * x.im, r • x.im + 0 * x.re⟩ end SMul open scoped SMul section SMul variable {R : Type*} [SMul R ℝ] theorem smul_re (r : R) (z : ℂ) : (r • z).re = r • z.re := by simp [(· • ·), SMul.smul] theorem smul_im (r : R) (z : ℂ) : (r • z).im = r • z.im := by simp [(· • ·), SMul.smul] @[simp] theorem real_smul {x : ℝ} {z : ℂ} : x • z = x * z := rfl end SMul -- Porting note: proof needed modifications and rewritten fields instance addCommGroup : AddCommGroup ℂ := { zero := (0 : ℂ) add := (· + ·) neg := Neg.neg sub := Sub.sub nsmul := fun n z => n • z zsmul := fun n z => n • z zsmul_zero' := by intros; ext <;> simp [smul_re, smul_im] nsmul_zero := by intros; ext <;> simp [smul_re, smul_im] nsmul_succ := by intros; ext <;> simp [AddMonoid.nsmul_succ, add_mul, add_comm, smul_re, smul_im] zsmul_succ' := by intros; ext <;> simp [SubNegMonoid.zsmul_succ', add_mul, add_comm, smul_re, smul_im] zsmul_neg' := by intros; ext <;> simp [zsmul_neg', add_mul, smul_re, smul_im] add_assoc := by intros; ext <;> simp [add_assoc] zero_add := by intros; ext <;> simp add_zero := by intros; ext <;> simp add_comm := by intros; ext <;> simp [add_comm] add_left_neg := by intros; ext <;> simp } instance addGroupWithOne : AddGroupWithOne ℂ := { Complex.addCommGroup with natCast := fun n => ⟨n, 0⟩ natCast_zero := by ext <;> simp [Nat.cast, AddMonoidWithOne.natCast_zero] natCast_succ := fun _ => by ext <;> simp [Nat.cast, AddMonoidWithOne.natCast_succ] intCast := fun n => ⟨n, 0⟩ intCast_ofNat := fun _ => by ext <;> rfl intCast_negSucc := fun n => by ext · simp [AddGroupWithOne.intCast_negSucc] show -(1 : ℝ) + (-n) = -(↑(n + 1)) simp [Nat.cast_add, add_comm] · simp [AddGroupWithOne.intCast_negSucc] show im ⟨n, 0⟩ = 0 rfl one := 1 } -- Porting note: proof needed modifications and rewritten fields instance commRing : CommRing ℂ := { addGroupWithOne with mul := (· * ·) npow := @npowRec _ ⟨(1 : ℂ)⟩ ⟨(· * ·)⟩ add_comm := by intros; ext <;> simp [add_comm] left_distrib := by intros; ext <;> simp [mul_re, mul_im] <;> ring right_distrib := by intros; ext <;> simp [mul_re, mul_im] <;> ring zero_mul := by intros; ext <;> simp [zero_mul] mul_zero := by intros; ext <;> simp [mul_zero] mul_assoc := by intros; ext <;> simp [mul_assoc] <;> ring one_mul := by intros; ext <;> simp [one_mul] mul_one := by intros; ext <;> simp [mul_one] mul_comm := by intros; ext <;> simp [mul_comm]; ring } /-- This shortcut instance ensures we do not find `Ring` via the noncomputable `Complex.field` instance. -/ instance : Ring ℂ := by infer_instance /-- This shortcut instance ensures we do not find `CommSemiring` via the noncomputable `Complex.field` instance. -/ instance : CommSemiring ℂ := inferInstance -- Porting note: added due to changes in typeclass search order /-- This shortcut instance ensures we do not find `Semiring` via the noncomputable `Complex.field` instance. -/ instance : Semiring ℂ := inferInstance /-- The "real part" map, considered as an additive group homomorphism. -/ def reAddGroupHom : ℂ →+ ℝ where toFun := re map_zero' := zero_re map_add' := add_re @[simp] theorem coe_reAddGroupHom : (reAddGroupHom : ℂ → ℝ) = re := rfl /-- The "imaginary part" map, considered as an additive group homomorphism. -/ def imAddGroupHom : ℂ →+ ℝ where toFun := im map_zero' := zero_im map_add' := add_im @[simp] theorem coe_imAddGroupHom : (imAddGroupHom : ℂ → ℝ) = im := rfl section end /-! ### Cast lemmas -/ noncomputable instance instNNRatCast : NNRatCast ℂ where nnratCast q := ofReal' q noncomputable instance instRatCast : RatCast ℂ where ratCast q := ofReal' q -- See note [no_index around OfNat.ofNat] @[simp, norm_cast] lemma ofReal_ofNat (n : ℕ) [n.AtLeastTwo] : ofReal' (no_index (OfNat.ofNat n)) = OfNat.ofNat n := rfl @[simp, norm_cast] lemma ofReal_natCast (n : ℕ) : ofReal' n = n := rfl @[simp, norm_cast] lemma ofReal_intCast (n : ℤ) : ofReal' n = n := rfl @[simp, norm_cast] lemma ofReal_nnratCast (q : ℚ≥0) : ofReal' q = q := rfl @[simp, norm_cast] lemma ofReal_ratCast (q : ℚ) : ofReal' q = q := rfl @[deprecated (since := "2024-04-17")] alias ofReal_rat_cast := ofReal_ratCast -- See note [no_index around OfNat.ofNat] @[simp] lemma re_ofNat (n : ℕ) [n.AtLeastTwo] : (no_index (OfNat.ofNat n) : ℂ).re = OfNat.ofNat n := rfl @[simp] lemma im_ofNat (n : ℕ) [n.AtLeastTwo] : (no_index (OfNat.ofNat n) : ℂ).im = 0 := rfl @[simp, norm_cast] lemma natCast_re (n : ℕ) : (n : ℂ).re = n := rfl @[simp, norm_cast] lemma natCast_im (n : ℕ) : (n : ℂ).im = 0 := rfl @[simp, norm_cast] lemma intCast_re (n : ℤ) : (n : ℂ).re = n := rfl @[simp, norm_cast] lemma intCast_im (n : ℤ) : (n : ℂ).im = 0 := rfl @[simp, norm_cast] lemma re_nnratCast (q : ℚ≥0) : (q : ℂ).re = q := rfl @[simp, norm_cast] lemma im_nnratCast (q : ℚ≥0) : (q : ℂ).im = 0 := rfl @[simp, norm_cast] lemma ratCast_re (q : ℚ) : (q : ℂ).re = q := rfl @[simp, norm_cast] lemma ratCast_im (q : ℚ) : (q : ℂ).im = 0 := rfl @[deprecated (since := "2024-04-17")] alias rat_cast_im := ratCast_im @[norm_cast] lemma ofReal_nsmul (n : ℕ) (r : ℝ) : ↑(n • r) = n • (r : ℂ) := by simp @[norm_cast] lemma ofReal_zsmul (n : ℤ) (r : ℝ) : ↑(n • r) = n • (r : ℂ) := by simp /-! ### Complex conjugation -/ /-- This defines the complex conjugate as the `star` operation of the `StarRing ℂ`. It is recommended to use the ring endomorphism version `starRingEnd`, available under the notation `conj` in the locale `ComplexConjugate`. -/ instance : StarRing ℂ where star z := ⟨z.re, -z.im⟩ star_involutive x := by simp only [eta, neg_neg] star_mul a b := by ext <;> simp [add_comm] <;> ring star_add a b := by ext <;> simp [add_comm] @[simp] theorem conj_re (z : ℂ) : (conj z).re = z.re := rfl @[simp] theorem conj_im (z : ℂ) : (conj z).im = -z.im := rfl @[simp] theorem conj_ofReal (r : ℝ) : conj (r : ℂ) = r := Complex.ext_iff.2 <| by simp [star] @[simp] theorem conj_I : conj I = -I := Complex.ext_iff.2 <| by simp theorem conj_natCast (n : ℕ) : conj (n : ℂ) = n := map_natCast _ _ @[deprecated (since := "2024-04-17")] alias conj_nat_cast := conj_natCast -- See note [no_index around OfNat.ofNat] theorem conj_ofNat (n : ℕ) [n.AtLeastTwo] : conj (no_index (OfNat.ofNat n : ℂ)) = OfNat.ofNat n := map_ofNat _ _ -- @[simp] /- Porting note (#11119): `simp` attribute removed as the result could be proved by `simp only [@map_neg, Complex.conj_i, @neg_neg]` -/ theorem conj_neg_I : conj (-I) = I := Complex.ext_iff.2 <| by simp theorem conj_eq_iff_real {z : ℂ} : conj z = z ↔ ∃ r : ℝ, z = r := ⟨fun h => ⟨z.re, ext rfl <| eq_zero_of_neg_eq (congr_arg im h)⟩, fun ⟨h, e⟩ => by rw [e, conj_ofReal]⟩ theorem conj_eq_iff_re {z : ℂ} : conj z = z ↔ (z.re : ℂ) = z := conj_eq_iff_real.trans ⟨by rintro ⟨r, rfl⟩; simp [ofReal'], fun h => ⟨_, h.symm⟩⟩ theorem conj_eq_iff_im {z : ℂ} : conj z = z ↔ z.im = 0 := ⟨fun h => add_self_eq_zero.mp (neg_eq_iff_add_eq_zero.mp (congr_arg im h)), fun h => ext rfl (neg_eq_iff_add_eq_zero.mpr (add_self_eq_zero.mpr h))⟩ -- `simpNF` complains about this being provable by `RCLike.star_def` even -- though it's not imported by this file. -- Porting note: linter `simpNF` not found @[simp] theorem star_def : (Star.star : ℂ → ℂ) = conj := rfl /-! ### Norm squared -/ /-- The norm squared function. -/ @[pp_nodot] def normSq : ℂ →*₀ ℝ where toFun z := z.re * z.re + z.im * z.im map_zero' := by simp map_one' := by simp map_mul' z w := by dsimp ring theorem normSq_apply (z : ℂ) : normSq z = z.re * z.re + z.im * z.im := rfl @[simp] theorem normSq_ofReal (r : ℝ) : normSq r = r * r := by simp [normSq, ofReal'] @[simp] theorem normSq_natCast (n : ℕ) : normSq n = n * n := normSq_ofReal _ @[deprecated (since := "2024-04-17")] alias normSq_nat_cast := normSq_natCast @[simp] theorem normSq_intCast (z : ℤ) : normSq z = z * z := normSq_ofReal _ @[deprecated (since := "2024-04-17")] alias normSq_int_cast := normSq_intCast @[simp] theorem normSq_ratCast (q : ℚ) : normSq q = q * q := normSq_ofReal _ @[deprecated (since := "2024-04-17")] alias normSq_rat_cast := normSq_ratCast -- See note [no_index around OfNat.ofNat] @[simp] theorem normSq_ofNat (n : ℕ) [n.AtLeastTwo] : normSq (no_index (OfNat.ofNat n : ℂ)) = OfNat.ofNat n * OfNat.ofNat n := normSq_natCast _ @[simp] theorem normSq_mk (x y : ℝ) : normSq ⟨x, y⟩ = x * x + y * y := rfl theorem normSq_add_mul_I (x y : ℝ) : normSq (x + y * I) = x ^ 2 + y ^ 2 := by rw [← mk_eq_add_mul_I, normSq_mk, sq, sq] theorem normSq_eq_conj_mul_self {z : ℂ} : (normSq z : ℂ) = conj z * z := by ext <;> simp [normSq, mul_comm, ofReal'] -- @[simp] /- Porting note (#11119): `simp` attribute removed as linter reports this can be proved by `simp only [@map_zero]` -/ theorem normSq_zero : normSq 0 = 0 := normSq.map_zero -- @[simp] /- Porting note (#11119): `simp` attribute removed as linter reports this can be proved by `simp only [@map_one]` -/ theorem normSq_one : normSq 1 = 1 := normSq.map_one @[simp] theorem normSq_I : normSq I = 1 := by simp [normSq] theorem normSq_nonneg (z : ℂ) : 0 ≤ normSq z := add_nonneg (mul_self_nonneg _) (mul_self_nonneg _) theorem normSq_eq_zero {z : ℂ} : normSq z = 0 ↔ z = 0 := ⟨fun h => ext (eq_zero_of_mul_self_add_mul_self_eq_zero h) (eq_zero_of_mul_self_add_mul_self_eq_zero <| (add_comm _ _).trans h), fun h => h.symm ▸ normSq_zero⟩ @[simp] theorem normSq_pos {z : ℂ} : 0 < normSq z ↔ z ≠ 0 := (normSq_nonneg z).lt_iff_ne.trans <| not_congr (eq_comm.trans normSq_eq_zero) @[simp] theorem normSq_neg (z : ℂ) : normSq (-z) = normSq z := by simp [normSq] @[simp] theorem normSq_conj (z : ℂ) : normSq (conj z) = normSq z := by simp [normSq] theorem normSq_mul (z w : ℂ) : normSq (z * w) = normSq z * normSq w := normSq.map_mul z w theorem normSq_add (z w : ℂ) : normSq (z + w) = normSq z + normSq w + 2 * (z * conj w).re := by dsimp [normSq]; ring theorem re_sq_le_normSq (z : ℂ) : z.re * z.re ≤ normSq z := le_add_of_nonneg_right (mul_self_nonneg _) theorem im_sq_le_normSq (z : ℂ) : z.im * z.im ≤ normSq z := le_add_of_nonneg_left (mul_self_nonneg _) theorem mul_conj (z : ℂ) : z * conj z = normSq z := Complex.ext_iff.2 <| by simp [normSq, mul_comm, sub_eq_neg_add, add_comm, ofReal'] theorem add_conj (z : ℂ) : z + conj z = (2 * z.re : ℝ) := Complex.ext_iff.2 <| by simp [two_mul, ofReal'] /-- The coercion `ℝ → ℂ` as a `RingHom`. -/ def ofReal : ℝ →+* ℂ where toFun x := (x : ℂ) map_one' := ofReal_one map_zero' := ofReal_zero map_mul' := ofReal_mul map_add' := ofReal_add @[simp] theorem ofReal_eq_coe (r : ℝ) : ofReal r = r := rfl @[simp] theorem I_sq : I ^ 2 = -1 := by rw [sq, I_mul_I] @[simp] theorem I_pow_four : I ^ 4 = 1 := by rw [(by norm_num : 4 = 2 * 2), pow_mul, I_sq, neg_one_sq] @[simp] theorem sub_re (z w : ℂ) : (z - w).re = z.re - w.re := rfl @[simp] theorem sub_im (z w : ℂ) : (z - w).im = z.im - w.im := rfl @[simp, norm_cast] theorem ofReal_sub (r s : ℝ) : ((r - s : ℝ) : ℂ) = r - s := Complex.ext_iff.2 <| by simp [ofReal'] @[simp, norm_cast] theorem ofReal_pow (r : ℝ) (n : ℕ) : ((r ^ n : ℝ) : ℂ) = (r : ℂ) ^ n := by induction n <;> simp [*, ofReal_mul, pow_succ] theorem sub_conj (z : ℂ) : z - conj z = (2 * z.im : ℝ) * I := Complex.ext_iff.2 <| by simp [two_mul, sub_eq_add_neg, ofReal'] theorem normSq_sub (z w : ℂ) : normSq (z - w) = normSq z + normSq w - 2 * (z * conj w).re := by rw [sub_eq_add_neg, normSq_add] simp only [RingHom.map_neg, mul_neg, neg_re, normSq_neg] ring /-! ### Inversion -/ noncomputable instance : Inv ℂ := ⟨fun z => conj z * ((normSq z)⁻¹ : ℝ)⟩ theorem inv_def (z : ℂ) : z⁻¹ = conj z * ((normSq z)⁻¹ : ℝ) := rfl @[simp] theorem inv_re (z : ℂ) : z⁻¹.re = z.re / normSq z := by simp [inv_def, division_def, ofReal'] @[simp] theorem inv_im (z : ℂ) : z⁻¹.im = -z.im / normSq z := by simp [inv_def, division_def, ofReal'] @[simp, norm_cast] theorem ofReal_inv (r : ℝ) : ((r⁻¹ : ℝ) : ℂ) = (r : ℂ)⁻¹ := Complex.ext_iff.2 <| by simp [ofReal'] protected theorem inv_zero : (0⁻¹ : ℂ) = 0 := by rw [← ofReal_zero, ← ofReal_inv, inv_zero] protected theorem mul_inv_cancel {z : ℂ} (h : z ≠ 0) : z * z⁻¹ = 1 := by rw [inv_def, ← mul_assoc, mul_conj, ← ofReal_mul, mul_inv_cancel (mt normSq_eq_zero.1 h), ofReal_one] noncomputable instance instDivInvMonoid : DivInvMonoid ℂ where lemma div_re (z w : ℂ) : (z / w).re = z.re * w.re / normSq w + z.im * w.im / normSq w := by simp [div_eq_mul_inv, mul_assoc, sub_eq_add_neg] lemma div_im (z w : ℂ) : (z / w).im = z.im * w.re / normSq w - z.re * w.im / normSq w := by simp [div_eq_mul_inv, mul_assoc, sub_eq_add_neg, add_comm] /-! ### Field instance and lemmas -/ noncomputable instance instField : Field ℂ where mul_inv_cancel := @Complex.mul_inv_cancel inv_zero := Complex.inv_zero nnqsmul := (· • ·) qsmul := (· • ·) nnratCast_def q := by ext <;> simp [NNRat.cast_def, div_re, div_im, mul_div_mul_comm] ratCast_def q := by ext <;> simp [Rat.cast_def, div_re, div_im, mul_div_mul_comm] nnqsmul_def n z := Complex.ext_iff.2 <| by simp [NNRat.smul_def, smul_re, smul_im] qsmul_def n z := Complex.ext_iff.2 <| by simp [Rat.smul_def, smul_re, smul_im] @[simp, norm_cast] lemma ofReal_nnqsmul (q : ℚ≥0) (r : ℝ) : ofReal' (q • r) = q • r := by simp [NNRat.smul_def] @[simp, norm_cast] lemma ofReal_qsmul (q : ℚ) (r : ℝ) : ofReal' (q • r) = q • r := by simp [Rat.smul_def] theorem conj_inv (x : ℂ) : conj x⁻¹ = (conj x)⁻¹ := star_inv' _ @[simp, norm_cast] theorem ofReal_div (r s : ℝ) : ((r / s : ℝ) : ℂ) = r / s := map_div₀ ofReal r s @[simp, norm_cast] theorem ofReal_zpow (r : ℝ) (n : ℤ) : ((r ^ n : ℝ) : ℂ) = (r : ℂ) ^ n := map_zpow₀ ofReal r n @[simp] theorem div_I (z : ℂ) : z / I = -(z * I) := (div_eq_iff_mul_eq I_ne_zero).2 <| by simp [mul_assoc] @[simp] theorem inv_I : I⁻¹ = -I := by rw [inv_eq_one_div, div_I, one_mul] -- @[simp] /- Porting note (#11119): `simp` attribute removed as linter reports this can be proved by `simp only [@map_inv₀]` -/ theorem normSq_inv (z : ℂ) : normSq z⁻¹ = (normSq z)⁻¹ := map_inv₀ normSq z -- @[simp] /- Porting note (#11119): `simp` attribute removed as linter reports this can be proved by `simp only [@map_div₀]` -/ theorem normSq_div (z w : ℂ) : normSq (z / w) = normSq z / normSq w := map_div₀ normSq z w lemma div_ofReal (z : ℂ) (x : ℝ) : z / x = ⟨z.re / x, z.im / x⟩ := by simp_rw [div_eq_inv_mul, ← ofReal_inv, ofReal_mul'] lemma div_natCast (z : ℂ) (n : ℕ) : z / n = ⟨z.re / n, z.im / n⟩ := mod_cast div_ofReal z n @[deprecated (since := "2024-04-17")] alias div_nat_cast := div_natCast lemma div_intCast (z : ℂ) (n : ℤ) : z / n = ⟨z.re / n, z.im / n⟩ := mod_cast div_ofReal z n @[deprecated (since := "2024-04-17")] alias div_int_cast := div_intCast lemma div_ratCast (z : ℂ) (x : ℚ) : z / x = ⟨z.re / x, z.im / x⟩ := mod_cast div_ofReal z x @[deprecated (since := "2024-04-17")] alias div_rat_cast := div_ratCast lemma div_ofNat (z : ℂ) (n : ℕ) [n.AtLeastTwo] : z / OfNat.ofNat n = ⟨z.re / OfNat.ofNat n, z.im / OfNat.ofNat n⟩ := div_natCast z n @[simp] lemma div_ofReal_re (z : ℂ) (x : ℝ) : (z / x).re = z.re / x := by rw [div_ofReal] @[simp] lemma div_ofReal_im (z : ℂ) (x : ℝ) : (z / x).im = z.im / x := by rw [div_ofReal] @[simp] lemma div_natCast_re (z : ℂ) (n : ℕ) : (z / n).re = z.re / n := by rw [div_natCast] @[simp] lemma div_natCast_im (z : ℂ) (n : ℕ) : (z / n).im = z.im / n := by rw [div_natCast] @[simp] lemma div_intCast_re (z : ℂ) (n : ℤ) : (z / n).re = z.re / n := by rw [div_intCast] @[simp] lemma div_intCast_im (z : ℂ) (n : ℤ) : (z / n).im = z.im / n := by rw [div_intCast] @[simp] lemma div_ratCast_re (z : ℂ) (x : ℚ) : (z / x).re = z.re / x := by rw [div_ratCast] @[simp] lemma div_ratCast_im (z : ℂ) (x : ℚ) : (z / x).im = z.im / x := by rw [div_ratCast] @[deprecated (since := "2024-04-17")] alias div_rat_cast_im := div_ratCast_im @[simp] lemma div_ofNat_re (z : ℂ) (n : ℕ) [n.AtLeastTwo] : (z / no_index (OfNat.ofNat n)).re = z.re / OfNat.ofNat n := div_natCast_re z n @[simp] lemma div_ofNat_im (z : ℂ) (n : ℕ) [n.AtLeastTwo] : (z / no_index (OfNat.ofNat n)).im = z.im / OfNat.ofNat n := div_natCast_im z n /-! ### Characteristic zero -/ instance instCharZero : CharZero ℂ := charZero_of_inj_zero fun n h => by rwa [← ofReal_natCast, ofReal_eq_zero, Nat.cast_eq_zero] at h /-- A complex number `z` plus its conjugate `conj z` is `2` times its real part. -/ theorem re_eq_add_conj (z : ℂ) : (z.re : ℂ) = (z + conj z) / 2 := by simp only [add_conj, ofReal_mul, ofReal_ofNat, mul_div_cancel_left₀ (z.re : ℂ) two_ne_zero] /-- A complex number `z` minus its conjugate `conj z` is `2i` times its imaginary part. -/ theorem im_eq_sub_conj (z : ℂ) : (z.im : ℂ) = (z - conj z) / (2 * I) := by simp only [sub_conj, ofReal_mul, ofReal_ofNat, mul_right_comm, mul_div_cancel_left₀ _ (mul_ne_zero two_ne_zero I_ne_zero : 2 * I ≠ 0)] /-- Show the imaginary number ⟨x, y⟩ as an "x + y*I" string Note that the Real numbers used for x and y will show as cauchy sequences due to the way Real numbers are represented. -/ unsafe instance instRepr : Repr ℂ where reprPrec f p := (if p > 65 then (Std.Format.bracket "(" · ")") else (·)) <| reprPrec f.re 65 ++ " + " ++ reprPrec f.im 70 ++ "*I" end Complex assert_not_exists Multiset assert_not_exists Algebra
Data\Complex\BigOperators.lean
/- Copyright (c) 2017 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, Mario Carneiro -/ import Mathlib.Algebra.BigOperators.Group.Finset import Mathlib.Data.Complex.Basic /-! # Finite sums and products of complex numbers -/ namespace Complex variable {α : Type*} (s : Finset α) @[simp, norm_cast] theorem ofReal_prod (f : α → ℝ) : ((∏ i ∈ s, f i : ℝ) : ℂ) = ∏ i ∈ s, (f i : ℂ) := map_prod ofReal _ _ @[simp, norm_cast] theorem ofReal_sum (f : α → ℝ) : ((∑ i ∈ s, f i : ℝ) : ℂ) = ∑ i ∈ s, (f i : ℂ) := map_sum ofReal _ _ @[simp] theorem re_sum (f : α → ℂ) : (∑ i ∈ s, f i).re = ∑ i ∈ s, (f i).re := map_sum reAddGroupHom f s @[simp] theorem im_sum (f : α → ℂ) : (∑ i ∈ s, f i).im = ∑ i ∈ s, (f i).im := map_sum imAddGroupHom f s end Complex
Data\Complex\Cardinality.lean
/- Copyright (c) 2022 Violeta Hernández Palacios. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Violeta Hernández Palacios -/ import Mathlib.Data.Complex.Basic import Mathlib.Data.Real.Cardinality /-! # The cardinality of the complex numbers This file shows that the complex numbers have cardinality continuum, i.e. `#ℂ = 𝔠`. -/ -- Porting note: the lemmas `mk_complex` and `mk_univ_complex` should be in the namespace `Cardinal` -- like their real counterparts. open Cardinal Set open Cardinal /-- The cardinality of the complex numbers, as a type. -/ @[simp] theorem mk_complex : #ℂ = 𝔠 := by rw [mk_congr Complex.equivRealProd, mk_prod, lift_id, mk_real, continuum_mul_self] /-- The cardinality of the complex numbers, as a set. -/ -- @[simp] -- Porting note (#10618): simp can prove this theorem mk_univ_complex : #(Set.univ : Set ℂ) = 𝔠 := by rw [mk_univ, mk_complex] /-- The complex numbers are not countable. -/ theorem not_countable_complex : ¬(Set.univ : Set ℂ).Countable := by rw [← le_aleph0_iff_set_countable, not_le, mk_univ_complex] apply cantor
Data\Complex\Determinant.lean
/- Copyright (c) 2022 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers -/ import Mathlib.Data.Complex.Module import Mathlib.LinearAlgebra.Determinant /-! # Determinants of maps in the complex numbers as a vector space over `ℝ` This file provides results about the determinants of maps in the complex numbers as a vector space over `ℝ`. -/ namespace Complex /-- The determinant of `conjAe`, as a linear map. -/ @[simp] theorem det_conjAe : LinearMap.det conjAe.toLinearMap = -1 := by rw [← LinearMap.det_toMatrix basisOneI, toMatrix_conjAe, Matrix.det_fin_two_of] simp /-- The determinant of `conjAe`, as a linear equiv. -/ @[simp] theorem linearEquiv_det_conjAe : LinearEquiv.det conjAe.toLinearEquiv = -1 := by rw [← Units.eq_iff, LinearEquiv.coe_det, AlgEquiv.toLinearEquiv_toLinearMap, det_conjAe, Units.coe_neg_one] end Complex
Data\Complex\Exponential.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 Mathlib.Algebra.Order.CauSeq.BigOperators import Mathlib.Algebra.Star.Order import Mathlib.Data.Complex.Abs import Mathlib.Data.Complex.BigOperators import Mathlib.Data.Nat.Choose.Sum import Mathlib.Tactic.Bound.Attribute /-! # 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. -/ open CauSeq Finset IsAbsoluteValue open scoped ComplexConjugate namespace Complex theorem isCauSeq_abs_exp (z : ℂ) : IsCauSeq _root_.abs fun n => ∑ m ∈ range n, abs (z ^ m / m.factorial) := let ⟨n, hn⟩ := exists_nat_gt (abs z) have hn0 : (0 : ℝ) < n := lt_of_le_of_lt (abs.nonneg _) hn IsCauSeq.series_ratio_test n (abs z / n) (div_nonneg (abs.nonneg _) (le_of_lt hn0)) (by rwa [div_lt_iff hn0, one_mul]) fun m hm => by rw [abs_abs, abs_abs, Nat.factorial_succ, pow_succ', mul_comm m.succ, Nat.cast_mul, ← div_div, mul_div_assoc, mul_div_right_comm, map_mul, map_div₀, abs_natCast] gcongr exact le_trans hm (Nat.le_succ _) noncomputable section theorem isCauSeq_exp (z : ℂ) : IsCauSeq abs fun n => ∑ m ∈ range n, z ^ m / m.factorial := (isCauSeq_abs_exp z).of_abv /-- The Cauchy sequence consisting of partial sums of the Taylor series of the complex exponential function -/ @[pp_nodot] def exp' (z : ℂ) : CauSeq ℂ Complex.abs := ⟨fun n => ∑ m ∈ range n, z ^ m / m.factorial, isCauSeq_exp z⟩ /-- The complex exponential function, defined via its Taylor series -/ -- Porting note: removed `irreducible` attribute, so I can prove things @[pp_nodot] def exp (z : ℂ) : ℂ := CauSeq.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 cotangent function, defined as `cos z / sin z` -/ def cot (z : ℂ) : ℂ := cos z / sin 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 /-- scoped notation for the complex exponential function -/ scoped notation "cexp" => Complex.exp end end Complex namespace Real open Complex noncomputable section /-- The real exponential function, defined as the real part of the complex exponential -/ @[pp_nodot] nonrec def exp (x : ℝ) : ℝ := (exp x).re /-- The real sine function, defined as the real part of the complex sine -/ @[pp_nodot] nonrec def sin (x : ℝ) : ℝ := (sin x).re /-- The real cosine function, defined as the real part of the complex cosine -/ @[pp_nodot] nonrec def cos (x : ℝ) : ℝ := (cos x).re /-- The real tangent function, defined as the real part of the complex tangent -/ @[pp_nodot] nonrec def tan (x : ℝ) : ℝ := (tan x).re /-- The real cotangent function, defined as the real part of the complex cotangent -/ nonrec def cot (x : ℝ) : ℝ := (cot x).re /-- The real hypebolic sine function, defined as the real part of the complex hyperbolic sine -/ @[pp_nodot] nonrec def sinh (x : ℝ) : ℝ := (sinh x).re /-- The real hypebolic cosine function, defined as the real part of the complex hyperbolic cosine -/ @[pp_nodot] nonrec def cosh (x : ℝ) : ℝ := (cosh x).re /-- The real hypebolic tangent function, defined as the real part of the complex hyperbolic tangent -/ @[pp_nodot] nonrec def tanh (x : ℝ) : ℝ := (tanh x).re /-- scoped notation for the real exponential function -/ scoped notation "rexp" => Real.exp end end Real namespace Complex variable (x y : ℂ) @[simp] theorem exp_zero : exp 0 = 1 := by rw [exp] refine lim_eq_of_equiv_const fun ε ε0 => ⟨1, fun j hj => ?_⟩ convert (config := .unfoldSameFun) ε0 -- Porting note: ε0 : ε > 0 but goal is _ < ε cases' j with j j · exact absurd hj (not_le_of_gt zero_lt_one) · dsimp [exp'] induction' j with j ih · dsimp [exp']; simp [show Nat.succ 0 = 1 from rfl] · rw [← ih (by simp [Nat.succ_le_succ])] simp only [sum_range_succ, pow_succ] simp theorem exp_add : exp (x + y) = exp x * exp y := by have hj : ∀ j : ℕ, (∑ m ∈ range j, (x + y) ^ m / m.factorial) = ∑ i ∈ range j, ∑ k ∈ range (i + 1), x ^ k / k.factorial * (y ^ (i - k) / (i - k).factorial) := by intro j refine Finset.sum_congr rfl fun m _ => ?_ rw [add_pow, div_eq_mul_inv, sum_mul] refine Finset.sum_congr rfl fun 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] simp_rw [exp, exp', lim_mul_lim] apply (lim_eq_lim_of_equiv _).symm simp only [hj] exact cauchy_product (isCauSeq_abs_exp x) (isCauSeq_exp y) -- Porting note (#11445): new definition /-- the exponential function as a monoid hom from `Multiplicative ℂ` to `ℂ` -/ noncomputable def expMonoidHom : MonoidHom (Multiplicative ℂ) ℂ := { toFun := fun z => exp (Multiplicative.toAdd z), map_one' := by simp, map_mul' := by simp [exp_add] } theorem exp_list_sum (l : List ℂ) : exp l.sum = (l.map exp).prod := map_list_prod (M := Multiplicative ℂ) expMonoidHom l theorem exp_multiset_sum (s : Multiset ℂ) : exp s.sum = (s.map exp).prod := @MonoidHom.map_multiset_prod (Multiplicative ℂ) ℂ _ _ expMonoidHom s theorem exp_sum {α : Type*} (s : Finset α) (f : α → ℂ) : exp (∑ x ∈ s, f x) = ∏ x ∈ s, exp (f x) := map_prod (β := Multiplicative ℂ) expMonoidHom f s lemma exp_nsmul (x : ℂ) (n : ℕ) : exp (n • x) = exp x ^ n := @MonoidHom.map_pow (Multiplicative ℂ) ℂ _ _ expMonoidHom _ _ theorem 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 _ n, one_mul] @[simp] theorem exp_ne_zero : exp x ≠ 0 := fun h => zero_ne_one <| by rw [← exp_zero, ← add_neg_self x, exp_add, h]; simp theorem 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)] theorem exp_sub : exp (x - y) = exp x / exp y := by simp [sub_eq_add_neg, exp_add, exp_neg, div_eq_mul_inv] theorem exp_int_mul (z : ℂ) (n : ℤ) : Complex.exp (n * z) = Complex.exp z ^ n := by cases n · simp [exp_nat_mul] · simp [exp_add, add_mul, pow_add, exp_neg, exp_nat_mul] @[simp] theorem exp_conj : exp (conj x) = conj (exp x) := by dsimp [exp] rw [← lim_conj] refine congr_arg CauSeq.lim (CauSeq.ext fun _ => ?_) dsimp [exp', Function.comp_def, cauSeqConj] rw [map_sum (starRingEnd _)] refine sum_congr rfl fun n _ => ?_ rw [map_div₀, map_pow, ← ofReal_natCast, conj_ofReal] @[simp] theorem ofReal_exp_ofReal_re (x : ℝ) : ((exp x).re : ℂ) = exp x := conj_eq_iff_re.1 <| by rw [← exp_conj, conj_ofReal] @[simp, norm_cast] theorem ofReal_exp (x : ℝ) : (Real.exp x : ℂ) = exp x := ofReal_exp_ofReal_re _ @[simp] theorem exp_ofReal_im (x : ℝ) : (exp x).im = 0 := by rw [← ofReal_exp_ofReal_re, ofReal_im] theorem exp_ofReal_re (x : ℝ) : (exp x).re = Real.exp x := rfl theorem two_sinh : 2 * sinh x = exp x - exp (-x) := mul_div_cancel₀ _ two_ne_zero theorem two_cosh : 2 * cosh x = exp x + exp (-x) := mul_div_cancel₀ _ two_ne_zero @[simp] theorem sinh_zero : sinh 0 = 0 := by simp [sinh] @[simp] theorem sinh_neg : sinh (-x) = -sinh x := by simp [sinh, exp_neg, (neg_div _ _).symm, add_mul] private theorem sinh_add_aux {a b c d : ℂ} : (a - b) * (c + d) + (a + b) * (c - d) = 2 * (a * c - b * d) := by ring theorem sinh_add : sinh (x + y) = sinh x * cosh y + cosh x * sinh y := by 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 @[simp] theorem cosh_zero : cosh 0 = 1 := by simp [cosh] @[simp] theorem cosh_neg : cosh (-x) = cosh x := by simp [add_comm, cosh, exp_neg] private theorem cosh_add_aux {a b c d : ℂ} : (a + b) * (c + d) + (a - b) * (c - d) = 2 * (a * c + b * d) := by ring theorem cosh_add : cosh (x + y) = cosh x * cosh y + sinh x * sinh y := by 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 theorem 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] theorem 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] theorem sinh_conj : sinh (conj x) = conj (sinh x) := by rw [sinh, ← RingHom.map_neg, exp_conj, exp_conj, ← RingHom.map_sub, sinh, map_div₀] -- Porting note: not nice simp [← one_add_one_eq_two] @[simp] theorem ofReal_sinh_ofReal_re (x : ℝ) : ((sinh x).re : ℂ) = sinh x := conj_eq_iff_re.1 <| by rw [← sinh_conj, conj_ofReal] @[simp, norm_cast] theorem ofReal_sinh (x : ℝ) : (Real.sinh x : ℂ) = sinh x := ofReal_sinh_ofReal_re _ @[simp] theorem sinh_ofReal_im (x : ℝ) : (sinh x).im = 0 := by rw [← ofReal_sinh_ofReal_re, ofReal_im] theorem sinh_ofReal_re (x : ℝ) : (sinh x).re = Real.sinh x := rfl theorem cosh_conj : cosh (conj x) = conj (cosh x) := by rw [cosh, ← RingHom.map_neg, exp_conj, exp_conj, ← RingHom.map_add, cosh, map_div₀] -- Porting note: not nice simp [← one_add_one_eq_two] theorem ofReal_cosh_ofReal_re (x : ℝ) : ((cosh x).re : ℂ) = cosh x := conj_eq_iff_re.1 <| by rw [← cosh_conj, conj_ofReal] @[simp, norm_cast] theorem ofReal_cosh (x : ℝ) : (Real.cosh x : ℂ) = cosh x := ofReal_cosh_ofReal_re _ @[simp] theorem cosh_ofReal_im (x : ℝ) : (cosh x).im = 0 := by rw [← ofReal_cosh_ofReal_re, ofReal_im] @[simp] theorem cosh_ofReal_re (x : ℝ) : (cosh x).re = Real.cosh x := rfl theorem tanh_eq_sinh_div_cosh : tanh x = sinh x / cosh x := rfl @[simp] theorem tanh_zero : tanh 0 = 0 := by simp [tanh] @[simp] theorem tanh_neg : tanh (-x) = -tanh x := by simp [tanh, neg_div] theorem tanh_conj : tanh (conj x) = conj (tanh x) := by rw [tanh, sinh_conj, cosh_conj, ← map_div₀, tanh] @[simp] theorem ofReal_tanh_ofReal_re (x : ℝ) : ((tanh x).re : ℂ) = tanh x := conj_eq_iff_re.1 <| by rw [← tanh_conj, conj_ofReal] @[simp, norm_cast] theorem ofReal_tanh (x : ℝ) : (Real.tanh x : ℂ) = tanh x := ofReal_tanh_ofReal_re _ @[simp] theorem tanh_ofReal_im (x : ℝ) : (tanh x).im = 0 := by rw [← ofReal_tanh_ofReal_re, ofReal_im] theorem tanh_ofReal_re (x : ℝ) : (tanh x).re = Real.tanh x := rfl @[simp] theorem 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] @[simp] theorem sinh_add_cosh : sinh x + cosh x = exp x := by rw [add_comm, cosh_add_sinh] @[simp] theorem exp_sub_cosh : exp x - cosh x = sinh x := sub_eq_iff_eq_add.2 (sinh_add_cosh x).symm @[simp] theorem exp_sub_sinh : exp x - sinh x = cosh x := sub_eq_iff_eq_add.2 (cosh_add_sinh x).symm @[simp] theorem 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] @[simp] theorem sinh_sub_cosh : sinh x - cosh x = -exp (-x) := by rw [← neg_sub, cosh_sub_sinh] @[simp] theorem 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] theorem cosh_sq : cosh x ^ 2 = sinh x ^ 2 + 1 := by rw [← cosh_sq_sub_sinh_sq x] ring theorem sinh_sq : sinh x ^ 2 = cosh x ^ 2 - 1 := by rw [← cosh_sq_sub_sinh_sq x] ring theorem cosh_two_mul : cosh (2 * x) = cosh x ^ 2 + sinh x ^ 2 := by rw [two_mul, cosh_add, sq, sq] theorem sinh_two_mul : sinh (2 * x) = 2 * sinh x * cosh x := by rw [two_mul, sinh_add] ring theorem cosh_three_mul : cosh (3 * x) = 4 * cosh x ^ 3 - 3 * cosh x := by 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_sq] ring theorem sinh_three_mul : sinh (3 * x) = 4 * sinh x ^ 3 + 3 * sinh x := by 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_sq] ring @[simp] theorem sin_zero : sin 0 = 0 := by simp [sin] @[simp] theorem sin_neg : sin (-x) = -sin x := by simp [sin, sub_eq_add_neg, exp_neg, (neg_div _ _).symm, add_mul] theorem two_sin : 2 * sin x = (exp (-x * I) - exp (x * I)) * I := mul_div_cancel₀ _ two_ne_zero theorem two_cos : 2 * cos x = exp (x * I) + exp (-x * I) := mul_div_cancel₀ _ two_ne_zero theorem 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] theorem 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] theorem tanh_mul_I : tanh (x * I) = tan x * I := by rw [tanh_eq_sinh_div_cosh, cosh_mul_I, sinh_mul_I, mul_div_right_comm, tan] theorem cos_mul_I : cos (x * I) = cosh x := by rw [← cosh_mul_I]; ring_nf; simp theorem sin_mul_I : sin (x * I) = sinh x * I := by have h : I * sin (x * I) = -sinh x := by rw [mul_comm, ← sinh_mul_I] ring_nf simp rw [← neg_neg (sinh x), ← h] apply Complex.ext <;> simp theorem tan_mul_I : tan (x * I) = tanh x * I := by rw [tan, sin_mul_I, cos_mul_I, mul_div_right_comm, tanh_eq_sinh_div_cosh] theorem 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] theorem cos_zero : cos 0 = 1 := by simp [cos] @[simp] theorem cos_neg : cos (-x) = cos x := by simp [cos, sub_eq_add_neg, exp_neg, add_comm] private theorem cos_add_aux {a b c d : ℂ} : (a + b) * (c + d) - (b - a) * (d - c) * -1 = 2 * (a * c + b * d) := by ring theorem 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] theorem 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] theorem 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_add_mul_I (x y : ℂ) : sin (x + y * I) = sin x * cosh y + cos x * sinh y * I := by rw [sin_add, cos_mul_I, sin_mul_I, mul_assoc] theorem sin_eq (z : ℂ) : sin z = sin z.re * cosh z.im + cos z.re * sinh z.im * I := by convert sin_add_mul_I z.re z.im; exact (re_add_im z).symm theorem cos_add_mul_I (x y : ℂ) : cos (x + y * I) = cos x * cosh y - sin x * sinh y * I := by rw [cos_add, cos_mul_I, sin_mul_I, mul_assoc] theorem cos_eq (z : ℂ) : cos z = cos z.re * cosh z.im - sin z.re * sinh z.im * I := by convert cos_add_mul_I z.re z.im; exact (re_add_im z).symm theorem sin_sub_sin : sin x - sin y = 2 * sin ((x - y) / 2) * cos ((x + y) / 2) := by 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_right, add_self_div_two] at s1 rw [div_sub_div_same, ← sub_add, add_sub_cancel_left, add_self_div_two] at s2 rw [s1, s2] ring theorem cos_sub_cos : cos x - cos y = -2 * sin ((x + y) / 2) * sin ((x - y) / 2) := by 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_right, add_self_div_two] at s1 rw [div_sub_div_same, ← sub_add, add_sub_cancel_left, add_self_div_two] at s2 rw [s1, s2] ring theorem sin_add_sin : sin x + sin y = 2 * sin ((x + y) / 2) * cos ((x - y) / 2) := by simpa using sin_sub_sin x (-y) theorem cos_add_cos : cos x + cos y = 2 * cos ((x + y) / 2) * cos ((x - y) / 2) := by 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 · rw [cos_add, cos_sub] ring theorem sin_conj : sin (conj x) = conj (sin x) := by rw [← mul_left_inj' I_ne_zero, ← sinh_mul_I, ← conj_neg_I, ← RingHom.map_mul, ← RingHom.map_mul, sinh_conj, mul_neg, sinh_neg, sinh_mul_I, mul_neg] @[simp] theorem ofReal_sin_ofReal_re (x : ℝ) : ((sin x).re : ℂ) = sin x := conj_eq_iff_re.1 <| by rw [← sin_conj, conj_ofReal] @[simp, norm_cast] theorem ofReal_sin (x : ℝ) : (Real.sin x : ℂ) = sin x := ofReal_sin_ofReal_re _ @[simp] theorem sin_ofReal_im (x : ℝ) : (sin x).im = 0 := by rw [← ofReal_sin_ofReal_re, ofReal_im] theorem sin_ofReal_re (x : ℝ) : (sin x).re = Real.sin x := rfl theorem cos_conj : cos (conj x) = conj (cos x) := by rw [← cosh_mul_I, ← conj_neg_I, ← RingHom.map_mul, ← cosh_mul_I, cosh_conj, mul_neg, cosh_neg] @[simp] theorem ofReal_cos_ofReal_re (x : ℝ) : ((cos x).re : ℂ) = cos x := conj_eq_iff_re.1 <| by rw [← cos_conj, conj_ofReal] @[simp, norm_cast] theorem ofReal_cos (x : ℝ) : (Real.cos x : ℂ) = cos x := ofReal_cos_ofReal_re _ @[simp] theorem cos_ofReal_im (x : ℝ) : (cos x).im = 0 := by rw [← ofReal_cos_ofReal_re, ofReal_im] theorem cos_ofReal_re (x : ℝ) : (cos x).re = Real.cos x := rfl @[simp] theorem tan_zero : tan 0 = 0 := by simp [tan] theorem tan_eq_sin_div_cos : tan x = sin x / cos x := rfl theorem cot_eq_cos_div_sin : cot x = cos x / sin x := rfl theorem 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] theorem tan_neg : tan (-x) = -tan x := by simp [tan, neg_div] theorem tan_conj : tan (conj x) = conj (tan x) := by rw [tan, sin_conj, cos_conj, ← map_div₀, tan] theorem cot_conj : cot (conj x) = conj (cot x) := by rw [cot, sin_conj, cos_conj, ← map_div₀, cot] @[simp] theorem ofReal_tan_ofReal_re (x : ℝ) : ((tan x).re : ℂ) = tan x := conj_eq_iff_re.1 <| by rw [← tan_conj, conj_ofReal] @[simp] theorem ofReal_cot_ofReal_re (x : ℝ) : ((cot x).re : ℂ) = cot x := conj_eq_iff_re.1 <| by rw [← cot_conj, conj_ofReal] @[simp, norm_cast] theorem ofReal_tan (x : ℝ) : (Real.tan x : ℂ) = tan x := ofReal_tan_ofReal_re _ @[simp, norm_cast] theorem ofReal_cot (x : ℝ) : (Real.cot x : ℂ) = cot x := ofReal_cot_ofReal_re _ @[simp] theorem tan_ofReal_im (x : ℝ) : (tan x).im = 0 := by rw [← ofReal_tan_ofReal_re, ofReal_im] theorem tan_ofReal_re (x : ℝ) : (tan x).re = Real.tan x := rfl theorem cos_add_sin_I : cos x + sin x * I = exp (x * I) := by rw [← cosh_add_sinh, sinh_mul_I, cosh_mul_I] theorem cos_sub_sin_I : cos x - sin x * I = exp (-x * I) := by rw [neg_mul, ← cosh_sub_sinh, sinh_mul_I, cosh_mul_I] @[simp] theorem 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] theorem cos_sq_add_sin_sq : cos x ^ 2 + sin x ^ 2 = 1 := by rw [add_comm, sin_sq_add_cos_sq] theorem cos_two_mul' : cos (2 * x) = cos x ^ 2 - sin x ^ 2 := by rw [two_mul, cos_add, ← sq, ← sq] theorem 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] theorem sin_two_mul : sin (2 * x) = 2 * sin x * cos x := by rw [two_mul, sin_add, two_mul, add_mul, mul_comm] theorem cos_sq : 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] theorem cos_sq' : cos x ^ 2 = 1 - sin x ^ 2 := by rw [← sin_sq_add_cos_sq x, add_sub_cancel_left] theorem sin_sq : sin x ^ 2 = 1 - cos x ^ 2 := by rw [← sin_sq_add_cos_sq x, add_sub_cancel_right] theorem inv_one_add_tan_sq {x : ℂ} (hx : cos x ≠ 0) : (1 + tan x ^ 2)⁻¹ = cos x ^ 2 := by rw [tan_eq_sin_div_cos, div_pow] field_simp theorem 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] theorem cos_three_mul : cos (3 * x) = 4 * cos x ^ 3 - 3 * cos x := by 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, sq] have h2 : 4 * cos x ^ 3 = 2 * cos x * cos x * cos x + 2 * cos x * cos x ^ 2 := by ring rw [h2, cos_sq'] ring theorem sin_three_mul : sin (3 * x) = 3 * sin x - 4 * sin x ^ 3 := by 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_sq'] have h2 : cos x * (2 * sin x * cos x) = 2 * sin x * cos x ^ 2 := by ring rw [h2, cos_sq'] ring theorem exp_mul_I : exp (x * I) = cos x + sin x * I := (cos_add_sin_I _).symm theorem exp_add_mul_I : exp (x + y * I) = exp x * (cos y + sin y * I) := by rw [exp_add, exp_mul_I] theorem 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] theorem exp_re : (exp x).re = Real.exp x.re * Real.cos x.im := by rw [exp_eq_exp_re_mul_sin_add_cos] simp [exp_ofReal_re, cos_ofReal_re] theorem exp_im : (exp x).im = Real.exp x.re * Real.sin x.im := by rw [exp_eq_exp_re_mul_sin_add_cos] simp [exp_ofReal_re, sin_ofReal_re] @[simp] theorem exp_ofReal_mul_I_re (x : ℝ) : (exp (x * I)).re = Real.cos x := by simp [exp_mul_I, cos_ofReal_re] @[simp] theorem exp_ofReal_mul_I_im (x : ℝ) : (exp (x * I)).im = Real.sin x := by simp [exp_mul_I, sin_ofReal_re] /-- **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 := by 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 Complex namespace Real open Complex variable (x y : ℝ) @[simp] theorem exp_zero : exp 0 = 1 := by simp [Real.exp] nonrec theorem exp_add : exp (x + y) = exp x * exp y := by simp [exp_add, exp] -- Porting note (#11445): new definition /-- the exponential function as a monoid hom from `Multiplicative ℝ` to `ℝ` -/ noncomputable def expMonoidHom : MonoidHom (Multiplicative ℝ) ℝ := { toFun := fun x => exp (Multiplicative.toAdd x), map_one' := by simp, map_mul' := by simp [exp_add] } theorem exp_list_sum (l : List ℝ) : exp l.sum = (l.map exp).prod := map_list_prod (M := Multiplicative ℝ) expMonoidHom l theorem exp_multiset_sum (s : Multiset ℝ) : exp s.sum = (s.map exp).prod := @MonoidHom.map_multiset_prod (Multiplicative ℝ) ℝ _ _ expMonoidHom s theorem exp_sum {α : Type*} (s : Finset α) (f : α → ℝ) : exp (∑ x ∈ s, f x) = ∏ x ∈ s, exp (f x) := map_prod (β := Multiplicative ℝ) expMonoidHom f s lemma exp_nsmul (x : ℝ) (n : ℕ) : exp (n • x) = exp x ^ n := @MonoidHom.map_pow (Multiplicative ℝ) ℝ _ _ expMonoidHom _ _ nonrec theorem exp_nat_mul (x : ℝ) (n : ℕ) : exp (n * x) = exp x ^ n := ofReal_injective (by simp [exp_nat_mul]) @[simp] nonrec theorem exp_ne_zero : exp x ≠ 0 := fun h => exp_ne_zero x <| by rw [exp, ← ofReal_inj] at h; simp_all nonrec theorem exp_neg : exp (-x) = (exp x)⁻¹ := ofReal_injective <| by simp [exp_neg] theorem exp_sub : exp (x - y) = exp x / exp y := by simp [sub_eq_add_neg, exp_add, exp_neg, div_eq_mul_inv] @[simp] theorem sin_zero : sin 0 = 0 := by simp [sin] @[simp] theorem sin_neg : sin (-x) = -sin x := by simp [sin, exp_neg, (neg_div _ _).symm, add_mul] nonrec theorem sin_add : sin (x + y) = sin x * cos y + cos x * sin y := ofReal_injective <| by simp [sin_add] @[simp] theorem cos_zero : cos 0 = 1 := by simp [cos] @[simp] theorem cos_neg : cos (-x) = cos x := by simp [cos, exp_neg] @[simp] theorem cos_abs : cos |x| = cos x := by cases le_total x 0 <;> simp only [*, _root_.abs_of_nonneg, abs_of_nonpos, cos_neg] nonrec theorem cos_add : cos (x + y) = cos x * cos y - sin x * sin y := ofReal_injective <| by simp [cos_add] theorem 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] theorem 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] nonrec theorem sin_sub_sin : sin x - sin y = 2 * sin ((x - y) / 2) * cos ((x + y) / 2) := ofReal_injective <| by simp [sin_sub_sin] nonrec theorem cos_sub_cos : cos x - cos y = -2 * sin ((x + y) / 2) * sin ((x - y) / 2) := ofReal_injective <| by simp [cos_sub_cos] nonrec theorem cos_add_cos : cos x + cos y = 2 * cos ((x + y) / 2) * cos ((x - y) / 2) := ofReal_injective <| by simp [cos_add_cos] nonrec theorem tan_eq_sin_div_cos : tan x = sin x / cos x := ofReal_injective <| by simp only [ofReal_tan, tan_eq_sin_div_cos, ofReal_div, ofReal_sin, ofReal_cos] nonrec theorem cot_eq_cos_div_sin : cot x = cos x / sin x := ofReal_injective <| by simp [cot_eq_cos_div_sin] theorem 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] theorem tan_zero : tan 0 = 0 := by simp [tan] @[simp] theorem tan_neg : tan (-x) = -tan x := by simp [tan, neg_div] @[simp] nonrec theorem sin_sq_add_cos_sq : sin x ^ 2 + cos x ^ 2 = 1 := ofReal_injective (by simp [sin_sq_add_cos_sq]) @[simp] theorem cos_sq_add_sin_sq : cos x ^ 2 + sin x ^ 2 = 1 := by rw [add_comm, sin_sq_add_cos_sq] theorem sin_sq_le_one : sin x ^ 2 ≤ 1 := by rw [← sin_sq_add_cos_sq x]; exact le_add_of_nonneg_right (sq_nonneg _) theorem cos_sq_le_one : cos x ^ 2 ≤ 1 := by rw [← sin_sq_add_cos_sq x]; exact le_add_of_nonneg_left (sq_nonneg _) theorem abs_sin_le_one : |sin x| ≤ 1 := abs_le_one_iff_mul_self_le_one.2 <| by simp only [← sq, sin_sq_le_one] theorem abs_cos_le_one : |cos x| ≤ 1 := abs_le_one_iff_mul_self_le_one.2 <| by simp only [← sq, cos_sq_le_one] theorem sin_le_one : sin x ≤ 1 := (abs_le.1 (abs_sin_le_one _)).2 theorem cos_le_one : cos x ≤ 1 := (abs_le.1 (abs_cos_le_one _)).2 theorem neg_one_le_sin : -1 ≤ sin x := (abs_le.1 (abs_sin_le_one _)).1 theorem neg_one_le_cos : -1 ≤ cos x := (abs_le.1 (abs_cos_le_one _)).1 nonrec theorem cos_two_mul : cos (2 * x) = 2 * cos x ^ 2 - 1 := ofReal_injective <| by simp [cos_two_mul] nonrec theorem cos_two_mul' : cos (2 * x) = cos x ^ 2 - sin x ^ 2 := ofReal_injective <| by simp [cos_two_mul'] nonrec theorem sin_two_mul : sin (2 * x) = 2 * sin x * cos x := ofReal_injective <| by simp [sin_two_mul] nonrec theorem cos_sq : cos x ^ 2 = 1 / 2 + cos (2 * x) / 2 := ofReal_injective <| by simp [cos_sq] theorem cos_sq' : cos x ^ 2 = 1 - sin x ^ 2 := by rw [← sin_sq_add_cos_sq x, add_sub_cancel_left] theorem sin_sq : sin x ^ 2 = 1 - cos x ^ 2 := eq_sub_iff_add_eq.2 <| sin_sq_add_cos_sq _ lemma sin_sq_eq_half_sub : sin x ^ 2 = 1 / 2 - cos (2 * x) / 2 := by rw [sin_sq, cos_sq, ← sub_sub, sub_half] theorem abs_sin_eq_sqrt_one_sub_cos_sq (x : ℝ) : |sin x| = √(1 - cos x ^ 2) := by rw [← sin_sq, sqrt_sq_eq_abs] theorem abs_cos_eq_sqrt_one_sub_sin_sq (x : ℝ) : |cos x| = √(1 - sin x ^ 2) := by rw [← cos_sq', sqrt_sq_eq_abs] theorem inv_one_add_tan_sq {x : ℝ} (hx : cos x ≠ 0) : (1 + tan x ^ 2)⁻¹ = cos x ^ 2 := have : Complex.cos x ≠ 0 := mt (congr_arg re) hx ofReal_inj.1 <| by simpa using Complex.inv_one_add_tan_sq this theorem 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] theorem inv_sqrt_one_add_tan_sq {x : ℝ} (hx : 0 < cos x) : (√(1 + tan x ^ 2))⁻¹ = cos x := by rw [← sqrt_sq hx.le, ← sqrt_inv, inv_one_add_tan_sq hx.ne'] theorem tan_div_sqrt_one_add_tan_sq {x : ℝ} (hx : 0 < cos x) : tan x / √(1 + tan x ^ 2) = sin x := by rw [← tan_mul_cos hx.ne', ← inv_sqrt_one_add_tan_sq hx, div_eq_mul_inv] nonrec theorem cos_three_mul : cos (3 * x) = 4 * cos x ^ 3 - 3 * cos x := by rw [← ofReal_inj]; simp [cos_three_mul] nonrec theorem sin_three_mul : sin (3 * x) = 3 * sin x - 4 * sin x ^ 3 := by rw [← ofReal_inj]; simp [sin_three_mul] /-- The definition of `sinh` in terms of `exp`. -/ nonrec theorem sinh_eq (x : ℝ) : sinh x = (exp x - exp (-x)) / 2 := ofReal_injective <| by simp [Complex.sinh] @[simp] theorem sinh_zero : sinh 0 = 0 := by simp [sinh] @[simp] theorem sinh_neg : sinh (-x) = -sinh x := by simp [sinh, exp_neg, (neg_div _ _).symm, add_mul] nonrec theorem sinh_add : sinh (x + y) = sinh x * cosh y + cosh x * sinh y := by rw [← ofReal_inj]; simp [sinh_add] /-- The definition of `cosh` in terms of `exp`. -/ theorem cosh_eq (x : ℝ) : cosh x = (exp x + exp (-x)) / 2 := eq_div_of_mul_eq two_ne_zero <| by rw [cosh, exp, exp, Complex.ofReal_neg, Complex.cosh, mul_two, ← Complex.add_re, ← mul_two, div_mul_cancel₀ _ (two_ne_zero' ℂ), Complex.add_re] @[simp] theorem cosh_zero : cosh 0 = 1 := by simp [cosh] @[simp] theorem cosh_neg : cosh (-x) = cosh x := ofReal_inj.1 <| by simp @[simp] theorem cosh_abs : cosh |x| = cosh x := by cases le_total x 0 <;> simp [*, _root_.abs_of_nonneg, abs_of_nonpos] nonrec theorem cosh_add : cosh (x + y) = cosh x * cosh y + sinh x * sinh y := by rw [← ofReal_inj]; simp [cosh_add] theorem 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] theorem 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] nonrec theorem tanh_eq_sinh_div_cosh : tanh x = sinh x / cosh x := ofReal_inj.1 <| by simp [tanh_eq_sinh_div_cosh] @[simp] theorem tanh_zero : tanh 0 = 0 := by simp [tanh] @[simp] theorem tanh_neg : tanh (-x) = -tanh x := by simp [tanh, neg_div] @[simp] theorem cosh_add_sinh : cosh x + sinh x = exp x := by rw [← ofReal_inj]; simp @[simp] theorem sinh_add_cosh : sinh x + cosh x = exp x := by rw [add_comm, cosh_add_sinh] @[simp] theorem exp_sub_cosh : exp x - cosh x = sinh x := sub_eq_iff_eq_add.2 (sinh_add_cosh x).symm @[simp] theorem exp_sub_sinh : exp x - sinh x = cosh x := sub_eq_iff_eq_add.2 (cosh_add_sinh x).symm @[simp] theorem cosh_sub_sinh : cosh x - sinh x = exp (-x) := by rw [← ofReal_inj] simp @[simp] theorem sinh_sub_cosh : sinh x - cosh x = -exp (-x) := by rw [← neg_sub, cosh_sub_sinh] @[simp] theorem cosh_sq_sub_sinh_sq (x : ℝ) : cosh x ^ 2 - sinh x ^ 2 = 1 := by rw [← ofReal_inj]; simp nonrec theorem cosh_sq : cosh x ^ 2 = sinh x ^ 2 + 1 := by rw [← ofReal_inj]; simp [cosh_sq] theorem cosh_sq' : cosh x ^ 2 = 1 + sinh x ^ 2 := (cosh_sq x).trans (add_comm _ _) nonrec theorem sinh_sq : sinh x ^ 2 = cosh x ^ 2 - 1 := by rw [← ofReal_inj]; simp [sinh_sq] nonrec theorem cosh_two_mul : cosh (2 * x) = cosh x ^ 2 + sinh x ^ 2 := by rw [← ofReal_inj]; simp [cosh_two_mul] nonrec theorem sinh_two_mul : sinh (2 * x) = 2 * sinh x * cosh x := by rw [← ofReal_inj]; simp [sinh_two_mul] nonrec theorem cosh_three_mul : cosh (3 * x) = 4 * cosh x ^ 3 - 3 * cosh x := by rw [← ofReal_inj]; simp [cosh_three_mul] nonrec theorem sinh_three_mul : sinh (3 * x) = 4 * sinh x ^ 3 + 3 * sinh x := by rw [← ofReal_inj]; simp [sinh_three_mul] open IsAbsoluteValue Nat theorem sum_le_exp_of_nonneg {x : ℝ} (hx : 0 ≤ x) (n : ℕ) : ∑ i ∈ range n, x ^ i / i ! ≤ exp x := calc ∑ i ∈ range n, x ^ i / i ! ≤ lim (⟨_, isCauSeq_re (exp' x)⟩ : CauSeq ℝ abs) := by refine le_lim (CauSeq.le_of_exists ⟨n, fun j hj => ?_⟩) simp only [exp', const_apply, re_sum] norm_cast refine sum_le_sum_of_subset_of_nonneg (range_mono hj) fun _ _ _ ↦ ?_ positivity _ = exp x := by rw [exp, Complex.exp, ← cauSeqRe, lim_re] lemma pow_div_factorial_le_exp (hx : 0 ≤ x) (n : ℕ) : x ^ n / n ! ≤ exp x := calc x ^ n / n ! ≤ ∑ k ∈ range (n + 1), x ^ k / k ! := single_le_sum (f := fun k ↦ x ^ k / k !) (fun k _ ↦ by positivity) (self_mem_range_succ n) _ ≤ exp x := sum_le_exp_of_nonneg hx _ theorem quadratic_le_exp_of_nonneg {x : ℝ} (hx : 0 ≤ x) : 1 + x + x ^ 2 / 2 ≤ exp x := calc 1 + x + x ^ 2 / 2 = ∑ i ∈ range 3, x ^ i / i ! := by simp only [sum_range_succ, range_one, sum_singleton, _root_.pow_zero, factorial, cast_one, ne_eq, one_ne_zero, not_false_eq_true, div_self, pow_one, mul_one, div_one, Nat.mul_one, cast_succ, add_right_inj] ring_nf _ ≤ exp x := sum_le_exp_of_nonneg hx 3 private theorem add_one_lt_exp_of_pos {x : ℝ} (hx : 0 < x) : x + 1 < exp x := (by nlinarith : x + 1 < 1 + x + x ^ 2 / 2).trans_le (quadratic_le_exp_of_nonneg hx.le) private theorem add_one_le_exp_of_nonneg {x : ℝ} (hx : 0 ≤ x) : x + 1 ≤ exp x := by rcases eq_or_lt_of_le hx with (rfl | h) · simp exact (add_one_lt_exp_of_pos h).le theorem one_le_exp {x : ℝ} (hx : 0 ≤ x) : 1 ≤ exp x := by linarith [add_one_le_exp_of_nonneg hx] @[bound] theorem exp_pos (x : ℝ) : 0 < exp x := (le_total 0 x).elim (lt_of_lt_of_le zero_lt_one ∘ one_le_exp) fun 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))) @[bound] lemma exp_nonneg (x : ℝ) : 0 ≤ exp x := x.exp_pos.le @[simp] theorem abs_exp (x : ℝ) : |exp x| = exp x := abs_of_pos (exp_pos _) lemma exp_abs_le (x : ℝ) : exp |x| ≤ exp x + exp (-x) := by cases le_total x 0 <;> simp [abs_of_nonpos, _root_.abs_of_nonneg, exp_nonneg, *] @[mono] theorem exp_strictMono : StrictMono exp := fun 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))) @[gcongr] theorem exp_lt_exp_of_lt {x y : ℝ} (h : x < y) : exp x < exp y := exp_strictMono h @[mono] theorem exp_monotone : Monotone exp := exp_strictMono.monotone @[gcongr, bound] theorem exp_le_exp_of_le {x y : ℝ} (h : x ≤ y) : exp x ≤ exp y := exp_monotone h @[simp] theorem exp_lt_exp {x y : ℝ} : exp x < exp y ↔ x < y := exp_strictMono.lt_iff_lt @[simp] theorem exp_le_exp {x y : ℝ} : exp x ≤ exp y ↔ x ≤ y := exp_strictMono.le_iff_le theorem exp_injective : Function.Injective exp := exp_strictMono.injective @[simp] theorem exp_eq_exp {x y : ℝ} : exp x = exp y ↔ x = y := exp_injective.eq_iff @[simp] theorem exp_eq_one_iff : exp x = 1 ↔ x = 0 := exp_injective.eq_iff' exp_zero @[simp] theorem one_lt_exp_iff {x : ℝ} : 1 < exp x ↔ 0 < x := by rw [← exp_zero, exp_lt_exp] @[bound] private alias ⟨_, Bound.one_lt_exp_of_pos⟩ := one_lt_exp_iff @[simp] theorem exp_lt_one_iff {x : ℝ} : exp x < 1 ↔ x < 0 := by rw [← exp_zero, exp_lt_exp] @[simp] theorem exp_le_one_iff {x : ℝ} : exp x ≤ 1 ↔ x ≤ 0 := exp_zero ▸ exp_le_exp @[simp] theorem one_le_exp_iff {x : ℝ} : 1 ≤ exp x ↔ 0 ≤ x := exp_zero ▸ exp_le_exp /-- `Real.cosh` is always positive -/ theorem cosh_pos (x : ℝ) : 0 < Real.cosh x := (cosh_eq x).symm ▸ half_pos (add_pos (exp_pos x) (exp_pos (-x))) theorem sinh_lt_cosh : sinh x < cosh x := lt_of_pow_lt_pow_left 2 (cosh_pos _).le <| (cosh_sq x).symm ▸ lt_add_one _ end Real namespace Complex theorem sum_div_factorial_le {α : Type*} [LinearOrderedField α] (n j : ℕ) (hn : 0 < n) : (∑ m ∈ filter (fun k => n ≤ k) (range j), (1 / m.factorial : α)) ≤ n.succ / (n.factorial * n) := calc (∑ m ∈ filter (fun k => n ≤ k) (range j), (1 / m.factorial : α)) = ∑ m ∈ range (j - n), (1 / ((m + n).factorial : α)) := by refine sum_nbij' (· - n) (· + n) ?_ ?_ ?_ ?_ ?_ <;> simp (config := { contextual := true }) [lt_tsub_iff_right, tsub_add_cancel_of_le] _ ≤ ∑ m ∈ range (j - n), ((n.factorial : α) * (n.succ : α) ^ m)⁻¹ := by simp_rw [one_div] gcongr rw [← Nat.cast_pow, ← Nat.cast_mul, Nat.cast_le, add_comm] exact Nat.factorial_mul_pow_le_factorial _ = (n.factorial : α)⁻¹ * ∑ m ∈ range (j - n), (n.succ : α)⁻¹ ^ m := by simp [mul_inv, ← mul_sum, ← sum_mul, mul_comm, inv_pow] _ = ((n.succ : α) - n.succ * (n.succ : α)⁻¹ ^ (j - n)) / (n.factorial * n) := by have h₁ : (n.succ : α) ≠ 1 := @Nat.cast_one α _ ▸ mt Nat.cast_inj.1 (mt Nat.succ.inj (pos_iff_ne_zero.1 hn)) have h₂ : (n.succ : α) ≠ 0 := by positivity have h₃ : (n.factorial * n : α) ≠ 0 := by positivity have h₄ : (n.succ - 1 : α) = n := by simp rw [geom_sum_inv h₁ h₂, eq_div_iff_mul_eq h₃, mul_comm _ (n.factorial * n : α), ← mul_assoc (n.factorial⁻¹ : α), ← mul_inv_rev, h₄, ← mul_assoc (n.factorial * n : α), mul_comm (n : α) n.factorial, mul_inv_cancel h₃, one_mul, mul_comm] _ ≤ n.succ / (n.factorial * n : α) := by gcongr; apply sub_le_self; positivity theorem exp_bound {x : ℂ} (hx : abs x ≤ 1) {n : ℕ} (hn : 0 < n) : abs (exp x - ∑ m ∈ range n, x ^ m / m.factorial) ≤ abs x ^ n * ((n.succ : ℝ) * (n.factorial * n : ℝ)⁻¹) := by rw [← lim_const (abv := Complex.abs) (∑ m ∈ range n, _), exp, sub_eq_add_neg, ← lim_neg, lim_add, ← lim_abs] refine lim_le (CauSeq.le_of_exists ⟨n, fun j hj => ?_⟩) simp_rw [← sub_eq_add_neg] show abs ((∑ m ∈ range j, x ^ m / m.factorial) - ∑ m ∈ range n, x ^ m / m.factorial) ≤ abs x ^ n * ((n.succ : ℝ) * (n.factorial * n : ℝ)⁻¹) rw [sum_range_sub_sum_range hj] calc abs (∑ m ∈ (range j).filter fun k => n ≤ k, (x ^ m / m.factorial : ℂ)) = abs (∑ m ∈ (range j).filter fun k => n ≤ k, (x ^ n * (x ^ (m - n) / m.factorial) : ℂ)) := by refine congr_arg abs (sum_congr rfl fun m hm => ?_) rw [mem_filter, mem_range] at hm rw [← mul_div_assoc, ← pow_add, add_tsub_cancel_of_le hm.2] _ ≤ ∑ m ∈ filter (fun k => n ≤ k) (range j), abs (x ^ n * (x ^ (m - n) / m.factorial)) := (IsAbsoluteValue.abv_sum Complex.abs _ _) _ ≤ ∑ m ∈ filter (fun k => n ≤ k) (range j), abs x ^ n * (1 / m.factorial) := by simp_rw [map_mul, map_pow, map_div₀, abs_natCast] gcongr rw [abv_pow abs] exact pow_le_one _ (abs.nonneg _) hx _ = abs x ^ n * ∑ m ∈ (range j).filter fun k => n ≤ k, (1 / m.factorial : ℝ) := by simp [abs_mul, abv_pow abs, abs_div, ← mul_sum] _ ≤ abs x ^ n * (n.succ * (n.factorial * n : ℝ)⁻¹) := by gcongr exact sum_div_factorial_le _ _ hn theorem exp_bound' {x : ℂ} {n : ℕ} (hx : abs x / n.succ ≤ 1 / 2) : abs (exp x - ∑ m ∈ range n, x ^ m / m.factorial) ≤ abs x ^ n / n.factorial * 2 := by rw [← lim_const (abv := Complex.abs) (∑ m ∈ range n, _), exp, sub_eq_add_neg, ← lim_neg, lim_add, ← lim_abs] refine lim_le (CauSeq.le_of_exists ⟨n, fun j hj => ?_⟩) simp_rw [← sub_eq_add_neg] show abs ((∑ m ∈ range j, x ^ m / m.factorial) - ∑ m ∈ range n, x ^ m / m.factorial) ≤ abs x ^ n / n.factorial * 2 let k := j - n have hj : j = n + k := (add_tsub_cancel_of_le hj).symm rw [hj, sum_range_add_sub_sum_range] calc abs (∑ i ∈ range k, x ^ (n + i) / ((n + i).factorial : ℂ)) ≤ ∑ i ∈ range k, abs (x ^ (n + i) / ((n + i).factorial : ℂ)) := IsAbsoluteValue.abv_sum _ _ _ _ ≤ ∑ i ∈ range k, abs x ^ (n + i) / (n + i).factorial := by simp [Complex.abs_natCast, map_div₀, abv_pow abs] _ ≤ ∑ i ∈ range k, abs x ^ (n + i) / ((n.factorial : ℝ) * (n.succ : ℝ) ^ i) := ?_ _ = ∑ i ∈ range k, abs x ^ n / n.factorial * (abs x ^ i / (n.succ : ℝ) ^ i) := ?_ _ ≤ abs x ^ n / ↑n.factorial * 2 := ?_ · gcongr exact mod_cast Nat.factorial_mul_pow_le_factorial · refine Finset.sum_congr rfl fun _ _ => ?_ simp only [pow_add, div_eq_inv_mul, mul_inv, mul_left_comm, mul_assoc] · rw [← mul_sum] gcongr simp_rw [← div_pow] rw [geom_sum_eq, div_le_iff_of_neg] · trans (-1 : ℝ) · linarith · simp only [neg_le_sub_iff_le_add, div_pow, Nat.cast_succ, le_add_iff_nonneg_left] positivity · linarith · linarith theorem 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 ∈ range 1, x ^ m / m.factorial) := by simp [sum_range_succ] _ ≤ abs x ^ 1 * ((Nat.succ 1 : ℝ) * ((Nat.factorial 1) * (1 : ℕ) : ℝ)⁻¹) := (exp_bound hx (by decide)) _ = 2 * abs x := by simp [two_mul, mul_two, mul_add, mul_comm, add_mul, Nat.factorial] theorem 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 ∈ range 2, x ^ m / m.factorial) := by simp [sub_eq_add_neg, sum_range_succ_comm, add_assoc, Nat.factorial] _ ≤ abs x ^ 2 * ((Nat.succ 2 : ℝ) * (Nat.factorial 2 * (2 : ℕ) : ℝ)⁻¹) := (exp_bound hx (by decide)) _ ≤ abs x ^ 2 * 1 := by gcongr; norm_num [Nat.factorial] _ = abs x ^ 2 := by rw [mul_one] end Complex namespace Real open Complex Finset nonrec theorem exp_bound {x : ℝ} (hx : |x| ≤ 1) {n : ℕ} (hn : 0 < n) : |exp x - ∑ m ∈ range n, x ^ m / m.factorial| ≤ |x| ^ n * (n.succ / (n.factorial * n)) := by have hxc : Complex.abs x ≤ 1 := mod_cast hx convert exp_bound hxc hn using 2 <;> -- Porting note: was `norm_cast` simp only [← abs_ofReal, ← ofReal_sub, ← ofReal_exp, ← ofReal_sum, ← ofReal_pow, ← ofReal_div, ← ofReal_natCast] theorem exp_bound' {x : ℝ} (h1 : 0 ≤ x) (h2 : x ≤ 1) {n : ℕ} (hn : 0 < n) : Real.exp x ≤ (∑ m ∈ Finset.range n, x ^ m / m.factorial) + x ^ n * (n + 1) / (n.factorial * n) := by have h3 : |x| = x := by simpa have h4 : |x| ≤ 1 := by rwa [h3] have h' := Real.exp_bound h4 hn rw [h3] at h' have h'' := (abs_sub_le_iff.1 h').1 have t := sub_le_iff_le_add'.1 h'' simpa [mul_div_assoc] using t theorem abs_exp_sub_one_le {x : ℝ} (hx : |x| ≤ 1) : |exp x - 1| ≤ 2 * |x| := by have : |x| ≤ 1 := mod_cast hx -- Porting note: was --exact_mod_cast Complex.abs_exp_sub_one_le (x := x) this have := Complex.abs_exp_sub_one_le (x := x) (by simpa using this) rw [← ofReal_exp, ← ofReal_one, ← ofReal_sub, abs_ofReal, abs_ofReal] at this exact this theorem abs_exp_sub_one_sub_id_le {x : ℝ} (hx : |x| ≤ 1) : |exp x - 1 - x| ≤ x ^ 2 := by rw [← _root_.sq_abs] -- Porting note: was -- exact_mod_cast Complex.abs_exp_sub_one_sub_id_le this have : Complex.abs x ≤ 1 := mod_cast hx have := Complex.abs_exp_sub_one_sub_id_le this rw [← ofReal_one, ← ofReal_exp, ← ofReal_sub, ← ofReal_sub, abs_ofReal, abs_ofReal] at this exact this /-- 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 `expNear_succ`), with `expNear n x r ⟶ exp x` as `n ⟶ ∞`, for any `r`. -/ noncomputable def expNear (n : ℕ) (x r : ℝ) : ℝ := (∑ m ∈ range n, x ^ m / m.factorial) + x ^ n / n.factorial * r @[simp] theorem expNear_zero (x r) : expNear 0 x r = r := by simp [expNear] @[simp] theorem expNear_succ (n x r) : expNear (n + 1) x r = expNear n x (1 + x / (n + 1) * r) := by simp [expNear, range_succ, mul_add, add_left_comm, add_assoc, pow_succ, div_eq_mul_inv, mul_inv, Nat.factorial] ac_rfl theorem expNear_sub (n x r₁ r₂) : expNear n x r₁ - expNear n x r₂ = x ^ n / n.factorial * (r₁ - r₂) := by simp [expNear, mul_sub] theorem exp_approx_end (n m : ℕ) (x : ℝ) (e₁ : n + 1 = m) (h : |x| ≤ 1) : |exp x - expNear m x 0| ≤ |x| ^ m / m.factorial * ((m + 1) / m) := by simp only [expNear, mul_zero, add_zero] convert exp_bound (n := m) h ?_ using 1 · field_simp [mul_comm] · omega theorem exp_approx_succ {n} {x a₁ b₁ : ℝ} (m : ℕ) (e₁ : n + 1 = m) (a₂ b₂ : ℝ) (e : |1 + x / m * a₂ - a₁| ≤ b₁ - |x| / m * b₂) (h : |exp x - expNear m x a₂| ≤ |x| ^ m / m.factorial * b₂) : |exp x - expNear n x a₁| ≤ |x| ^ n / n.factorial * b₁ := by refine (abs_sub_le _ _ _).trans ((add_le_add_right h _).trans ?_) subst e₁; rw [expNear_succ, expNear_sub, abs_mul] convert mul_le_mul_of_nonneg_left (a := |x| ^ n / ↑(Nat.factorial n)) (le_sub_iff_add_le'.1 e) ?_ using 1 · simp [mul_add, pow_succ', div_eq_mul_inv, abs_mul, abs_inv, ← pow_abs, mul_inv, Nat.factorial] ac_rfl · simp [div_nonneg, abs_nonneg] theorem exp_approx_end' {n} {x a b : ℝ} (m : ℕ) (e₁ : n + 1 = m) (rm : ℝ) (er : ↑m = rm) (h : |x| ≤ 1) (e : |1 - a| ≤ b - |x| / rm * ((rm + 1) / rm)) : |exp x - expNear n x a| ≤ |x| ^ n / n.factorial * b := by subst er exact exp_approx_succ _ e₁ _ _ (by simpa using e) (exp_approx_end _ _ _ e₁ h) theorem exp_1_approx_succ_eq {n} {a₁ b₁ : ℝ} {m : ℕ} (en : n + 1 = m) {rm : ℝ} (er : ↑m = rm) (h : |exp 1 - expNear m 1 ((a₁ - 1) * rm)| ≤ |1| ^ m / m.factorial * (b₁ * rm)) : |exp 1 - expNear n 1 a₁| ≤ |1| ^ n / n.factorial * b₁ := by subst er refine exp_approx_succ _ en _ _ ?_ h field_simp [show (m : ℝ) ≠ 0 by norm_cast; omega] theorem exp_approx_start (x a b : ℝ) (h : |exp x - expNear 0 x a| ≤ |x| ^ 0 / Nat.factorial 0 * b) : |exp x - a| ≤ b := by simpa using h theorem cos_bound {x : ℝ} (hx : |x| ≤ 1) : |cos x - (1 - x ^ 2 / 2)| ≤ |x| ^ 4 * (5 / 96) := calc |cos x - (1 - x ^ 2 / 2)| = Complex.abs (Complex.cos x - (1 - (x : ℂ) ^ 2 / 2)) := by rw [← abs_ofReal]; simp _ = Complex.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 ∈ range 4, (x * I) ^ m / m.factorial) + (Complex.exp (-x * I) - ∑ m ∈ range 4, (-x * I) ^ m / m.factorial)) / 2) := (congr_arg Complex.abs (congr_arg (fun x : ℂ => x / 2) (by simp only [sum_range_succ, neg_mul, pow_succ, pow_zero, mul_one, range_zero, sum_empty, Nat.factorial, Nat.cast_one, ne_eq, one_ne_zero, not_false_eq_true, div_self, zero_add, div_one, Nat.mul_one, Nat.cast_succ, Nat.cast_mul, Nat.cast_ofNat, mul_neg, neg_neg] apply Complex.ext <;> simp [div_eq_mul_inv, normSq] <;> ring_nf ))) _ ≤ abs ((Complex.exp (x * I) - ∑ m ∈ range 4, (x * I) ^ m / m.factorial) / 2) + abs ((Complex.exp (-x * I) - ∑ m ∈ range 4, (-x * I) ^ m / m.factorial) / 2) := by rw [add_div]; exact Complex.abs.add_le _ _ _ = abs (Complex.exp (x * I) - ∑ m ∈ range 4, (x * I) ^ m / m.factorial) / 2 + abs (Complex.exp (-x * I) - ∑ m ∈ range 4, (-x * I) ^ m / m.factorial) / 2 := by simp [map_div₀] _ ≤ Complex.abs (x * I) ^ 4 * (Nat.succ 4 * ((Nat.factorial 4) * (4 : ℕ) : ℝ)⁻¹) / 2 + Complex.abs (-x * I) ^ 4 * (Nat.succ 4 * ((Nat.factorial 4) * (4 : ℕ) : ℝ)⁻¹) / 2 := by gcongr · exact Complex.exp_bound (by simpa) (by decide) · exact Complex.exp_bound (by simpa) (by decide) _ ≤ |x| ^ 4 * (5 / 96) := by norm_num [Nat.factorial] theorem sin_bound {x : ℝ} (hx : |x| ≤ 1) : |sin x - (x - x ^ 3 / 6)| ≤ |x| ^ 4 * (5 / 96) := calc |sin x - (x - x ^ 3 / 6)| = Complex.abs (Complex.sin x - (x - x ^ 3 / 6 : ℝ)) := by rw [← abs_ofReal]; simp _ = Complex.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, show (3 : ℂ) * 2 = 6 by norm_num] _ = Complex.abs (((Complex.exp (-x * I) - ∑ m ∈ range 4, (-x * I) ^ m / m.factorial) - (Complex.exp (x * I) - ∑ m ∈ range 4, (x * I) ^ m / m.factorial)) * I / 2) := (congr_arg Complex.abs (congr_arg (fun x : ℂ => x / 2) (by simp only [sum_range_succ, neg_mul, pow_succ, pow_zero, mul_one, ofReal_sub, ofReal_mul, ofReal_ofNat, ofReal_div, range_zero, sum_empty, Nat.factorial, Nat.cast_one, ne_eq, one_ne_zero, not_false_eq_true, div_self, zero_add, div_one, mul_neg, neg_neg, Nat.mul_one, Nat.cast_succ, Nat.cast_mul, Nat.cast_ofNat] apply Complex.ext <;> simp [div_eq_mul_inv, normSq]; ring))) _ ≤ abs ((Complex.exp (-x * I) - ∑ m ∈ range 4, (-x * I) ^ m / m.factorial) * I / 2) + abs (-((Complex.exp (x * I) - ∑ m ∈ range 4, (x * I) ^ m / m.factorial) * I) / 2) := by rw [sub_mul, sub_eq_add_neg, add_div]; exact Complex.abs.add_le _ _ _ = abs (Complex.exp (x * I) - ∑ m ∈ range 4, (x * I) ^ m / m.factorial) / 2 + abs (Complex.exp (-x * I) - ∑ m ∈ range 4, (-x * I) ^ m / m.factorial) / 2 := by simp [add_comm, map_div₀] _ ≤ Complex.abs (x * I) ^ 4 * (Nat.succ 4 * (Nat.factorial 4 * (4 : ℕ) : ℝ)⁻¹) / 2 + Complex.abs (-x * I) ^ 4 * (Nat.succ 4 * (Nat.factorial 4 * (4 : ℕ) : ℝ)⁻¹) / 2 := by gcongr · exact Complex.exp_bound (by simpa) (by decide) · exact Complex.exp_bound (by simpa) (by decide) _ ≤ |x| ^ 4 * (5 / 96) := by norm_num [Nat.factorial] theorem cos_pos_of_le_one {x : ℝ} (hx : |x| ≤ 1) : 0 < cos x := calc 0 < 1 - x ^ 2 / 2 - |x| ^ 4 * (5 / 96) := sub_pos.2 <| lt_sub_iff_add_lt.2 (calc |x| ^ 4 * (5 / 96) + x ^ 2 / 2 ≤ 1 * (5 / 96) + 1 / 2 := by gcongr · exact pow_le_one _ (abs_nonneg _) hx · rw [sq, ← abs_mul_self, abs_mul] exact mul_le_one hx (abs_nonneg _) hx _ < 1 := by norm_num) _ ≤ cos x := sub_le_comm.1 (abs_sub_le_iff.1 (cos_bound hx)).2 theorem sin_pos_of_pos_of_le_one {x : ℝ} (hx0 : 0 < x) (hx : x ≤ 1) : 0 < sin x := calc 0 < x - x ^ 3 / 6 - |x| ^ 4 * (5 / 96) := sub_pos.2 <| lt_sub_iff_add_lt.2 (calc |x| ^ 4 * (5 / 96) + x ^ 3 / 6 ≤ x * (5 / 96) + x / 6 := by gcongr · calc |x| ^ 4 ≤ |x| ^ 1 := pow_le_pow_of_le_one (abs_nonneg _) (by rwa [_root_.abs_of_nonneg (le_of_lt hx0)]) (by decide) _ = x := by simp [_root_.abs_of_nonneg (le_of_lt hx0)] · calc x ^ 3 ≤ x ^ 1 := pow_le_pow_of_le_one (le_of_lt hx0) hx (by decide) _ = x := pow_one _ _ < x := by linarith) _ ≤ sin x := sub_le_comm.1 (abs_sub_le_iff.1 (sin_bound (by rwa [_root_.abs_of_nonneg (le_of_lt hx0)]))).2 theorem sin_pos_of_pos_of_le_two {x : ℝ} (hx0 : 0 < x) (hx : x ≤ 2) : 0 < sin x := have : x / 2 ≤ 1 := (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] theorem cos_one_le : cos 1 ≤ 2 / 3 := calc cos 1 ≤ |(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 theorem cos_one_pos : 0 < cos 1 := cos_pos_of_le_one (le_of_eq abs_one) theorem 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 := by gcongr · exact cos_one_pos.le · apply cos_one_le _ < 0 := by norm_num theorem exp_bound_div_one_sub_of_interval' {x : ℝ} (h1 : 0 < x) (h2 : x < 1) : Real.exp x < 1 / (1 - x) := by have H : 0 < 1 - (1 + x + x ^ 2) * (1 - x) := calc 0 < x ^ 3 := by positivity _ = 1 - (1 + x + x ^ 2) * (1 - x) := by ring calc exp x ≤ _ := exp_bound' h1.le h2.le zero_lt_three _ ≤ 1 + x + x ^ 2 := by -- Porting note: was `norm_num [Finset.sum] <;> nlinarith` -- This proof should be restored after the norm_num plugin for big operators is ported. -- (It may also need the positivity extensions in #3907.) repeat erw [Finset.sum_range_succ] norm_num [Nat.factorial] nlinarith _ < 1 / (1 - x) := by rw [lt_div_iff] <;> nlinarith theorem exp_bound_div_one_sub_of_interval {x : ℝ} (h1 : 0 ≤ x) (h2 : x < 1) : Real.exp x ≤ 1 / (1 - x) := by rcases eq_or_lt_of_le h1 with (rfl | h1) · simp · exact (exp_bound_div_one_sub_of_interval' h1 h2).le theorem add_one_lt_exp {x : ℝ} (hx : x ≠ 0) : x + 1 < Real.exp x := by obtain hx | hx := hx.symm.lt_or_lt · exact add_one_lt_exp_of_pos hx obtain h' | h' := le_or_lt 1 (-x) · linarith [x.exp_pos] have hx' : 0 < x + 1 := by linarith simpa [add_comm, exp_neg, inv_lt_inv (exp_pos _) hx'] using exp_bound_div_one_sub_of_interval' (neg_pos.2 hx) h' theorem add_one_le_exp (x : ℝ) : x + 1 ≤ Real.exp x := by obtain rfl | hx := eq_or_ne x 0 · simp · exact (add_one_lt_exp hx).le lemma one_sub_lt_exp_neg {x : ℝ} (hx : x ≠ 0) : 1 - x < exp (-x) := (sub_eq_neg_add _ _).trans_lt <| add_one_lt_exp <| neg_ne_zero.2 hx lemma one_sub_le_exp_neg (x : ℝ) : 1 - x ≤ exp (-x) := (sub_eq_neg_add _ _).trans_le <| add_one_le_exp _ theorem one_sub_div_pow_le_exp_neg {n : ℕ} {t : ℝ} (ht' : t ≤ n) : (1 - t / n) ^ n ≤ exp (-t) := by rcases eq_or_ne n 0 with (rfl | hn) · simp rwa [Nat.cast_zero] at ht' convert pow_le_pow_left ?_ (one_sub_le_exp_neg (t / n)) n using 2 · rw [← Real.exp_nat_mul] congr 1 field_simp ring_nf · rwa [sub_nonneg, div_le_one] positivity end Real namespace Mathlib.Meta.Positivity open Lean.Meta Qq /-- Extension for the `positivity` tactic: `Real.exp` is always positive. -/ @[positivity Real.exp _] def evalExp : PositivityExt where eval {u α} _ _ e := do match u, α, e with | 0, ~q(ℝ), ~q(Real.exp $a) => assertInstancesCommute pure (.positive q(Real.exp_pos $a)) | _, _, _ => throwError "not Real.exp" /-- Extension for the `positivity` tactic: `Real.cosh` is always positive. -/ @[positivity Real.cosh _] def evalCosh : PositivityExt where eval {u α} _ _ e := do match u, α, e with | 0, ~q(ℝ), ~q(Real.cosh $a) => assertInstancesCommute return .positive q(Real.cosh_pos $a) | _, _, _ => throwError "not Real.cosh" example (x : ℝ) : 0 < x.cosh := by positivity end Mathlib.Meta.Positivity namespace Complex @[simp] theorem abs_cos_add_sin_mul_I (x : ℝ) : abs (cos x + sin x * I) = 1 := by have := Real.sin_sq_add_cos_sq x simp_all [add_comm, abs, normSq, sq, sin_ofReal_re, cos_ofReal_re, mul_re] @[simp] theorem abs_exp_ofReal (x : ℝ) : abs (exp x) = Real.exp x := by rw [← ofReal_exp] exact abs_of_nonneg (le_of_lt (Real.exp_pos _)) @[simp] theorem abs_exp_ofReal_mul_I (x : ℝ) : abs (exp (x * I)) = 1 := by rw [exp_mul_I, abs_cos_add_sin_mul_I] theorem abs_exp (z : ℂ) : abs (exp z) = Real.exp z.re := by rw [exp_eq_exp_re_mul_sin_add_cos, map_mul, abs_exp_ofReal, abs_cos_add_sin_mul_I, mul_one] theorem abs_exp_eq_iff_re_eq {x y : ℂ} : abs (exp x) = abs (exp y) ↔ x.re = y.re := by rw [abs_exp, abs_exp, Real.exp_eq_exp] end Complex
Data\Complex\ExponentialBounds.lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Joseph Myers -/ import Mathlib.Data.Complex.Exponential import Mathlib.Analysis.SpecialFunctions.Log.Deriv /-! # Bounds on specific values of the exponential -/ namespace Real open IsAbsoluteValue Finset CauSeq Complex theorem exp_one_near_10 : |exp 1 - 2244083 / 825552| ≤ 1 / 10 ^ 10 := by apply exp_approx_start iterate 13 refine exp_1_approx_succ_eq (by norm_num1; rfl) (by norm_cast) ?_ norm_num1 refine exp_approx_end' _ (by norm_num1; rfl) _ (by norm_cast) (by simp) ?_ rw [_root_.abs_one, abs_of_pos] <;> norm_num1 theorem exp_one_near_20 : |exp 1 - 363916618873 / 133877442384| ≤ 1 / 10 ^ 20 := by apply exp_approx_start iterate 21 refine exp_1_approx_succ_eq (by norm_num1; rfl) (by norm_cast) ?_ norm_num1 refine exp_approx_end' _ (by norm_num1; rfl) _ (by norm_cast) (by simp) ?_ rw [_root_.abs_one, abs_of_pos] <;> norm_num1 theorem exp_one_gt_d9 : 2.7182818283 < exp 1 := lt_of_lt_of_le (by norm_num) (sub_le_comm.1 (abs_sub_le_iff.1 exp_one_near_10).2) theorem exp_one_lt_d9 : exp 1 < 2.7182818286 := lt_of_le_of_lt (sub_le_iff_le_add.1 (abs_sub_le_iff.1 exp_one_near_10).1) (by norm_num) theorem exp_neg_one_gt_d9 : 0.36787944116 < exp (-1) := by rw [exp_neg, lt_inv _ (exp_pos _)] · refine lt_of_le_of_lt (sub_le_iff_le_add.1 (abs_sub_le_iff.1 exp_one_near_10).1) ?_ norm_num · norm_num theorem exp_neg_one_lt_d9 : exp (-1) < 0.3678794412 := by rw [exp_neg, inv_lt (exp_pos _)] · refine lt_of_lt_of_le ?_ (sub_le_comm.1 (abs_sub_le_iff.1 exp_one_near_10).2) norm_num · norm_num set_option tactic.skipAssignedInstances false in theorem log_two_near_10 : |log 2 - 287209 / 414355| ≤ 1 / 10 ^ 10 := by suffices |log 2 - 287209 / 414355| ≤ 1 / 17179869184 + (1 / 10 ^ 10 - 1 / 2 ^ 34) by norm_num1 at * assumption have t : |(2⁻¹ : ℝ)| = 2⁻¹ := by rw [abs_of_pos]; norm_num have z := Real.abs_log_sub_add_sum_range_le (show |(2⁻¹ : ℝ)| < 1 by rw [t]; norm_num) 34 rw [t] at z norm_num1 at z rw [one_div (2 : ℝ), log_inv, ← sub_eq_add_neg, _root_.abs_sub_comm] at z apply le_trans (_root_.abs_sub_le _ _ _) (add_le_add z _) simp_rw [sum_range_succ] norm_num rw [abs_of_pos] <;> norm_num theorem log_two_gt_d9 : 0.6931471803 < log 2 := lt_of_lt_of_le (by norm_num1) (sub_le_comm.1 (abs_sub_le_iff.1 log_two_near_10).2) theorem log_two_lt_d9 : log 2 < 0.6931471808 := lt_of_le_of_lt (sub_le_iff_le_add.1 (abs_sub_le_iff.1 log_two_near_10).1) (by norm_num) end Real
Data\Complex\FiniteDimensional.lean
/- Copyright (c) 2020 Alexander Bentkamp, Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alexander Bentkamp, Sébastien Gouëzel, Eric Wieser -/ import Mathlib.Algebra.Algebra.Rat import Mathlib.Data.Complex.Cardinality import Mathlib.Data.Complex.Module import Mathlib.LinearAlgebra.FiniteDimensional.Defs /-! # Complex number as a finite dimensional vector space over `ℝ` This file contains the `FiniteDimensional ℝ ℂ` instance, as well as some results about the rank (`finrank` and `Module.rank`). -/ open FiniteDimensional namespace Complex instance : FiniteDimensional ℝ ℂ := of_fintype_basis basisOneI @[simp] theorem finrank_real_complex : finrank ℝ ℂ = 2 := by rw [finrank_eq_card_basis basisOneI, Fintype.card_fin] @[simp] theorem rank_real_complex : Module.rank ℝ ℂ = 2 := by simp [← finrank_eq_rank, finrank_real_complex] theorem rank_real_complex'.{u} : Cardinal.lift.{u} (Module.rank ℝ ℂ) = 2 := by rw [← finrank_eq_rank, finrank_real_complex, Cardinal.lift_natCast, Nat.cast_ofNat] /-- `Fact` version of the dimension of `ℂ` over `ℝ`, locally useful in the definition of the circle. -/ theorem finrank_real_complex_fact : Fact (finrank ℝ ℂ = 2) := ⟨finrank_real_complex⟩ end Complex instance (priority := 100) FiniteDimensional.complexToReal (E : Type*) [AddCommGroup E] [Module ℂ E] [FiniteDimensional ℂ E] : FiniteDimensional ℝ E := FiniteDimensional.trans ℝ ℂ E theorem rank_real_of_complex (E : Type*) [AddCommGroup E] [Module ℂ E] : Module.rank ℝ E = 2 * Module.rank ℂ E := Cardinal.lift_inj.1 <| by rw [← lift_rank_mul_lift_rank ℝ ℂ E, Complex.rank_real_complex'] simp only [Cardinal.lift_id'] theorem finrank_real_of_complex (E : Type*) [AddCommGroup E] [Module ℂ E] : FiniteDimensional.finrank ℝ E = 2 * FiniteDimensional.finrank ℂ E := by rw [← FiniteDimensional.finrank_mul_finrank ℝ ℂ E, Complex.finrank_real_complex] section Rational open Cardinal Module @[simp] lemma Real.rank_rat_real : Module.rank ℚ ℝ = continuum := by refine (Free.rank_eq_mk_of_infinite_lt ℚ ℝ ?_).trans mk_real simpa [mk_real] using aleph0_lt_continuum @[simp] lemma Complex.rank_rat_complex : Module.rank ℚ ℂ = continuum := by refine (Free.rank_eq_mk_of_infinite_lt ℚ ℂ ?_).trans mk_complex simpa using aleph0_lt_continuum /-- `ℂ` and `ℝ` are isomorphic as vector spaces over `ℚ`, or equivalently, as additive groups. -/ theorem Complex.nonempty_linearEquiv_real : Nonempty (ℂ ≃ₗ[ℚ] ℝ) := LinearEquiv.nonempty_equiv_iff_rank_eq.mpr <| by simp end Rational
Data\Complex\Module.lean
/- Copyright (c) 2020 Alexander Bentkamp, Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alexander Bentkamp, Sébastien Gouëzel, Eric Wieser -/ import Mathlib.Algebra.Algebra.RestrictScalars import Mathlib.Algebra.CharP.Invertible import Mathlib.Data.Complex.Basic import Mathlib.LinearAlgebra.Matrix.ToLin import Mathlib.Data.Real.Star /-! # Complex number as a vector space over `ℝ` This file contains the following instances: * Any `•`-structure (`SMul`, `MulAction`, `DistribMulAction`, `Module`, `Algebra`) on `ℝ` imbues a corresponding structure on `ℂ`. This includes the statement that `ℂ` is an `ℝ` algebra. * any complex vector space is a real vector space; * any finite dimensional complex vector space is a finite dimensional real vector space; * the space of `ℝ`-linear maps from a real vector space to a complex vector space is a complex vector space. It also defines bundled versions of four standard maps (respectively, the real part, the imaginary part, the embedding of `ℝ` in `ℂ`, and the complex conjugate): * `Complex.reLm` (`ℝ`-linear map); * `Complex.imLm` (`ℝ`-linear map); * `Complex.ofRealAm` (`ℝ`-algebra (homo)morphism); * `Complex.conjAe` (`ℝ`-algebra equivalence). It also provides a universal property of the complex numbers `Complex.lift`, which constructs a `ℂ →ₐ[ℝ] A` into any `ℝ`-algebra `A` given a square root of `-1`. In addition, this file provides a decomposition into `realPart` and `imaginaryPart` for any element of a `StarModule` over `ℂ`. ## Notation * `ℜ` and `ℑ` for the `realPart` and `imaginaryPart`, respectively, in the locale `ComplexStarModule`. -/ assert_not_exists NNReal namespace Complex open ComplexConjugate open scoped SMul variable {R : Type*} {S : Type*} attribute [local ext] Complex.ext /- The priority of the following instances has been manually lowered, as when they don't apply they lead Lean to a very costly path, and most often they don't apply (most actions on `ℂ` don't come from actions on `ℝ`). See #11980-/ -- priority manually adjusted in #11980 instance (priority := 90) [SMul R ℝ] [SMul S ℝ] [SMulCommClass R S ℝ] : SMulCommClass R S ℂ where smul_comm r s x := by ext <;> simp [smul_re, smul_im, smul_comm] -- priority manually adjusted in #11980 instance (priority := 90) [SMul R S] [SMul R ℝ] [SMul S ℝ] [IsScalarTower R S ℝ] : IsScalarTower R S ℂ where smul_assoc r s x := by ext <;> simp [smul_re, smul_im, smul_assoc] -- priority manually adjusted in #11980 instance (priority := 90) [SMul R ℝ] [SMul Rᵐᵒᵖ ℝ] [IsCentralScalar R ℝ] : IsCentralScalar R ℂ where op_smul_eq_smul r x := by ext <;> simp [smul_re, smul_im, op_smul_eq_smul] -- priority manually adjusted in #11980 instance (priority := 90) mulAction [Monoid R] [MulAction R ℝ] : MulAction R ℂ where one_smul x := by ext <;> simp [smul_re, smul_im, one_smul] mul_smul r s x := by ext <;> simp [smul_re, smul_im, mul_smul] -- priority manually adjusted in #11980 instance (priority := 90) distribSMul [DistribSMul R ℝ] : DistribSMul R ℂ where smul_add r x y := by ext <;> simp [smul_re, smul_im, smul_add] smul_zero r := by ext <;> simp [smul_re, smul_im, smul_zero] -- priority manually adjusted in #11980 instance (priority := 90) [Semiring R] [DistribMulAction R ℝ] : DistribMulAction R ℂ := { Complex.distribSMul, Complex.mulAction with } -- priority manually adjusted in #11980 instance (priority := 100) instModule [Semiring R] [Module R ℝ] : Module R ℂ where add_smul r s x := by ext <;> simp [smul_re, smul_im, add_smul] zero_smul r := by ext <;> simp [smul_re, smul_im, zero_smul] -- priority manually adjusted in #11980 instance (priority := 95) instAlgebraOfReal [CommSemiring R] [Algebra R ℝ] : Algebra R ℂ := { Complex.ofReal.comp (algebraMap R ℝ) with smul := (· • ·) smul_def' := fun r x => by ext <;> simp [smul_re, smul_im, Algebra.smul_def] commutes' := fun r ⟨xr, xi⟩ => by ext <;> simp [smul_re, smul_im, Algebra.commutes] } instance : StarModule ℝ ℂ := ⟨fun r x => by simp only [star_def, star_trivial, real_smul, map_mul, conj_ofReal]⟩ @[simp] theorem coe_algebraMap : (algebraMap ℝ ℂ : ℝ → ℂ) = ((↑) : ℝ → ℂ) := rfl section variable {A : Type*} [Semiring A] [Algebra ℝ A] /-- We need this lemma since `Complex.coe_algebraMap` diverts the simp-normal form away from `AlgHom.commutes`. -/ @[simp] theorem _root_.AlgHom.map_coe_real_complex (f : ℂ →ₐ[ℝ] A) (x : ℝ) : f x = algebraMap ℝ A x := f.commutes x /-- Two `ℝ`-algebra homomorphisms from `ℂ` are equal if they agree on `Complex.I`. -/ @[ext] theorem algHom_ext ⦃f g : ℂ →ₐ[ℝ] A⦄ (h : f I = g I) : f = g := by ext ⟨x, y⟩ simp only [mk_eq_add_mul_I, map_add, AlgHom.map_coe_real_complex, map_mul, h] end open Submodule /-- `ℂ` has a basis over `ℝ` given by `1` and `I`. -/ noncomputable def basisOneI : Basis (Fin 2) ℝ ℂ := Basis.ofEquivFun { toFun := fun z => ![z.re, z.im] invFun := fun c => c 0 + c 1 • I left_inv := fun z => by simp right_inv := fun c => by ext i fin_cases i <;> simp map_add' := fun z z' => by simp map_smul' := fun c z => by simp } @[simp] theorem coe_basisOneI_repr (z : ℂ) : ⇑(basisOneI.repr z) = ![z.re, z.im] := rfl @[simp] theorem coe_basisOneI : ⇑basisOneI = ![1, I] := funext fun i => Basis.apply_eq_iff.mpr <| Finsupp.ext fun j => by fin_cases i <;> fin_cases j <;> -- Porting note: removed `only`, consider squeezing again simp [coe_basisOneI_repr, Finsupp.single_eq_of_ne, Matrix.cons_val_zero, Matrix.cons_val_one, Matrix.head_cons, Fin.one_eq_zero_iff, Ne, not_false_iff, I_re, Nat.succ_succ_ne_one, one_im, I_im, one_re, Finsupp.single_eq_same, Fin.zero_eq_one_iff] end Complex /- Register as an instance (with low priority) the fact that a complex vector space is also a real vector space. -/ instance (priority := 900) Module.complexToReal (E : Type*) [AddCommGroup E] [Module ℂ E] : Module ℝ E := RestrictScalars.module ℝ ℂ E /- Register as an instance (with low priority) the fact that a complex algebra is also a real algebra. -/ instance (priority := 900) Algebra.complexToReal {A : Type*} [Semiring A] [Algebra ℂ A] : Algebra ℝ A := RestrictScalars.algebra ℝ ℂ A -- try to make sure we're not introducing diamonds but we will need -- `reducible_and_instances` which currently fails #10906 example : Prod.algebra ℝ ℂ ℂ = (Prod.algebra ℂ ℂ ℂ).complexToReal := rfl -- try to make sure we're not introducing diamonds but we will need -- `reducible_and_instances` which currently fails #10906 example {ι : Type*} [Fintype ι] : Pi.algebra (R := ℝ) ι (fun _ ↦ ℂ) = (Pi.algebra (R := ℂ) ι (fun _ ↦ ℂ)).complexToReal := rfl example {A : Type*} [Ring A] [inst : Algebra ℂ A] : (inst.complexToReal).toModule = (inst.toModule).complexToReal := by with_reducible_and_instances rfl @[simp, norm_cast] theorem Complex.coe_smul {E : Type*} [AddCommGroup E] [Module ℂ E] (x : ℝ) (y : E) : (x : ℂ) • y = x • y := rfl /-- The scalar action of `ℝ` on a `ℂ`-module `E` induced by `Module.complexToReal` commutes with another scalar action of `M` on `E` whenever the action of `ℂ` commutes with the action of `M`. -/ instance (priority := 900) SMulCommClass.complexToReal {M E : Type*} [AddCommGroup E] [Module ℂ E] [SMul M E] [SMulCommClass ℂ M E] : SMulCommClass ℝ M E where smul_comm r _ _ := (smul_comm (r : ℂ) _ _ : _) /-- The scalar action of `ℝ` on a `ℂ`-module `E` induced by `Module.complexToReal` associates with another scalar action of `M` on `E` whenever the action of `ℂ` associates with the action of `M`. -/ instance IsScalarTower.complexToReal {M E : Type*} [AddCommGroup M] [Module ℂ M] [AddCommGroup E] [Module ℂ E] [SMul M E] [IsScalarTower ℂ M E] : IsScalarTower ℝ M E where smul_assoc r _ _ := (smul_assoc (r : ℂ) _ _ : _) -- check that the following instance is implied by the one above. example (E : Type*) [AddCommGroup E] [Module ℂ E] : IsScalarTower ℝ ℂ E := inferInstance instance (priority := 900) StarModule.complexToReal {E : Type*} [AddCommGroup E] [Star E] [Module ℂ E] [StarModule ℂ E] : StarModule ℝ E := ⟨fun r a => by rw [← smul_one_smul ℂ r a, star_smul, star_smul, star_one, smul_one_smul]⟩ namespace Complex open ComplexConjugate /-- Linear map version of the real part function, from `ℂ` to `ℝ`. -/ def reLm : ℂ →ₗ[ℝ] ℝ where toFun x := x.re map_add' := add_re map_smul' := by simp @[simp] theorem reLm_coe : ⇑reLm = re := rfl /-- Linear map version of the imaginary part function, from `ℂ` to `ℝ`. -/ def imLm : ℂ →ₗ[ℝ] ℝ where toFun x := x.im map_add' := add_im map_smul' := by simp @[simp] theorem imLm_coe : ⇑imLm = im := rfl /-- `ℝ`-algebra morphism version of the canonical embedding of `ℝ` in `ℂ`. -/ def ofRealAm : ℝ →ₐ[ℝ] ℂ := Algebra.ofId ℝ ℂ @[simp] theorem ofRealAm_coe : ⇑ofRealAm = ((↑) : ℝ → ℂ) := rfl /-- `ℝ`-algebra isomorphism version of the complex conjugation function from `ℂ` to `ℂ` -/ def conjAe : ℂ ≃ₐ[ℝ] ℂ := { conj with invFun := conj left_inv := star_star right_inv := star_star commutes' := conj_ofReal } @[simp] theorem conjAe_coe : ⇑conjAe = conj := rfl /-- The matrix representation of `conjAe`. -/ @[simp] theorem toMatrix_conjAe : LinearMap.toMatrix basisOneI basisOneI conjAe.toLinearMap = !![1, 0; 0, -1] := by ext i j -- Porting note: replaced non-terminal `simp [LinearMap.toMatrix_apply]` fin_cases i <;> fin_cases j <;> simp [LinearMap.toMatrix_apply] /-- The identity and the complex conjugation are the only two `ℝ`-algebra homomorphisms of `ℂ`. -/ theorem real_algHom_eq_id_or_conj (f : ℂ →ₐ[ℝ] ℂ) : f = AlgHom.id ℝ ℂ ∨ f = conjAe := by refine (eq_or_eq_neg_of_sq_eq_sq (f I) I <| by rw [← map_pow, I_sq, map_neg, map_one]).imp ?_ ?_ <;> refine fun h => algHom_ext ?_ exacts [h, conj_I.symm ▸ h] /-- The natural `LinearEquiv` from `ℂ` to `ℝ × ℝ`. -/ @[simps! (config := { simpRhs := true }) apply symm_apply_re symm_apply_im] def equivRealProdLm : ℂ ≃ₗ[ℝ] ℝ × ℝ := { equivRealProdAddHom with -- Porting note: `simp` has issues with `Prod.smul_def` map_smul' := fun r c => by simp [equivRealProdAddHom, Prod.smul_def, smul_eq_mul] } theorem equivRealProdLm_symm_apply (p : ℝ × ℝ) : Complex.equivRealProdLm.symm p = p.1 + p.2 * Complex.I := Complex.equivRealProd_symm_apply p section lift variable {A : Type*} [Ring A] [Algebra ℝ A] /-- There is an alg_hom from `ℂ` to any `ℝ`-algebra with an element that squares to `-1`. See `Complex.lift` for this as an equiv. -/ def liftAux (I' : A) (hf : I' * I' = -1) : ℂ →ₐ[ℝ] A := AlgHom.ofLinearMap ((Algebra.linearMap ℝ A).comp reLm + (LinearMap.toSpanSingleton _ _ I').comp imLm) (show algebraMap ℝ A 1 + (0 : ℝ) • I' = 1 by rw [RingHom.map_one, zero_smul, add_zero]) fun ⟨x₁, y₁⟩ ⟨x₂, y₂⟩ => show algebraMap ℝ A (x₁ * x₂ - y₁ * y₂) + (x₁ * y₂ + y₁ * x₂) • I' = (algebraMap ℝ A x₁ + y₁ • I') * (algebraMap ℝ A x₂ + y₂ • I') by rw [add_mul, mul_add, mul_add, add_comm _ (y₁ • I' * y₂ • I'), add_add_add_comm] congr 1 -- equate "real" and "imaginary" parts · let inst : SMulCommClass ℝ A A := by infer_instance -- Porting note: added rw [smul_mul_smul, hf, smul_neg, ← Algebra.algebraMap_eq_smul_one, ← sub_eq_add_neg, ← RingHom.map_mul, ← RingHom.map_sub] · rw [Algebra.smul_def, Algebra.smul_def, Algebra.smul_def, ← Algebra.right_comm _ x₂, ← mul_assoc, ← add_mul, ← RingHom.map_mul, ← RingHom.map_mul, ← RingHom.map_add] @[simp] theorem liftAux_apply (I' : A) (hI') (z : ℂ) : liftAux I' hI' z = algebraMap ℝ A z.re + z.im • I' := rfl theorem liftAux_apply_I (I' : A) (hI') : liftAux I' hI' I = I' := by simp /-- A universal property of the complex numbers, providing a unique `ℂ →ₐ[ℝ] A` for every element of `A` which squares to `-1`. This can be used to embed the complex numbers in the `Quaternion`s. This isomorphism is named to match the very similar `Zsqrtd.lift`. -/ @[simps (config := { simpRhs := true })] def lift : { I' : A // I' * I' = -1 } ≃ (ℂ →ₐ[ℝ] A) where toFun I' := liftAux I' I'.prop invFun F := ⟨F I, by rw [← map_mul, I_mul_I, map_neg, map_one]⟩ left_inv I' := Subtype.ext <| liftAux_apply_I (I' : A) I'.prop right_inv F := algHom_ext <| liftAux_apply_I _ _ -- When applied to `Complex.I` itself, `lift` is the identity. @[simp] theorem liftAux_I : liftAux I I_mul_I = AlgHom.id ℝ ℂ := algHom_ext <| liftAux_apply_I _ _ -- When applied to `-Complex.I`, `lift` is conjugation, `conj`. @[simp] theorem liftAux_neg_I : liftAux (-I) ((neg_mul_neg _ _).trans I_mul_I) = conjAe := algHom_ext <| (liftAux_apply_I _ _).trans conj_I.symm end lift end Complex section RealImaginaryPart open Complex variable {A : Type*} [AddCommGroup A] [Module ℂ A] [StarAddMonoid A] [StarModule ℂ A] /-- Create a `selfAdjoint` element from a `skewAdjoint` element by multiplying by the scalar `-Complex.I`. -/ @[simps] def skewAdjoint.negISMul : skewAdjoint A →ₗ[ℝ] selfAdjoint A where toFun a := ⟨-I • ↑a, by simp only [neg_smul, neg_mem_iff, selfAdjoint.mem_iff, star_smul, star_def, conj_I, star_val_eq, smul_neg, neg_neg]⟩ map_add' a b := by ext simp only [AddSubgroup.coe_add, smul_add, AddMemClass.mk_add_mk] map_smul' a b := by ext simp only [neg_smul, skewAdjoint.val_smul, AddSubgroup.coe_mk, RingHom.id_apply, selfAdjoint.val_smul, smul_neg, neg_inj] rw [smul_comm] theorem skewAdjoint.I_smul_neg_I (a : skewAdjoint A) : I • (skewAdjoint.negISMul a : A) = a := by simp only [smul_smul, skewAdjoint.negISMul_apply_coe, neg_smul, smul_neg, I_mul_I, one_smul, neg_neg] /-- The real part `ℜ a` of an element `a` of a star module over `ℂ`, as a linear map. This is just `selfAdjointPart ℝ`, but we provide it as a separate definition in order to link it with lemmas concerning the `imaginaryPart`, which doesn't exist in star modules over other rings. -/ noncomputable def realPart : A →ₗ[ℝ] selfAdjoint A := selfAdjointPart ℝ /-- The imaginary part `ℑ a` of an element `a` of a star module over `ℂ`, as a linear map into the self adjoint elements. In a general star module, we have a decomposition into the `selfAdjoint` and `skewAdjoint` parts, but in a star module over `ℂ` we have `realPart_add_I_smul_imaginaryPart`, which allows us to decompose into a linear combination of `selfAdjoint`s. -/ noncomputable def imaginaryPart : A →ₗ[ℝ] selfAdjoint A := skewAdjoint.negISMul.comp (skewAdjointPart ℝ) @[inherit_doc] scoped[ComplexStarModule] notation "ℜ" => realPart @[inherit_doc] scoped[ComplexStarModule] notation "ℑ" => imaginaryPart open ComplexStarModule theorem realPart_apply_coe (a : A) : (ℜ a : A) = (2 : ℝ)⁻¹ • (a + star a) := by unfold realPart simp only [selfAdjointPart_apply_coe, invOf_eq_inv] theorem imaginaryPart_apply_coe (a : A) : (ℑ a : A) = -I • (2 : ℝ)⁻¹ • (a - star a) := by unfold imaginaryPart simp only [LinearMap.coe_comp, Function.comp_apply, skewAdjoint.negISMul_apply_coe, skewAdjointPart_apply_coe, invOf_eq_inv, neg_smul] /-- The standard decomposition of `ℜ a + Complex.I • ℑ a = a` of an element of a star module over `ℂ` into a linear combination of self adjoint elements. -/ theorem realPart_add_I_smul_imaginaryPart (a : A) : (ℜ a : A) + I • (ℑ a : A) = a := by simpa only [smul_smul, realPart_apply_coe, imaginaryPart_apply_coe, neg_smul, I_mul_I, one_smul, neg_sub, add_add_sub_cancel, smul_sub, smul_add, neg_sub_neg, invOf_eq_inv] using invOf_two_smul_add_invOf_two_smul ℝ a @[simp] theorem realPart_I_smul (a : A) : ℜ (I • a) = -ℑ a := by ext -- Porting note: was -- simp [smul_comm I, smul_sub, sub_eq_add_neg, add_comm] rw [realPart_apply_coe, NegMemClass.coe_neg, imaginaryPart_apply_coe, neg_smul, neg_neg, smul_comm I, star_smul, star_def, conj_I, smul_sub, neg_smul, sub_eq_add_neg] @[simp] theorem imaginaryPart_I_smul (a : A) : ℑ (I • a) = ℜ a := by ext -- Porting note: was -- simp [smul_comm I, smul_smul I] rw [realPart_apply_coe, imaginaryPart_apply_coe, smul_comm] simp [← smul_assoc] theorem realPart_smul (z : ℂ) (a : A) : ℜ (z • a) = z.re • ℜ a - z.im • ℑ a := by have := by congrm (ℜ ($((re_add_im z).symm) • a)) simpa [-re_add_im, add_smul, ← smul_smul, sub_eq_add_neg] theorem imaginaryPart_smul (z : ℂ) (a : A) : ℑ (z • a) = z.re • ℑ a + z.im • ℜ a := by have := by congrm (ℑ ($((re_add_im z).symm) • a)) simpa [-re_add_im, add_smul, ← smul_smul] lemma skewAdjointPart_eq_I_smul_imaginaryPart (x : A) : (skewAdjointPart ℝ x : A) = I • (imaginaryPart x : A) := by simp [imaginaryPart_apply_coe, smul_smul] lemma imaginaryPart_eq_neg_I_smul_skewAdjointPart (x : A) : (imaginaryPart x : A) = -I • (skewAdjointPart ℝ x : A) := rfl lemma IsSelfAdjoint.coe_realPart {x : A} (hx : IsSelfAdjoint x) : (ℜ x : A) = x := hx.coe_selfAdjointPart_apply ℝ nonrec lemma IsSelfAdjoint.imaginaryPart {x : A} (hx : IsSelfAdjoint x) : ℑ x = 0 := by rw [imaginaryPart, LinearMap.comp_apply, hx.skewAdjointPart_apply _, map_zero] lemma realPart_comp_subtype_selfAdjoint : realPart.comp (selfAdjoint.submodule ℝ A).subtype = LinearMap.id := selfAdjointPart_comp_subtype_selfAdjoint ℝ lemma imaginaryPart_comp_subtype_selfAdjoint : imaginaryPart.comp (selfAdjoint.submodule ℝ A).subtype = 0 := by rw [imaginaryPart, LinearMap.comp_assoc, skewAdjointPart_comp_subtype_selfAdjoint, LinearMap.comp_zero] @[simp] lemma imaginaryPart_realPart {x : A} : ℑ (ℜ x : A) = 0 := (ℜ x).property.imaginaryPart @[simp] lemma imaginaryPart_imaginaryPart {x : A} : ℑ (ℑ x : A) = 0 := (ℑ x).property.imaginaryPart @[simp] lemma realPart_idem {x : A} : ℜ (ℜ x : A) = ℜ x := Subtype.ext <| (ℜ x).property.coe_realPart @[simp] lemma realPart_imaginaryPart {x : A} : ℜ (ℑ x : A) = ℑ x := Subtype.ext <| (ℑ x).property.coe_realPart lemma realPart_surjective : Function.Surjective (realPart (A := A)) := fun x ↦ ⟨(x : A), Subtype.ext x.property.coe_realPart⟩ lemma imaginaryPart_surjective : Function.Surjective (imaginaryPart (A := A)) := fun x ↦ ⟨I • (x : A), Subtype.ext <| by simp only [imaginaryPart_I_smul, x.property.coe_realPart]⟩ open Submodule lemma span_selfAdjoint : span ℂ (selfAdjoint A : Set A) = ⊤ := by refine eq_top_iff'.mpr fun x ↦ ?_ rw [← realPart_add_I_smul_imaginaryPart x] exact add_mem (subset_span (ℜ x).property) <| SMulMemClass.smul_mem _ <| subset_span (ℑ x).property /-- The natural `ℝ`-linear equivalence between `selfAdjoint ℂ` and `ℝ`. -/ @[simps apply symm_apply] def Complex.selfAdjointEquiv : selfAdjoint ℂ ≃ₗ[ℝ] ℝ where toFun := fun z ↦ (z : ℂ).re invFun := fun x ↦ ⟨x, conj_ofReal x⟩ left_inv := fun z ↦ Subtype.ext <| conj_eq_iff_re.mp z.property.star_eq right_inv := fun x ↦ rfl map_add' := by simp map_smul' := by simp lemma Complex.coe_selfAdjointEquiv (z : selfAdjoint ℂ) : (selfAdjointEquiv z : ℂ) = z := by simpa [selfAdjointEquiv_symm_apply] using (congr_arg Subtype.val <| Complex.selfAdjointEquiv.left_inv z) @[simp] lemma realPart_ofReal (r : ℝ) : (ℜ (r : ℂ) : ℂ) = r := by rw [realPart_apply_coe, star_def, conj_ofReal, ← two_smul ℝ (r : ℂ)] simp @[simp] lemma imaginaryPart_ofReal (r : ℝ) : ℑ (r : ℂ) = 0 := by ext1; simp [imaginaryPart_apply_coe, conj_ofReal] lemma Complex.coe_realPart (z : ℂ) : (ℜ z : ℂ) = z.re := calc (ℜ z : ℂ) = _ := by congrm (ℜ $((re_add_im z).symm)) _ = z.re := by rw [map_add, AddSubmonoid.coe_add, mul_comm, ← smul_eq_mul, realPart_I_smul] simp [conj_ofReal, ← two_mul] lemma star_mul_self_add_self_mul_star {A : Type*} [NonUnitalRing A] [StarRing A] [Module ℂ A] [IsScalarTower ℂ A A] [SMulCommClass ℂ A A] [StarModule ℂ A] (a : A) : star a * a + a * star a = 2 • (ℜ a * ℜ a + ℑ a * ℑ a) := have a_eq := (realPart_add_I_smul_imaginaryPart a).symm calc star a * a + a * star a = _ := congr((star $(a_eq)) * $(a_eq) + $(a_eq) * (star $(a_eq))) _ = 2 • (ℜ a * ℜ a + ℑ a * ℑ a) := by simp [mul_add, add_mul, smul_smul, two_smul, mul_smul_comm, smul_mul_assoc] abel end RealImaginaryPart
Data\Complex\Order.lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import Mathlib.Data.Complex.Abs /-! # The partial order on the complex numbers This order is defined by `z ≤ w ↔ z.re ≤ w.re ∧ z.im = w.im`. This is a natural order on `ℂ` because, as is well-known, there does not exist an order on `ℂ` making it into a `LinearOrderedField`. However, the order described above is the canonical order stemming from the structure of `ℂ` as a ⋆-ring (i.e., it becomes a `StarOrderedRing`). Moreover, with this order `ℂ` is a `StrictOrderedCommRing` and the coercion `(↑) : ℝ → ℂ` is an order embedding. This file only provides `Complex.partialOrder` and lemmas about it. Further structural classes are provided by `Mathlib/Data/RCLike/Basic.lean` as * `RCLike.toStrictOrderedCommRing` * `RCLike.toStarOrderedRing` * `RCLike.toOrderedSMul` These are all only available with `open scoped ComplexOrder`. -/ namespace Complex /-- We put a partial order on ℂ so that `z ≤ w` exactly if `w - z` is real and nonnegative. Complex numbers with different imaginary parts are incomparable. -/ protected def partialOrder : PartialOrder ℂ where le z w := z.re ≤ w.re ∧ z.im = w.im lt z w := z.re < w.re ∧ z.im = w.im lt_iff_le_not_le z w := by dsimp rw [lt_iff_le_not_le] tauto le_refl x := ⟨le_rfl, rfl⟩ le_trans x y z h₁ h₂ := ⟨h₁.1.trans h₂.1, h₁.2.trans h₂.2⟩ le_antisymm z w h₁ h₂ := ext (h₁.1.antisymm h₂.1) h₁.2 namespace _root_.ComplexOrder -- Porting note: made section into namespace to allow scoping scoped[ComplexOrder] attribute [instance] Complex.partialOrder end _root_.ComplexOrder open ComplexOrder theorem le_def {z w : ℂ} : z ≤ w ↔ z.re ≤ w.re ∧ z.im = w.im := Iff.rfl theorem lt_def {z w : ℂ} : z < w ↔ z.re < w.re ∧ z.im = w.im := Iff.rfl theorem nonneg_iff {z : ℂ} : 0 ≤ z ↔ 0 ≤ z.re ∧ 0 = z.im := le_def theorem pos_iff {z : ℂ} : 0 < z ↔ 0 < z.re ∧ 0 = z.im := lt_def @[simp, norm_cast] theorem real_le_real {x y : ℝ} : (x : ℂ) ≤ (y : ℂ) ↔ x ≤ y := by simp [le_def, ofReal'] @[simp, norm_cast] theorem real_lt_real {x y : ℝ} : (x : ℂ) < (y : ℂ) ↔ x < y := by simp [lt_def, ofReal'] @[simp, norm_cast] theorem zero_le_real {x : ℝ} : (0 : ℂ) ≤ (x : ℂ) ↔ 0 ≤ x := real_le_real @[simp, norm_cast] theorem zero_lt_real {x : ℝ} : (0 : ℂ) < (x : ℂ) ↔ 0 < x := real_lt_real theorem not_le_iff {z w : ℂ} : ¬z ≤ w ↔ w.re < z.re ∨ z.im ≠ w.im := by rw [le_def, not_and_or, not_le] theorem not_lt_iff {z w : ℂ} : ¬z < w ↔ w.re ≤ z.re ∨ z.im ≠ w.im := by rw [lt_def, not_and_or, not_lt] theorem not_le_zero_iff {z : ℂ} : ¬z ≤ 0 ↔ 0 < z.re ∨ z.im ≠ 0 := not_le_iff theorem not_lt_zero_iff {z : ℂ} : ¬z < 0 ↔ 0 ≤ z.re ∨ z.im ≠ 0 := not_lt_iff theorem eq_re_of_ofReal_le {r : ℝ} {z : ℂ} (hz : (r : ℂ) ≤ z) : z = z.re := by rw [eq_comm, ← conj_eq_iff_re, conj_eq_iff_im, ← (Complex.le_def.1 hz).2, Complex.ofReal_im] @[simp] lemma re_eq_abs {z : ℂ} : z.re = abs z ↔ 0 ≤ z := have : 0 ≤ abs z := apply_nonneg abs z ⟨fun h ↦ ⟨h.symm ▸ this, (abs_re_eq_abs.1 <| h.symm ▸ _root_.abs_of_nonneg this).symm⟩, fun ⟨h₁, h₂⟩ ↦ by rw [← abs_re_eq_abs.2 h₂.symm, _root_.abs_of_nonneg h₁]⟩ @[simp] lemma neg_re_eq_abs {z : ℂ} : -z.re = abs z ↔ z ≤ 0 := by rw [← neg_re, ← abs.map_neg, re_eq_abs] exact neg_nonneg.and <| eq_comm.trans neg_eq_zero @[simp] lemma re_eq_neg_abs {z : ℂ} : z.re = -abs z ↔ z ≤ 0 := by rw [← neg_eq_iff_eq_neg, neg_re_eq_abs] lemma monotone_ofReal : Monotone ofReal' := by intro x y hxy simp only [ofReal_eq_coe, real_le_real, hxy] end Complex namespace Mathlib.Meta.Positivity open Lean Meta Qq Complex open scoped ComplexOrder private alias ⟨_, ofReal_pos⟩ := zero_lt_real private alias ⟨_, ofReal_nonneg⟩ := zero_le_real private alias ⟨_, ofReal_ne_zero_of_ne_zero⟩ := ofReal_ne_zero /-- Extension for the `positivity` tactic: `Complex.ofReal` is positive/nonnegative/nonzero if its input is. -/ @[positivity Complex.ofReal' _, Complex.ofReal _] def evalComplexOfReal : PositivityExt where eval {u α} _ _ e := do -- TODO: Can we avoid duplicating the code? match u, α, e with | 0, ~q(ℂ), ~q(Complex.ofReal' $a) => assumeInstancesCommute match ← core q(inferInstance) q(inferInstance) a with | .positive pa => return .positive q(ofReal_pos $pa) | .nonnegative pa => return .nonnegative q(ofReal_nonneg $pa) | .nonzero pa => return .nonzero q(ofReal_ne_zero_of_ne_zero $pa) | _ => return .none | 0, ~q(ℂ), ~q(Complex.ofReal $a) => assumeInstancesCommute match ← core q(inferInstance) q(inferInstance) a with | .positive pa => return .positive q(ofReal_pos $pa) | .nonnegative pa => return .nonnegative q(ofReal_nonneg $pa) | .nonzero pa => return .nonzero q(ofReal_ne_zero_of_ne_zero $pa) | _ => return .none | _, _ => throwError "not Complex.ofReal'" example (x : ℝ) (hx : 0 < x) : 0 < (x : ℂ) := by positivity example (x : ℝ) (hx : 0 ≤ x) : 0 ≤ (x : ℂ) := by positivity example (x : ℝ) (hx : x ≠ 0) : (x : ℂ) ≠ 0 := by positivity end Mathlib.Meta.Positivity
Data\Complex\Orientation.lean
/- Copyright (c) 2021 Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth -/ import Mathlib.Data.Complex.Module import Mathlib.LinearAlgebra.Orientation /-! # The standard orientation on `ℂ`. This had previously been in `LinearAlgebra.Orientation`, but keeping it separate results in a significant import reduction. -/ namespace Complex /-- The standard orientation on `ℂ`. -/ protected noncomputable def orientation : Orientation ℝ ℂ (Fin 2) := Complex.basisOneI.orientation end Complex
Data\Countable\Basic.lean
/- Copyright (c) 2022 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import Mathlib.Logic.Equiv.Nat import Mathlib.Logic.Equiv.Fin import Mathlib.Data.Countable.Defs /-! # Countable types In this file we provide basic instances of the `Countable` typeclass defined elsewhere. -/ universe u v w open Function instance : Countable ℤ := Countable.of_equiv ℕ Equiv.intEquivNat.symm /-! ### Definition in terms of `Function.Embedding` -/ section Embedding variable {α : Sort u} {β : Sort v} theorem countable_iff_nonempty_embedding : Countable α ↔ Nonempty (α ↪ ℕ) := ⟨fun ⟨⟨f, hf⟩⟩ => ⟨⟨f, hf⟩⟩, fun ⟨f⟩ => ⟨⟨f, f.2⟩⟩⟩ theorem uncountable_iff_isEmpty_embedding : Uncountable α ↔ IsEmpty (α ↪ ℕ) := by rw [← not_countable_iff, countable_iff_nonempty_embedding, not_nonempty_iff] theorem nonempty_embedding_nat (α) [Countable α] : Nonempty (α ↪ ℕ) := countable_iff_nonempty_embedding.1 ‹_› protected theorem Function.Embedding.countable [Countable β] (f : α ↪ β) : Countable α := f.injective.countable protected lemma Function.Embedding.uncountable [Uncountable α] (f : α ↪ β) : Uncountable β := f.injective.uncountable end Embedding /-! ### Operations on `Type*`s -/ section type variable {α : Type u} {β : Type v} {π : α → Type w} instance [Countable α] [Countable β] : Countable (α ⊕ β) := by rcases exists_injective_nat α with ⟨f, hf⟩ rcases exists_injective_nat β with ⟨g, hg⟩ exact (Equiv.natSumNatEquivNat.injective.comp <| hf.sum_map hg).countable instance Sum.uncountable_inl [Uncountable α] : Uncountable (α ⊕ β) := inl_injective.uncountable instance Sum.uncountable_inr [Uncountable β] : Uncountable (α ⊕ β) := inr_injective.uncountable instance [Countable α] : Countable (Option α) := Countable.of_equiv _ (Equiv.optionEquivSumPUnit.{_, 0} α).symm instance Option.instUncountable [Uncountable α] : Uncountable (Option α) := Injective.uncountable fun _ _ ↦ Option.some_inj.1 instance [Countable α] [Countable β] : Countable (α × β) := by rcases exists_injective_nat α with ⟨f, hf⟩ rcases exists_injective_nat β with ⟨g, hg⟩ exact (Nat.pairEquiv.injective.comp <| hf.prodMap hg).countable instance [Uncountable α] [Nonempty β] : Uncountable (α × β) := by inhabit β exact (Prod.mk.inj_right default).uncountable instance [Nonempty α] [Uncountable β] : Uncountable (α × β) := by inhabit α exact (Prod.mk.inj_left default).uncountable instance [Countable α] [∀ a, Countable (π a)] : Countable (Sigma π) := by rcases exists_injective_nat α with ⟨f, hf⟩ choose g hg using fun a => exists_injective_nat (π a) exact ((Equiv.sigmaEquivProd ℕ ℕ).injective.comp <| hf.sigma_map hg).countable lemma Sigma.uncountable (a : α) [Uncountable (π a)] : Uncountable (Sigma π) := (sigma_mk_injective (i := a)).uncountable instance [Nonempty α] [∀ a, Uncountable (π a)] : Uncountable (Sigma π) := by inhabit α; exact Sigma.uncountable default instance (priority := 500) SetCoe.countable [Countable α] (s : Set α) : Countable s := Subtype.countable end type section sort variable {α : Sort u} {β : Sort v} {π : α → Sort w} /-! ### Operations on `Sort*`s -/ instance [Countable α] [Countable β] : Countable (α ⊕' β) := Countable.of_equiv (PLift α ⊕ PLift β) (Equiv.plift.sumPSum Equiv.plift) instance [Countable α] [Countable β] : Countable (PProd α β) := Countable.of_equiv (PLift α × PLift β) (Equiv.plift.prodPProd Equiv.plift) instance [Countable α] [∀ a, Countable (π a)] : Countable (PSigma π) := Countable.of_equiv (Σa : PLift α, PLift (π a.down)) (Equiv.psigmaEquivSigmaPLift π).symm instance [Finite α] [∀ a, Countable (π a)] : Countable (∀ a, π a) := by have : ∀ n, Countable (Fin n → ℕ) := by intro n induction' n with n ihn · change Countable (Fin 0 → ℕ); infer_instance · haveI := ihn exact Countable.of_equiv (ℕ × (Fin n → ℕ)) (Equiv.piFinSucc _ _).symm rcases Finite.exists_equiv_fin α with ⟨n, ⟨e⟩⟩ have f := fun a => (nonempty_embedding_nat (π a)).some exact ((Embedding.piCongrRight f).trans (Equiv.piCongrLeft' _ e).toEmbedding).countable end sort
Data\Countable\Defs.lean
/- Copyright (c) 2022 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import Mathlib.Data.Finite.Defs import Mathlib.Data.Bool.Basic import Mathlib.Data.Subtype import Mathlib.Tactic.MkIffOfInductiveProp /-! # Countable and uncountable types In this file we define a typeclass `Countable` saying that a given `Sort*` is countable and a typeclass `Uncountable` saying that a given `Type*` is uncountable. See also `Encodable` for a version that singles out a specific encoding of elements of `α` by natural numbers. This file also provides a few instances of these typeclasses. More instances can be found in other files. -/ open Function universe u v variable {α : Sort u} {β : Sort v} /-! ### Definition and basic properties -/ /-- A type `α` is countable if there exists an injective map `α → ℕ`. -/ @[mk_iff countable_iff_exists_injective] class Countable (α : Sort u) : Prop where /-- A type `α` is countable if there exists an injective map `α → ℕ`. -/ exists_injective_nat' : ∃ f : α → ℕ, Injective f lemma Countable.exists_injective_nat (α : Sort u) [Countable α] : ∃ f : α → ℕ, Injective f := Countable.exists_injective_nat' instance : Countable ℕ := ⟨⟨id, injective_id⟩⟩ export Countable (exists_injective_nat) protected theorem Function.Injective.countable [Countable β] {f : α → β} (hf : Injective f) : Countable α := let ⟨g, hg⟩ := exists_injective_nat β ⟨⟨g ∘ f, hg.comp hf⟩⟩ protected theorem Function.Surjective.countable [Countable α] {f : α → β} (hf : Surjective f) : Countable β := (injective_surjInv hf).countable theorem exists_surjective_nat (α : Sort u) [Nonempty α] [Countable α] : ∃ f : ℕ → α, Surjective f := let ⟨f, hf⟩ := exists_injective_nat α ⟨invFun f, invFun_surjective hf⟩ theorem countable_iff_exists_surjective [Nonempty α] : Countable α ↔ ∃ f : ℕ → α, Surjective f := ⟨@exists_surjective_nat _ _, fun ⟨_, hf⟩ ↦ hf.countable⟩ theorem Countable.of_equiv (α : Sort*) [Countable α] (e : α ≃ β) : Countable β := e.symm.injective.countable theorem Equiv.countable_iff (e : α ≃ β) : Countable α ↔ Countable β := ⟨fun h => @Countable.of_equiv _ _ h e, fun h => @Countable.of_equiv _ _ h e.symm⟩ instance {β : Type v} [Countable β] : Countable (ULift.{u} β) := Countable.of_equiv _ Equiv.ulift.symm /-! ### Operations on `Sort*`s -/ instance [Countable α] : Countable (PLift α) := Equiv.plift.injective.countable instance (priority := 100) Subsingleton.to_countable [Subsingleton α] : Countable α := ⟨⟨fun _ => 0, fun x y _ => Subsingleton.elim x y⟩⟩ instance (priority := 500) Subtype.countable [Countable α] {p : α → Prop} : Countable { x // p x } := Subtype.val_injective.countable instance {n : ℕ} : Countable (Fin n) := Function.Injective.countable (@Fin.eq_of_val_eq n) instance (priority := 100) Finite.to_countable [Finite α] : Countable α := let ⟨_, ⟨e⟩⟩ := Finite.exists_equiv_fin α Countable.of_equiv _ e.symm instance : Countable PUnit.{u} := Subsingleton.to_countable instance (priority := 100) Prop.countable (p : Prop) : Countable p := Subsingleton.to_countable instance Bool.countable : Countable Bool := ⟨⟨fun b => cond b 0 1, Bool.injective_iff.2 Nat.one_ne_zero⟩⟩ instance Prop.countable' : Countable Prop := Countable.of_equiv Bool Equiv.propEquivBool.symm instance (priority := 500) Quotient.countable [Countable α] {r : α → α → Prop} : Countable (Quot r) := (surjective_quot_mk r).countable instance (priority := 500) [Countable α] {s : Setoid α} : Countable (Quotient s) := (inferInstance : Countable (@Quot α _)) /-! ### Uncountable types -/ /-- A type `α` is uncountable if it is not countable. -/ @[mk_iff uncountable_iff_not_countable] class Uncountable (α : Sort*) : Prop where /-- A type `α` is uncountable if it is not countable. -/ not_countable : ¬Countable α lemma not_uncountable_iff : ¬Uncountable α ↔ Countable α := by rw [uncountable_iff_not_countable, not_not] lemma not_countable_iff : ¬Countable α ↔ Uncountable α := (uncountable_iff_not_countable α).symm @[simp] lemma not_uncountable [Countable α] : ¬Uncountable α := not_uncountable_iff.2 ‹_› @[simp] lemma not_countable [Uncountable α] : ¬Countable α := Uncountable.not_countable protected theorem Function.Injective.uncountable [Uncountable α] {f : α → β} (hf : Injective f) : Uncountable β := ⟨fun _ ↦ not_countable hf.countable⟩ protected theorem Function.Surjective.uncountable [Uncountable β] {f : α → β} (hf : Surjective f) : Uncountable α := (injective_surjInv hf).uncountable lemma not_injective_uncountable_countable [Uncountable α] [Countable β] (f : α → β) : ¬Injective f := fun hf ↦ not_countable hf.countable lemma not_surjective_countable_uncountable [Countable α] [Uncountable β] (f : α → β) : ¬Surjective f := fun hf ↦ not_countable hf.countable theorem uncountable_iff_forall_not_surjective [Nonempty α] : Uncountable α ↔ ∀ f : ℕ → α, ¬Surjective f := by rw [← not_countable_iff, countable_iff_exists_surjective, not_exists] theorem Uncountable.of_equiv (α : Sort*) [Uncountable α] (e : α ≃ β) : Uncountable β := e.injective.uncountable theorem Equiv.uncountable_iff (e : α ≃ β) : Uncountable α ↔ Uncountable β := ⟨fun h => @Uncountable.of_equiv _ _ h e, fun h => @Uncountable.of_equiv _ _ h e.symm⟩ instance {β : Type v} [Uncountable β] : Uncountable (ULift.{u} β) := .of_equiv _ Equiv.ulift.symm instance [Uncountable α] : Uncountable (PLift α) := .of_equiv _ Equiv.plift.symm instance (priority := 100) [Uncountable α] : Infinite α := ⟨fun _ ↦ not_countable (α := α) inferInstance⟩
Data\Countable\Small.lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import Mathlib.Logic.Small.Basic import Mathlib.Data.Countable.Defs /-! # All countable types are small. That is, any countable type is equivalent to a type in any universe. -/ universe w v instance (priority := 100) Countable.toSmall (α : Type v) [Countable α] : Small.{w} α := let ⟨_, hf⟩ := exists_injective_nat α small_of_injective hf @[deprecated (since := "2024-03-20"), nolint defLemma] alias small_of_countable := Countable.toSmall @[deprecated (since := "2024-03-20"), nolint defLemma] alias small_of_fintype := Countable.toSmall
Data\DFinsupp\Basic.lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Kenny Lau -/ import Mathlib.Algebra.BigOperators.GroupWithZero.Finset import Mathlib.Algebra.Group.Submonoid.Membership import Mathlib.Algebra.GroupWithZero.Action.Pi import Mathlib.Algebra.Module.LinearMap.Defs import Mathlib.Data.Finset.Preimage import Mathlib.Data.Fintype.Quotient import Mathlib.Data.Set.Finite import Mathlib.GroupTheory.GroupAction.BigOperators import Mathlib.Order.ConditionallyCompleteLattice.Basic /-! # Dependent functions with finite support For a non-dependent version see `data/finsupp.lean`. ## Notation This file introduces the notation `Π₀ a, β a` as notation for `DFinsupp β`, mirroring the `α →₀ β` notation used for `Finsupp`. This works for nested binders too, with `Π₀ a b, γ a b` as notation for `DFinsupp (fun a ↦ DFinsupp (γ a))`. ## Implementation notes The support is internally represented (in the primed `DFinsupp.support'`) as a `Multiset` that represents a superset of the true support of the function, quotiented by the always-true relation so that this does not impact equality. This approach has computational benefits over storing a `Finset`; it allows us to add together two finitely-supported functions without having to evaluate the resulting function to recompute its support (which would required decidability of `b = 0` for `b : β i`). The true support of the function can still be recovered with `DFinsupp.support`; but these decidability obligations are now postponed to when the support is actually needed. As a consequence, there are two ways to sum a `DFinsupp`: with `DFinsupp.sum` which works over an arbitrary function but requires recomputation of the support and therefore a `Decidable` argument; and with `DFinsupp.sumAddHom` which requires an additive morphism, using its properties to show that summing over a superset of the support is sufficient. `Finsupp` takes an altogether different approach here; it uses `Classical.Decidable` and declares the `Add` instance as noncomputable. This design difference is independent of the fact that `DFinsupp` is dependently-typed and `Finsupp` is not; in future, we may want to align these two definitions, or introduce two more definitions for the other combinations of decisions. -/ universe u u₁ u₂ v v₁ v₂ v₃ w x y l variable {ι : Type u} {γ : Type w} {β : ι → Type v} {β₁ : ι → Type v₁} {β₂ : ι → Type v₂} variable (β) /-- A dependent function `Π i, β i` with finite support, with notation `Π₀ i, β i`. Note that `DFinsupp.support` is the preferred API for accessing the support of the function, `DFinsupp.support'` is an implementation detail that aids computability; see the implementation notes in this file for more information. -/ structure DFinsupp [∀ i, Zero (β i)] : Type max u v where mk' :: /-- The underlying function of a dependent function with finite support (aka `DFinsupp`). -/ toFun : ∀ i, β i /-- The support of a dependent function with finite support (aka `DFinsupp`). -/ support' : Trunc { s : Multiset ι // ∀ i, i ∈ s ∨ toFun i = 0 } variable {β} /-- `Π₀ i, β i` denotes the type of dependent functions with finite support `DFinsupp β`. -/ notation3 "Π₀ "(...)", "r:(scoped f => DFinsupp f) => r namespace DFinsupp section Basic variable [∀ i, Zero (β i)] [∀ i, Zero (β₁ i)] [∀ i, Zero (β₂ i)] instance instDFunLike : DFunLike (Π₀ i, β i) ι β := ⟨fun f => f.toFun, fun ⟨f₁, s₁⟩ ⟨f₂, s₁⟩ ↦ fun (h : f₁ = f₂) ↦ by subst h congr subsingleton ⟩ /-- Helper instance for when there are too many metavariables to apply `DFunLike.coeFunForall` directly. -/ instance : CoeFun (Π₀ i, β i) fun _ => ∀ i, β i := inferInstance @[simp] theorem toFun_eq_coe (f : Π₀ i, β i) : f.toFun = f := rfl @[ext] theorem ext {f g : Π₀ i, β i} (h : ∀ i, f i = g i) : f = g := DFunLike.ext _ _ h lemma ne_iff {f g : Π₀ i, β i} : f ≠ g ↔ ∃ i, f i ≠ g i := DFunLike.ne_iff instance : Zero (Π₀ i, β i) := ⟨⟨0, Trunc.mk <| ⟨∅, fun _ => Or.inr rfl⟩⟩⟩ instance : Inhabited (Π₀ i, β i) := ⟨0⟩ @[simp, norm_cast] lemma coe_mk' (f : ∀ i, β i) (s) : ⇑(⟨f, s⟩ : Π₀ i, β i) = f := rfl @[simp, norm_cast] lemma coe_zero : ⇑(0 : Π₀ i, β i) = 0 := rfl theorem zero_apply (i : ι) : (0 : Π₀ i, β i) i = 0 := rfl /-- The composition of `f : β₁ → β₂` and `g : Π₀ i, β₁ i` is `mapRange f hf g : Π₀ i, β₂ i`, well defined when `f 0 = 0`. This preserves the structure on `f`, and exists in various bundled forms for when `f` is itself bundled: * `DFinsupp.mapRange.addMonoidHom` * `DFinsupp.mapRange.addEquiv` * `dfinsupp.mapRange.linearMap` * `dfinsupp.mapRange.linearEquiv` -/ def mapRange (f : ∀ i, β₁ i → β₂ i) (hf : ∀ i, f i 0 = 0) (x : Π₀ i, β₁ i) : Π₀ i, β₂ i := ⟨fun i => f i (x i), x.support'.map fun s => ⟨s.1, fun i => (s.2 i).imp_right fun h : x i = 0 => by rw [← hf i, ← h]⟩⟩ @[simp] theorem mapRange_apply (f : ∀ i, β₁ i → β₂ i) (hf : ∀ i, f i 0 = 0) (g : Π₀ i, β₁ i) (i : ι) : mapRange f hf g i = f i (g i) := rfl @[simp] theorem mapRange_id (h : ∀ i, id (0 : β₁ i) = 0 := fun i => rfl) (g : Π₀ i : ι, β₁ i) : mapRange (fun i => (id : β₁ i → β₁ i)) h g = g := by ext rfl theorem mapRange_comp (f : ∀ i, β₁ i → β₂ i) (f₂ : ∀ i, β i → β₁ i) (hf : ∀ i, f i 0 = 0) (hf₂ : ∀ i, f₂ i 0 = 0) (h : ∀ i, (f i ∘ f₂ i) 0 = 0) (g : Π₀ i : ι, β i) : mapRange (fun i => f i ∘ f₂ i) h g = mapRange f hf (mapRange f₂ hf₂ g) := by ext simp only [mapRange_apply]; rfl @[simp] theorem mapRange_zero (f : ∀ i, β₁ i → β₂ i) (hf : ∀ i, f i 0 = 0) : mapRange f hf (0 : Π₀ i, β₁ i) = 0 := by ext simp only [mapRange_apply, coe_zero, Pi.zero_apply, hf] /-- Let `f i` be a binary operation `β₁ i → β₂ i → β i` such that `f i 0 0 = 0`. Then `zipWith f hf` is a binary operation `Π₀ i, β₁ i → Π₀ i, β₂ i → Π₀ i, β i`. -/ def zipWith (f : ∀ i, β₁ i → β₂ i → β i) (hf : ∀ i, f i 0 0 = 0) (x : Π₀ i, β₁ i) (y : Π₀ i, β₂ i) : Π₀ i, β i := ⟨fun i => f i (x i) (y i), by refine x.support'.bind fun xs => ?_ refine y.support'.map fun ys => ?_ refine ⟨xs + ys, fun i => ?_⟩ obtain h1 | (h1 : x i = 0) := xs.prop i · left rw [Multiset.mem_add] left exact h1 obtain h2 | (h2 : y i = 0) := ys.prop i · left rw [Multiset.mem_add] right exact h2 right; rw [← hf, ← h1, ← h2]⟩ @[simp] theorem zipWith_apply (f : ∀ i, β₁ i → β₂ i → β i) (hf : ∀ i, f i 0 0 = 0) (g₁ : Π₀ i, β₁ i) (g₂ : Π₀ i, β₂ i) (i : ι) : zipWith f hf g₁ g₂ i = f i (g₁ i) (g₂ i) := rfl section Piecewise variable (x y : Π₀ i, β i) (s : Set ι) [∀ i, Decidable (i ∈ s)] /-- `x.piecewise y s` is the finitely supported function equal to `x` on the set `s`, and to `y` on its complement. -/ def piecewise : Π₀ i, β i := zipWith (fun i x y => if i ∈ s then x else y) (fun _ => ite_self 0) x y theorem piecewise_apply (i : ι) : x.piecewise y s i = if i ∈ s then x i else y i := zipWith_apply _ _ x y i @[simp, norm_cast] theorem coe_piecewise : ⇑(x.piecewise y s) = s.piecewise x y := by ext apply piecewise_apply end Piecewise end Basic section Algebra instance [∀ i, AddZeroClass (β i)] : Add (Π₀ i, β i) := ⟨zipWith (fun _ => (· + ·)) fun _ => add_zero 0⟩ theorem add_apply [∀ i, AddZeroClass (β i)] (g₁ g₂ : Π₀ i, β i) (i : ι) : (g₁ + g₂) i = g₁ i + g₂ i := rfl @[simp, norm_cast] theorem coe_add [∀ i, AddZeroClass (β i)] (g₁ g₂ : Π₀ i, β i) : ⇑(g₁ + g₂) = g₁ + g₂ := rfl instance addZeroClass [∀ i, AddZeroClass (β i)] : AddZeroClass (Π₀ i, β i) := DFunLike.coe_injective.addZeroClass _ coe_zero coe_add instance instIsLeftCancelAdd [∀ i, AddZeroClass (β i)] [∀ i, IsLeftCancelAdd (β i)] : IsLeftCancelAdd (Π₀ i, β i) where add_left_cancel _ _ _ h := ext fun x => add_left_cancel <| DFunLike.congr_fun h x instance instIsRightCancelAdd [∀ i, AddZeroClass (β i)] [∀ i, IsRightCancelAdd (β i)] : IsRightCancelAdd (Π₀ i, β i) where add_right_cancel _ _ _ h := ext fun x => add_right_cancel <| DFunLike.congr_fun h x instance instIsCancelAdd [∀ i, AddZeroClass (β i)] [∀ i, IsCancelAdd (β i)] : IsCancelAdd (Π₀ i, β i) where /-- Note the general `SMul` instance doesn't apply as `ℕ` is not distributive unless `β i`'s addition is commutative. -/ instance hasNatScalar [∀ i, AddMonoid (β i)] : SMul ℕ (Π₀ i, β i) := ⟨fun c v => v.mapRange (fun _ => (c • ·)) fun _ => nsmul_zero _⟩ theorem nsmul_apply [∀ i, AddMonoid (β i)] (b : ℕ) (v : Π₀ i, β i) (i : ι) : (b • v) i = b • v i := rfl @[simp, norm_cast] theorem coe_nsmul [∀ i, AddMonoid (β i)] (b : ℕ) (v : Π₀ i, β i) : ⇑(b • v) = b • ⇑v := rfl instance [∀ i, AddMonoid (β i)] : AddMonoid (Π₀ i, β i) := DFunLike.coe_injective.addMonoid _ coe_zero coe_add fun _ _ => coe_nsmul _ _ /-- Coercion from a `DFinsupp` to a pi type is an `AddMonoidHom`. -/ def coeFnAddMonoidHom [∀ i, AddZeroClass (β i)] : (Π₀ i, β i) →+ ∀ i, β i where toFun := (⇑) map_zero' := coe_zero map_add' := coe_add /-- Evaluation at a point is an `AddMonoidHom`. This is the finitely-supported version of `Pi.evalAddMonoidHom`. -/ def evalAddMonoidHom [∀ i, AddZeroClass (β i)] (i : ι) : (Π₀ i, β i) →+ β i := (Pi.evalAddMonoidHom β i).comp coeFnAddMonoidHom instance addCommMonoid [∀ i, AddCommMonoid (β i)] : AddCommMonoid (Π₀ i, β i) := DFunLike.coe_injective.addCommMonoid _ coe_zero coe_add fun _ _ => coe_nsmul _ _ @[simp, norm_cast] theorem coe_finset_sum {α} [∀ i, AddCommMonoid (β i)] (s : Finset α) (g : α → Π₀ i, β i) : ⇑(∑ a ∈ s, g a) = ∑ a ∈ s, ⇑(g a) := map_sum coeFnAddMonoidHom g s @[simp] theorem finset_sum_apply {α} [∀ i, AddCommMonoid (β i)] (s : Finset α) (g : α → Π₀ i, β i) (i : ι) : (∑ a ∈ s, g a) i = ∑ a ∈ s, g a i := map_sum (evalAddMonoidHom i) g s instance [∀ i, AddGroup (β i)] : Neg (Π₀ i, β i) := ⟨fun f => f.mapRange (fun _ => Neg.neg) fun _ => neg_zero⟩ theorem neg_apply [∀ i, AddGroup (β i)] (g : Π₀ i, β i) (i : ι) : (-g) i = -g i := rfl @[simp, norm_cast] lemma coe_neg [∀ i, AddGroup (β i)] (g : Π₀ i, β i) : ⇑(-g) = -g := rfl instance [∀ i, AddGroup (β i)] : Sub (Π₀ i, β i) := ⟨zipWith (fun _ => Sub.sub) fun _ => sub_zero 0⟩ theorem sub_apply [∀ i, AddGroup (β i)] (g₁ g₂ : Π₀ i, β i) (i : ι) : (g₁ - g₂) i = g₁ i - g₂ i := rfl @[simp, norm_cast] theorem coe_sub [∀ i, AddGroup (β i)] (g₁ g₂ : Π₀ i, β i) : ⇑(g₁ - g₂) = g₁ - g₂ := rfl /-- Note the general `SMul` instance doesn't apply as `ℤ` is not distributive unless `β i`'s addition is commutative. -/ instance hasIntScalar [∀ i, AddGroup (β i)] : SMul ℤ (Π₀ i, β i) := ⟨fun c v => v.mapRange (fun _ => (c • ·)) fun _ => zsmul_zero _⟩ theorem zsmul_apply [∀ i, AddGroup (β i)] (b : ℤ) (v : Π₀ i, β i) (i : ι) : (b • v) i = b • v i := rfl @[simp, norm_cast] theorem coe_zsmul [∀ i, AddGroup (β i)] (b : ℤ) (v : Π₀ i, β i) : ⇑(b • v) = b • ⇑v := rfl instance [∀ i, AddGroup (β i)] : AddGroup (Π₀ i, β i) := DFunLike.coe_injective.addGroup _ coe_zero coe_add coe_neg coe_sub (fun _ _ => coe_nsmul _ _) fun _ _ => coe_zsmul _ _ instance addCommGroup [∀ i, AddCommGroup (β i)] : AddCommGroup (Π₀ i, β i) := DFunLike.coe_injective.addCommGroup _ coe_zero coe_add coe_neg coe_sub (fun _ _ => coe_nsmul _ _) fun _ _ => coe_zsmul _ _ /-- Dependent functions with finite support inherit a semiring action from an action on each coordinate. -/ instance [Monoid γ] [∀ i, AddMonoid (β i)] [∀ i, DistribMulAction γ (β i)] : SMul γ (Π₀ i, β i) := ⟨fun c v => v.mapRange (fun _ => (c • ·)) fun _ => smul_zero _⟩ theorem smul_apply [Monoid γ] [∀ i, AddMonoid (β i)] [∀ i, DistribMulAction γ (β i)] (b : γ) (v : Π₀ i, β i) (i : ι) : (b • v) i = b • v i := rfl @[simp, norm_cast] theorem coe_smul [Monoid γ] [∀ i, AddMonoid (β i)] [∀ i, DistribMulAction γ (β i)] (b : γ) (v : Π₀ i, β i) : ⇑(b • v) = b • ⇑v := rfl instance smulCommClass {δ : Type*} [Monoid γ] [Monoid δ] [∀ i, AddMonoid (β i)] [∀ i, DistribMulAction γ (β i)] [∀ i, DistribMulAction δ (β i)] [∀ i, SMulCommClass γ δ (β i)] : SMulCommClass γ δ (Π₀ i, β i) where smul_comm r s m := ext fun i => by simp only [smul_apply, smul_comm r s (m i)] instance isScalarTower {δ : Type*} [Monoid γ] [Monoid δ] [∀ i, AddMonoid (β i)] [∀ i, DistribMulAction γ (β i)] [∀ i, DistribMulAction δ (β i)] [SMul γ δ] [∀ i, IsScalarTower γ δ (β i)] : IsScalarTower γ δ (Π₀ i, β i) where smul_assoc r s m := ext fun i => by simp only [smul_apply, smul_assoc r s (m i)] instance isCentralScalar [Monoid γ] [∀ i, AddMonoid (β i)] [∀ i, DistribMulAction γ (β i)] [∀ i, DistribMulAction γᵐᵒᵖ (β i)] [∀ i, IsCentralScalar γ (β i)] : IsCentralScalar γ (Π₀ i, β i) where op_smul_eq_smul r m := ext fun i => by simp only [smul_apply, op_smul_eq_smul r (m i)] /-- Dependent functions with finite support inherit a `DistribMulAction` structure from such a structure on each coordinate. -/ instance distribMulAction [Monoid γ] [∀ i, AddMonoid (β i)] [∀ i, DistribMulAction γ (β i)] : DistribMulAction γ (Π₀ i, β i) := Function.Injective.distribMulAction coeFnAddMonoidHom DFunLike.coe_injective coe_smul /-- Dependent functions with finite support inherit a module structure from such a structure on each coordinate. -/ instance module [Semiring γ] [∀ i, AddCommMonoid (β i)] [∀ i, Module γ (β i)] : Module γ (Π₀ i, β i) := { inferInstanceAs (DistribMulAction γ (Π₀ i, β i)) with zero_smul := fun c => ext fun i => by simp only [smul_apply, zero_smul, zero_apply] add_smul := fun c x y => ext fun i => by simp only [add_apply, smul_apply, add_smul] } end Algebra section FilterAndSubtypeDomain /-- `Filter p f` is the function which is `f i` if `p i` is true and 0 otherwise. -/ def filter [∀ i, Zero (β i)] (p : ι → Prop) [DecidablePred p] (x : Π₀ i, β i) : Π₀ i, β i := ⟨fun i => if p i then x i else 0, x.support'.map fun xs => ⟨xs.1, fun i => (xs.prop i).imp_right fun H : x i = 0 => by simp only [H, ite_self]⟩⟩ @[simp] theorem filter_apply [∀ i, Zero (β i)] (p : ι → Prop) [DecidablePred p] (i : ι) (f : Π₀ i, β i) : f.filter p i = if p i then f i else 0 := rfl theorem filter_apply_pos [∀ i, Zero (β i)] {p : ι → Prop} [DecidablePred p] (f : Π₀ i, β i) {i : ι} (h : p i) : f.filter p i = f i := by simp only [filter_apply, if_pos h] theorem filter_apply_neg [∀ i, Zero (β i)] {p : ι → Prop} [DecidablePred p] (f : Π₀ i, β i) {i : ι} (h : ¬p i) : f.filter p i = 0 := by simp only [filter_apply, if_neg h] theorem filter_pos_add_filter_neg [∀ i, AddZeroClass (β i)] (f : Π₀ i, β i) (p : ι → Prop) [DecidablePred p] : (f.filter p + f.filter fun i => ¬p i) = f := ext fun i => by simp only [add_apply, filter_apply]; split_ifs <;> simp only [add_zero, zero_add] @[simp] theorem filter_zero [∀ i, Zero (β i)] (p : ι → Prop) [DecidablePred p] : (0 : Π₀ i, β i).filter p = 0 := by ext simp @[simp] theorem filter_add [∀ i, AddZeroClass (β i)] (p : ι → Prop) [DecidablePred p] (f g : Π₀ i, β i) : (f + g).filter p = f.filter p + g.filter p := by ext simp [ite_add_zero] @[simp] theorem filter_smul [Monoid γ] [∀ i, AddMonoid (β i)] [∀ i, DistribMulAction γ (β i)] (p : ι → Prop) [DecidablePred p] (r : γ) (f : Π₀ i, β i) : (r • f).filter p = r • f.filter p := by ext simp [smul_apply, smul_ite] variable (γ β) /-- `DFinsupp.filter` as an `AddMonoidHom`. -/ @[simps] def filterAddMonoidHom [∀ i, AddZeroClass (β i)] (p : ι → Prop) [DecidablePred p] : (Π₀ i, β i) →+ Π₀ i, β i where toFun := filter p map_zero' := filter_zero p map_add' := filter_add p /-- `DFinsupp.filter` as a `LinearMap`. -/ @[simps] def filterLinearMap [Semiring γ] [∀ i, AddCommMonoid (β i)] [∀ i, Module γ (β i)] (p : ι → Prop) [DecidablePred p] : (Π₀ i, β i) →ₗ[γ] Π₀ i, β i where toFun := filter p map_add' := filter_add p map_smul' := filter_smul p variable {γ β} @[simp] theorem filter_neg [∀ i, AddGroup (β i)] (p : ι → Prop) [DecidablePred p] (f : Π₀ i, β i) : (-f).filter p = -f.filter p := (filterAddMonoidHom β p).map_neg f @[simp] theorem filter_sub [∀ i, AddGroup (β i)] (p : ι → Prop) [DecidablePred p] (f g : Π₀ i, β i) : (f - g).filter p = f.filter p - g.filter p := (filterAddMonoidHom β p).map_sub f g /-- `subtypeDomain p f` is the restriction of the finitely supported function `f` to the subtype `p`. -/ def subtypeDomain [∀ i, Zero (β i)] (p : ι → Prop) [DecidablePred p] (x : Π₀ i, β i) : Π₀ i : Subtype p, β i := ⟨fun i => x (i : ι), x.support'.map fun xs => ⟨(Multiset.filter p xs.1).attach.map fun j => ⟨j.1, (Multiset.mem_filter.1 j.2).2⟩, fun i => (xs.prop i).imp_left fun H => Multiset.mem_map.2 ⟨⟨i, Multiset.mem_filter.2 ⟨H, i.2⟩⟩, Multiset.mem_attach _ _, Subtype.eta _ _⟩⟩⟩ @[simp] theorem subtypeDomain_zero [∀ i, Zero (β i)] {p : ι → Prop} [DecidablePred p] : subtypeDomain p (0 : Π₀ i, β i) = 0 := rfl @[simp] theorem subtypeDomain_apply [∀ i, Zero (β i)] {p : ι → Prop} [DecidablePred p] {i : Subtype p} {v : Π₀ i, β i} : (subtypeDomain p v) i = v i := rfl @[simp] theorem subtypeDomain_add [∀ i, AddZeroClass (β i)] {p : ι → Prop} [DecidablePred p] (v v' : Π₀ i, β i) : (v + v').subtypeDomain p = v.subtypeDomain p + v'.subtypeDomain p := DFunLike.coe_injective rfl @[simp] theorem subtypeDomain_smul [Monoid γ] [∀ i, AddMonoid (β i)] [∀ i, DistribMulAction γ (β i)] {p : ι → Prop} [DecidablePred p] (r : γ) (f : Π₀ i, β i) : (r • f).subtypeDomain p = r • f.subtypeDomain p := DFunLike.coe_injective rfl variable (γ β) /-- `subtypeDomain` but as an `AddMonoidHom`. -/ @[simps] def subtypeDomainAddMonoidHom [∀ i, AddZeroClass (β i)] (p : ι → Prop) [DecidablePred p] : (Π₀ i : ι, β i) →+ Π₀ i : Subtype p, β i where toFun := subtypeDomain p map_zero' := subtypeDomain_zero map_add' := subtypeDomain_add /-- `DFinsupp.subtypeDomain` as a `LinearMap`. -/ @[simps] def subtypeDomainLinearMap [Semiring γ] [∀ i, AddCommMonoid (β i)] [∀ i, Module γ (β i)] (p : ι → Prop) [DecidablePred p] : (Π₀ i, β i) →ₗ[γ] Π₀ i : Subtype p, β i where toFun := subtypeDomain p map_add' := subtypeDomain_add map_smul' := subtypeDomain_smul variable {γ β} @[simp] theorem subtypeDomain_neg [∀ i, AddGroup (β i)] {p : ι → Prop} [DecidablePred p] {v : Π₀ i, β i} : (-v).subtypeDomain p = -v.subtypeDomain p := DFunLike.coe_injective rfl @[simp] theorem subtypeDomain_sub [∀ i, AddGroup (β i)] {p : ι → Prop} [DecidablePred p] {v v' : Π₀ i, β i} : (v - v').subtypeDomain p = v.subtypeDomain p - v'.subtypeDomain p := DFunLike.coe_injective rfl end FilterAndSubtypeDomain variable [DecidableEq ι] section Basic variable [∀ i, Zero (β i)] theorem finite_support (f : Π₀ i, β i) : Set.Finite { i | f i ≠ 0 } := Trunc.induction_on f.support' fun xs ↦ xs.1.finite_toSet.subset fun i H ↦ ((xs.prop i).resolve_right H) /-- Create an element of `Π₀ i, β i` from a finset `s` and a function `x` defined on this `Finset`. -/ def mk (s : Finset ι) (x : ∀ i : (↑s : Set ι), β (i : ι)) : Π₀ i, β i := ⟨fun i => if H : i ∈ s then x ⟨i, H⟩ else 0, Trunc.mk ⟨s.1, fun i => if H : i ∈ s then Or.inl H else Or.inr <| dif_neg H⟩⟩ variable {s : Finset ι} {x : ∀ i : (↑s : Set ι), β i} {i : ι} @[simp] theorem mk_apply : (mk s x : ∀ i, β i) i = if H : i ∈ s then x ⟨i, H⟩ else 0 := rfl theorem mk_of_mem (hi : i ∈ s) : (mk s x : ∀ i, β i) i = x ⟨i, hi⟩ := dif_pos hi theorem mk_of_not_mem (hi : i ∉ s) : (mk s x : ∀ i, β i) i = 0 := dif_neg hi theorem mk_injective (s : Finset ι) : Function.Injective (@mk ι β _ _ s) := by intro x y H ext i have h1 : (mk s x : ∀ i, β i) i = (mk s y : ∀ i, β i) i := by rw [H] obtain ⟨i, hi : i ∈ s⟩ := i dsimp only [mk_apply, Subtype.coe_mk] at h1 simpa only [dif_pos hi] using h1 instance unique [∀ i, Subsingleton (β i)] : Unique (Π₀ i, β i) := DFunLike.coe_injective.unique instance uniqueOfIsEmpty [IsEmpty ι] : Unique (Π₀ i, β i) := DFunLike.coe_injective.unique /-- Given `Fintype ι`, `equivFunOnFintype` is the `Equiv` between `Π₀ i, β i` and `Π i, β i`. (All dependent functions on a finite type are finitely supported.) -/ @[simps apply] def equivFunOnFintype [Fintype ι] : (Π₀ i, β i) ≃ ∀ i, β i where toFun := (⇑) invFun f := ⟨f, Trunc.mk ⟨Finset.univ.1, fun _ => Or.inl <| Finset.mem_univ_val _⟩⟩ left_inv _ := DFunLike.coe_injective rfl right_inv _ := rfl @[simp] theorem equivFunOnFintype_symm_coe [Fintype ι] (f : Π₀ i, β i) : equivFunOnFintype.symm f = f := Equiv.symm_apply_apply _ _ /-- The function `single i b : Π₀ i, β i` sends `i` to `b` and all other points to `0`. -/ def single (i : ι) (b : β i) : Π₀ i, β i := ⟨Pi.single i b, Trunc.mk ⟨{i}, fun j => (Decidable.eq_or_ne j i).imp (by simp) fun h => Pi.single_eq_of_ne h _⟩⟩ theorem single_eq_pi_single {i b} : ⇑(single i b : Π₀ i, β i) = Pi.single i b := rfl @[simp] theorem single_apply {i i' b} : (single i b : Π₀ i, β i) i' = if h : i = i' then Eq.recOn h b else 0 := by rw [single_eq_pi_single, Pi.single, Function.update] simp [@eq_comm _ i i'] @[simp] theorem single_zero (i) : (single i 0 : Π₀ i, β i) = 0 := DFunLike.coe_injective <| Pi.single_zero _ -- @[simp] -- Porting note (#10618): simp can prove this theorem single_eq_same {i b} : (single i b : Π₀ i, β i) i = b := by simp only [single_apply, dite_eq_ite, ite_true] theorem single_eq_of_ne {i i' b} (h : i ≠ i') : (single i b : Π₀ i, β i) i' = 0 := by simp only [single_apply, dif_neg h] theorem single_injective {i} : Function.Injective (single i : β i → Π₀ i, β i) := fun _ _ H => Pi.single_injective β i <| DFunLike.coe_injective.eq_iff.mpr H /-- Like `Finsupp.single_eq_single_iff`, but with a `HEq` due to dependent types -/ theorem single_eq_single_iff (i j : ι) (xi : β i) (xj : β j) : DFinsupp.single i xi = DFinsupp.single j xj ↔ i = j ∧ HEq xi xj ∨ xi = 0 ∧ xj = 0 := by constructor · intro h by_cases hij : i = j · subst hij exact Or.inl ⟨rfl, heq_of_eq (DFinsupp.single_injective h)⟩ · have h_coe : ⇑(DFinsupp.single i xi) = DFinsupp.single j xj := congr_arg (⇑) h have hci := congr_fun h_coe i have hcj := congr_fun h_coe j rw [DFinsupp.single_eq_same] at hci hcj rw [DFinsupp.single_eq_of_ne (Ne.symm hij)] at hci rw [DFinsupp.single_eq_of_ne hij] at hcj exact Or.inr ⟨hci, hcj.symm⟩ · rintro (⟨rfl, hxi⟩ | ⟨hi, hj⟩) · rw [eq_of_heq hxi] · rw [hi, hj, DFinsupp.single_zero, DFinsupp.single_zero] /-- `DFinsupp.single a b` is injective in `a`. For the statement that it is injective in `b`, see `DFinsupp.single_injective` -/ theorem single_left_injective {b : ∀ i : ι, β i} (h : ∀ i, b i ≠ 0) : Function.Injective (fun i => single i (b i) : ι → Π₀ i, β i) := fun _ _ H => (((single_eq_single_iff _ _ _ _).mp H).resolve_right fun hb => h _ hb.1).left @[simp] theorem single_eq_zero {i : ι} {xi : β i} : single i xi = 0 ↔ xi = 0 := by rw [← single_zero i, single_eq_single_iff] simp theorem filter_single (p : ι → Prop) [DecidablePred p] (i : ι) (x : β i) : (single i x).filter p = if p i then single i x else 0 := by ext j have := apply_ite (fun x : Π₀ i, β i => x j) (p i) (single i x) 0 dsimp at this rw [filter_apply, this] obtain rfl | hij := Decidable.eq_or_ne i j · rfl · rw [single_eq_of_ne hij, ite_self, ite_self] @[simp] theorem filter_single_pos {p : ι → Prop} [DecidablePred p] (i : ι) (x : β i) (h : p i) : (single i x).filter p = single i x := by rw [filter_single, if_pos h] @[simp] theorem filter_single_neg {p : ι → Prop} [DecidablePred p] (i : ι) (x : β i) (h : ¬p i) : (single i x).filter p = 0 := by rw [filter_single, if_neg h] /-- Equality of sigma types is sufficient (but not necessary) to show equality of `DFinsupp`s. -/ theorem single_eq_of_sigma_eq {i j} {xi : β i} {xj : β j} (h : (⟨i, xi⟩ : Sigma β) = ⟨j, xj⟩) : DFinsupp.single i xi = DFinsupp.single j xj := by cases h rfl @[simp] theorem equivFunOnFintype_single [Fintype ι] (i : ι) (m : β i) : (@DFinsupp.equivFunOnFintype ι β _ _) (DFinsupp.single i m) = Pi.single i m := by ext x dsimp [Pi.single, Function.update] simp [DFinsupp.single_eq_pi_single, @eq_comm _ i] @[simp] theorem equivFunOnFintype_symm_single [Fintype ι] (i : ι) (m : β i) : (@DFinsupp.equivFunOnFintype ι β _ _).symm (Pi.single i m) = DFinsupp.single i m := by ext i' simp only [← single_eq_pi_single, equivFunOnFintype_symm_coe] section SingleAndZipWith variable [∀ i, Zero (β₁ i)] [∀ i, Zero (β₂ i)] @[simp] theorem zipWith_single_single (f : ∀ i, β₁ i → β₂ i → β i) (hf : ∀ i, f i 0 0 = 0) {i} (b₁ : β₁ i) (b₂ : β₂ i) : zipWith f hf (single i b₁) (single i b₂) = single i (f i b₁ b₂) := by ext j rw [zipWith_apply] obtain rfl | hij := Decidable.eq_or_ne i j · rw [single_eq_same, single_eq_same, single_eq_same] · rw [single_eq_of_ne hij, single_eq_of_ne hij, single_eq_of_ne hij, hf] end SingleAndZipWith /-- Redefine `f i` to be `0`. -/ def erase (i : ι) (x : Π₀ i, β i) : Π₀ i, β i := ⟨fun j ↦ if j = i then 0 else x.1 j, x.support'.map fun xs ↦ ⟨xs.1, fun j ↦ (xs.prop j).imp_right (by simp only [·, ite_self])⟩⟩ @[simp] theorem erase_apply {i j : ι} {f : Π₀ i, β i} : (f.erase i) j = if j = i then 0 else f j := rfl -- @[simp] -- Porting note (#10618): simp can prove this theorem erase_same {i : ι} {f : Π₀ i, β i} : (f.erase i) i = 0 := by simp theorem erase_ne {i i' : ι} {f : Π₀ i, β i} (h : i' ≠ i) : (f.erase i) i' = f i' := by simp [h] theorem piecewise_single_erase (x : Π₀ i, β i) (i : ι) [∀ i' : ι, Decidable <| (i' ∈ ({i} : Set ι))] : -- Porting note: added Decidable hypothesis (single i (x i)).piecewise (x.erase i) {i} = x := by ext j; rw [piecewise_apply]; split_ifs with h · rw [(id h : j = i), single_eq_same] · exact erase_ne h theorem erase_eq_sub_single {β : ι → Type*} [∀ i, AddGroup (β i)] (f : Π₀ i, β i) (i : ι) : f.erase i = f - single i (f i) := by ext j rcases eq_or_ne i j with (rfl | h) · simp · simp [erase_ne h.symm, single_eq_of_ne h, @eq_comm _ j, h] @[simp] theorem erase_zero (i : ι) : erase i (0 : Π₀ i, β i) = 0 := ext fun _ => ite_self _ @[simp] theorem filter_ne_eq_erase (f : Π₀ i, β i) (i : ι) : f.filter (· ≠ i) = f.erase i := by ext1 j simp only [DFinsupp.filter_apply, DFinsupp.erase_apply, ite_not] @[simp] theorem filter_ne_eq_erase' (f : Π₀ i, β i) (i : ι) : f.filter (i ≠ ·) = f.erase i := by rw [← filter_ne_eq_erase f i] congr with j exact ne_comm theorem erase_single (j : ι) (i : ι) (x : β i) : (single i x).erase j = if i = j then 0 else single i x := by rw [← filter_ne_eq_erase, filter_single, ite_not] @[simp] theorem erase_single_same (i : ι) (x : β i) : (single i x).erase i = 0 := by rw [erase_single, if_pos rfl] @[simp] theorem erase_single_ne {i j : ι} (x : β i) (h : i ≠ j) : (single i x).erase j = single i x := by rw [erase_single, if_neg h] section Update variable (f : Π₀ i, β i) (i) (b : β i) /-- Replace the value of a `Π₀ i, β i` at a given point `i : ι` by a given value `b : β i`. If `b = 0`, this amounts to removing `i` from the support. Otherwise, `i` is added to it. This is the (dependent) finitely-supported version of `Function.update`. -/ def update : Π₀ i, β i := ⟨Function.update f i b, f.support'.map fun s => ⟨i ::ₘ s.1, fun j => by rcases eq_or_ne i j with (rfl | hi) · simp · obtain hj | (hj : f j = 0) := s.prop j · exact Or.inl (Multiset.mem_cons_of_mem hj) · exact Or.inr ((Function.update_noteq hi.symm b _).trans hj)⟩⟩ variable (j : ι) @[simp, norm_cast] lemma coe_update : (f.update i b : ∀ i : ι, β i) = Function.update f i b := rfl @[simp] theorem update_self : f.update i (f i) = f := by ext simp @[simp] theorem update_eq_erase : f.update i 0 = f.erase i := by ext j rcases eq_or_ne i j with (rfl | hi) · simp · simp [hi.symm] theorem update_eq_single_add_erase {β : ι → Type*} [∀ i, AddZeroClass (β i)] (f : Π₀ i, β i) (i : ι) (b : β i) : f.update i b = single i b + f.erase i := by ext j rcases eq_or_ne i j with (rfl | h) · simp · simp [Function.update_noteq h.symm, h, erase_ne, h.symm] theorem update_eq_erase_add_single {β : ι → Type*} [∀ i, AddZeroClass (β i)] (f : Π₀ i, β i) (i : ι) (b : β i) : f.update i b = f.erase i + single i b := by ext j rcases eq_or_ne i j with (rfl | h) · simp · simp [Function.update_noteq h.symm, h, erase_ne, h.symm] theorem update_eq_sub_add_single {β : ι → Type*} [∀ i, AddGroup (β i)] (f : Π₀ i, β i) (i : ι) (b : β i) : f.update i b = f - single i (f i) + single i b := by rw [update_eq_erase_add_single f i b, erase_eq_sub_single f i] end Update end Basic section AddMonoid variable [∀ i, AddZeroClass (β i)] @[simp] theorem single_add (i : ι) (b₁ b₂ : β i) : single i (b₁ + b₂) = single i b₁ + single i b₂ := (zipWith_single_single (fun _ => (· + ·)) _ b₁ b₂).symm @[simp] theorem erase_add (i : ι) (f₁ f₂ : Π₀ i, β i) : erase i (f₁ + f₂) = erase i f₁ + erase i f₂ := ext fun _ => by simp [ite_zero_add] variable (β) /-- `DFinsupp.single` as an `AddMonoidHom`. -/ @[simps] def singleAddHom (i : ι) : β i →+ Π₀ i, β i where toFun := single i map_zero' := single_zero i map_add' := single_add i /-- `DFinsupp.erase` as an `AddMonoidHom`. -/ @[simps] def eraseAddHom (i : ι) : (Π₀ i, β i) →+ Π₀ i, β i where toFun := erase i map_zero' := erase_zero i map_add' := erase_add i variable {β} @[simp] theorem single_neg {β : ι → Type v} [∀ i, AddGroup (β i)] (i : ι) (x : β i) : single i (-x) = -single i x := (singleAddHom β i).map_neg x @[simp] theorem single_sub {β : ι → Type v} [∀ i, AddGroup (β i)] (i : ι) (x y : β i) : single i (x - y) = single i x - single i y := (singleAddHom β i).map_sub x y @[simp] theorem erase_neg {β : ι → Type v} [∀ i, AddGroup (β i)] (i : ι) (f : Π₀ i, β i) : (-f).erase i = -f.erase i := (eraseAddHom β i).map_neg f @[simp] theorem erase_sub {β : ι → Type v} [∀ i, AddGroup (β i)] (i : ι) (f g : Π₀ i, β i) : (f - g).erase i = f.erase i - g.erase i := (eraseAddHom β i).map_sub f g theorem single_add_erase (i : ι) (f : Π₀ i, β i) : single i (f i) + f.erase i = f := ext fun i' => if h : i = i' then by subst h; simp only [add_apply, single_apply, erase_apply, add_zero, dite_eq_ite, if_true] else by simp only [add_apply, single_apply, erase_apply, dif_neg h, if_neg (Ne.symm h), zero_add] theorem erase_add_single (i : ι) (f : Π₀ i, β i) : f.erase i + single i (f i) = f := ext fun i' => if h : i = i' then by subst h; simp only [add_apply, single_apply, erase_apply, zero_add, dite_eq_ite, if_true] else by simp only [add_apply, single_apply, erase_apply, dif_neg h, if_neg (Ne.symm h), add_zero] protected theorem induction {p : (Π₀ i, β i) → Prop} (f : Π₀ i, β i) (h0 : p 0) (ha : ∀ (i b) (f : Π₀ i, β i), f i = 0 → b ≠ 0 → p f → p (single i b + f)) : p f := by cases' f with f s induction' s using Trunc.induction_on with s cases' s with s H induction' s using Multiset.induction_on with i s ih generalizing f · have : f = 0 := funext fun i => (H i).resolve_left (Multiset.not_mem_zero _) subst this exact h0 have H2 : p (erase i ⟨f, Trunc.mk ⟨i ::ₘ s, H⟩⟩) := by dsimp only [erase, Trunc.map, Trunc.bind, Trunc.liftOn, Trunc.lift_mk, Function.comp, Subtype.coe_mk] have H2 : ∀ j, j ∈ s ∨ ite (j = i) 0 (f j) = 0 := by intro j cases' H j with H2 H2 · cases' Multiset.mem_cons.1 H2 with H3 H3 · right; exact if_pos H3 · left; exact H3 right split_ifs <;> [rfl; exact H2] have H3 : ∀ aux, (⟨fun j : ι => ite (j = i) 0 (f j), Trunc.mk ⟨i ::ₘ s, aux⟩⟩ : Π₀ i, β i) = ⟨fun j : ι => ite (j = i) 0 (f j), Trunc.mk ⟨s, H2⟩⟩ := fun _ ↦ ext fun _ => rfl rw [H3] apply ih have H3 : single i _ + _ = (⟨f, Trunc.mk ⟨i ::ₘ s, H⟩⟩ : Π₀ i, β i) := single_add_erase _ _ rw [← H3] change p (single i (f i) + _) cases' Classical.em (f i = 0) with h h · rw [h, single_zero, zero_add] exact H2 refine ha _ _ _ ?_ h H2 rw [erase_same] theorem induction₂ {p : (Π₀ i, β i) → Prop} (f : Π₀ i, β i) (h0 : p 0) (ha : ∀ (i b) (f : Π₀ i, β i), f i = 0 → b ≠ 0 → p f → p (f + single i b)) : p f := DFinsupp.induction f h0 fun i b f h1 h2 h3 => have h4 : f + single i b = single i b + f := by ext j; by_cases H : i = j · subst H simp [h1] · simp [H] Eq.recOn h4 <| ha i b f h1 h2 h3 @[simp] theorem add_closure_iUnion_range_single : AddSubmonoid.closure (⋃ i : ι, Set.range (single i : β i → Π₀ i, β i)) = ⊤ := top_unique fun x _ => by apply DFinsupp.induction x · exact AddSubmonoid.zero_mem _ exact fun a b f _ _ hf => AddSubmonoid.add_mem _ (AddSubmonoid.subset_closure <| Set.mem_iUnion.2 ⟨a, Set.mem_range_self _⟩) hf /-- If two additive homomorphisms from `Π₀ i, β i` are equal on each `single a b`, then they are equal. -/ theorem addHom_ext {γ : Type w} [AddZeroClass γ] ⦃f g : (Π₀ i, β i) →+ γ⦄ (H : ∀ (i : ι) (y : β i), f (single i y) = g (single i y)) : f = g := by refine AddMonoidHom.eq_of_eqOn_denseM add_closure_iUnion_range_single fun f hf => ?_ simp only [Set.mem_iUnion, Set.mem_range] at hf rcases hf with ⟨x, y, rfl⟩ apply H /-- If two additive homomorphisms from `Π₀ i, β i` are equal on each `single a b`, then they are equal. See note [partially-applied ext lemmas]. -/ @[ext] theorem addHom_ext' {γ : Type w} [AddZeroClass γ] ⦃f g : (Π₀ i, β i) →+ γ⦄ (H : ∀ x, f.comp (singleAddHom β x) = g.comp (singleAddHom β x)) : f = g := addHom_ext fun x => DFunLike.congr_fun (H x) end AddMonoid @[simp] theorem mk_add [∀ i, AddZeroClass (β i)] {s : Finset ι} {x y : ∀ i : (↑s : Set ι), β i} : mk s (x + y) = mk s x + mk s y := ext fun i => by simp only [add_apply, mk_apply]; split_ifs <;> [rfl; rw [zero_add]] @[simp] theorem mk_zero [∀ i, Zero (β i)] {s : Finset ι} : mk s (0 : ∀ i : (↑s : Set ι), β i.1) = 0 := ext fun i => by simp only [mk_apply]; split_ifs <;> rfl @[simp] theorem mk_neg [∀ i, AddGroup (β i)] {s : Finset ι} {x : ∀ i : (↑s : Set ι), β i.1} : mk s (-x) = -mk s x := ext fun i => by simp only [neg_apply, mk_apply]; split_ifs <;> [rfl; rw [neg_zero]] @[simp] theorem mk_sub [∀ i, AddGroup (β i)] {s : Finset ι} {x y : ∀ i : (↑s : Set ι), β i.1} : mk s (x - y) = mk s x - mk s y := ext fun i => by simp only [sub_apply, mk_apply]; split_ifs <;> [rfl; rw [sub_zero]] /-- If `s` is a subset of `ι` then `mk_addGroupHom s` is the canonical additive group homomorphism from $\prod_{i\in s}\beta_i$ to $\prod_{\mathtt{i : \iota}}\beta_i.$-/ def mkAddGroupHom [∀ i, AddGroup (β i)] (s : Finset ι) : (∀ i : (s : Set ι), β ↑i) →+ Π₀ i : ι, β i where toFun := mk s map_zero' := mk_zero map_add' _ _ := mk_add section variable [Monoid γ] [∀ i, AddMonoid (β i)] [∀ i, DistribMulAction γ (β i)] @[simp] theorem mk_smul {s : Finset ι} (c : γ) (x : ∀ i : (↑s : Set ι), β (i : ι)) : mk s (c • x) = c • mk s x := ext fun i => by simp only [smul_apply, mk_apply]; split_ifs <;> [rfl; rw [smul_zero]] @[simp] theorem single_smul {i : ι} (c : γ) (x : β i) : single i (c • x) = c • single i x := ext fun i => by simp only [smul_apply, single_apply] split_ifs with h · cases h; rfl · rw [smul_zero] end section SupportBasic variable [∀ i, Zero (β i)] [∀ (i) (x : β i), Decidable (x ≠ 0)] /-- Set `{i | f x ≠ 0}` as a `Finset`. -/ def support (f : Π₀ i, β i) : Finset ι := (f.support'.lift fun xs => (Multiset.toFinset xs.1).filter fun i => f i ≠ 0) <| by rintro ⟨sx, hx⟩ ⟨sy, hy⟩ dsimp only [Subtype.coe_mk, toFun_eq_coe] at * ext i; constructor · intro H rcases Finset.mem_filter.1 H with ⟨_, h⟩ exact Finset.mem_filter.2 ⟨Multiset.mem_toFinset.2 <| (hy i).resolve_right h, h⟩ · intro H rcases Finset.mem_filter.1 H with ⟨_, h⟩ exact Finset.mem_filter.2 ⟨Multiset.mem_toFinset.2 <| (hx i).resolve_right h, h⟩ @[simp] theorem support_mk_subset {s : Finset ι} {x : ∀ i : (↑s : Set ι), β i.1} : (mk s x).support ⊆ s := fun _ H => Multiset.mem_toFinset.1 (Finset.mem_filter.1 H).1 @[simp] theorem support_mk'_subset {f : ∀ i, β i} {s : Multiset ι} {h} : (mk' f <| Trunc.mk ⟨s, h⟩).support ⊆ s.toFinset := fun i H => Multiset.mem_toFinset.1 <| by simpa using (Finset.mem_filter.1 H).1 @[simp] theorem mem_support_toFun (f : Π₀ i, β i) (i) : i ∈ f.support ↔ f i ≠ 0 := by cases' f with f s induction' s using Trunc.induction_on with s dsimp only [support, Trunc.lift_mk] rw [Finset.mem_filter, Multiset.mem_toFinset, coe_mk'] exact and_iff_right_of_imp (s.prop i).resolve_right theorem eq_mk_support (f : Π₀ i, β i) : f = mk f.support fun i => f i := by aesop /-- Equivalence between dependent functions with finite support `s : Finset ι` and functions `∀ i, {x : β i // x ≠ 0}`. -/ @[simps] def subtypeSupportEqEquiv (s : Finset ι) : {f : Π₀ i, β i // f.support = s} ≃ ∀ i : s, {x : β i // x ≠ 0} where toFun | ⟨f, hf⟩ => fun ⟨i, hi⟩ ↦ ⟨f i, (f.mem_support_toFun i).1 <| hf.symm ▸ hi⟩ invFun f := ⟨mk s fun i ↦ (f i).1, Finset.ext fun i ↦ by -- TODO: `simp` fails to use `(f _).2` inside `∃ _, _` calc i ∈ support (mk s fun i ↦ (f i).1) ↔ ∃ h : i ∈ s, (f ⟨i, h⟩).1 ≠ 0 := by simp _ ↔ ∃ _ : i ∈ s, True := exists_congr fun h ↦ (iff_true _).mpr (f _).2 _ ↔ i ∈ s := by simp⟩ left_inv := by rintro ⟨f, rfl⟩ ext i simpa using Eq.symm right_inv f := by ext1 simp [Subtype.eta]; rfl /-- Equivalence between all dependent finitely supported functions `f : Π₀ i, β i` and type of pairs `⟨s : Finset ι, f : ∀ i : s, {x : β i // x ≠ 0}⟩`. -/ @[simps! apply_fst apply_snd_coe] def sigmaFinsetFunEquiv : (Π₀ i, β i) ≃ Σ s : Finset ι, ∀ i : s, {x : β i // x ≠ 0} := (Equiv.sigmaFiberEquiv DFinsupp.support).symm.trans (.sigmaCongrRight subtypeSupportEqEquiv) @[simp] theorem support_zero : (0 : Π₀ i, β i).support = ∅ := rfl theorem mem_support_iff {f : Π₀ i, β i} {i : ι} : i ∈ f.support ↔ f i ≠ 0 := f.mem_support_toFun _ theorem not_mem_support_iff {f : Π₀ i, β i} {i : ι} : i ∉ f.support ↔ f i = 0 := not_iff_comm.1 mem_support_iff.symm @[simp] theorem support_eq_empty {f : Π₀ i, β i} : f.support = ∅ ↔ f = 0 := ⟨fun H => ext <| by simpa [Finset.ext_iff] using H, by simp (config := { contextual := true })⟩ instance decidableZero [∀ (i) (x : β i), Decidable (x = 0)] (f : Π₀ i, β i) : Decidable (f = 0) := f.support'.recOnSubsingleton <| fun s => decidable_of_iff (∀ i ∈ s.val, f i = 0) <| by constructor case mpr => rintro rfl _ _; rfl case mp => intro hs₁; ext i -- This instance prevent consuming `DecidableEq ι` in the next `by_cases`. letI := Classical.propDecidable by_cases hs₂ : i ∈ s.val case pos => exact hs₁ _ hs₂ case neg => exact (s.prop i).resolve_left hs₂ theorem support_subset_iff {s : Set ι} {f : Π₀ i, β i} : ↑f.support ⊆ s ↔ ∀ i ∉ s, f i = 0 := by simp [Set.subset_def]; exact forall_congr' fun i => not_imp_comm theorem support_single_ne_zero {i : ι} {b : β i} (hb : b ≠ 0) : (single i b).support = {i} := by ext j; by_cases h : i = j · subst h simp [hb] simp [Ne.symm h, h] theorem support_single_subset {i : ι} {b : β i} : (single i b).support ⊆ {i} := support_mk'_subset section MapRangeAndZipWith variable [∀ i, Zero (β₁ i)] [∀ i, Zero (β₂ i)] theorem mapRange_def [∀ (i) (x : β₁ i), Decidable (x ≠ 0)] {f : ∀ i, β₁ i → β₂ i} {hf : ∀ i, f i 0 = 0} {g : Π₀ i, β₁ i} : mapRange f hf g = mk g.support fun i => f i.1 (g i.1) := by ext i by_cases h : g i ≠ 0 <;> simp at h <;> simp [h, hf] @[simp] theorem mapRange_single {f : ∀ i, β₁ i → β₂ i} {hf : ∀ i, f i 0 = 0} {i : ι} {b : β₁ i} : mapRange f hf (single i b) = single i (f i b) := DFinsupp.ext fun i' => by by_cases h : i = i' · subst i' simp · simp [h, hf] variable [∀ (i) (x : β₁ i), Decidable (x ≠ 0)] [∀ (i) (x : β₂ i), Decidable (x ≠ 0)] theorem support_mapRange {f : ∀ i, β₁ i → β₂ i} {hf : ∀ i, f i 0 = 0} {g : Π₀ i, β₁ i} : (mapRange f hf g).support ⊆ g.support := by simp [mapRange_def] theorem zipWith_def {ι : Type u} {β : ι → Type v} {β₁ : ι → Type v₁} {β₂ : ι → Type v₂} [dec : DecidableEq ι] [∀ i : ι, Zero (β i)] [∀ i : ι, Zero (β₁ i)] [∀ i : ι, Zero (β₂ i)] [∀ (i : ι) (x : β₁ i), Decidable (x ≠ 0)] [∀ (i : ι) (x : β₂ i), Decidable (x ≠ 0)] {f : ∀ i, β₁ i → β₂ i → β i} {hf : ∀ i, f i 0 0 = 0} {g₁ : Π₀ i, β₁ i} {g₂ : Π₀ i, β₂ i} : zipWith f hf g₁ g₂ = mk (g₁.support ∪ g₂.support) fun i => f i.1 (g₁ i.1) (g₂ i.1) := by ext i by_cases h1 : g₁ i ≠ 0 <;> by_cases h2 : g₂ i ≠ 0 <;> simp only [not_not, Ne] at h1 h2 <;> simp [h1, h2, hf] theorem support_zipWith {f : ∀ i, β₁ i → β₂ i → β i} {hf : ∀ i, f i 0 0 = 0} {g₁ : Π₀ i, β₁ i} {g₂ : Π₀ i, β₂ i} : (zipWith f hf g₁ g₂).support ⊆ g₁.support ∪ g₂.support := by simp [zipWith_def] end MapRangeAndZipWith theorem erase_def (i : ι) (f : Π₀ i, β i) : f.erase i = mk (f.support.erase i) fun j => f j.1 := by ext j by_cases h1 : j = i <;> by_cases h2 : f j ≠ 0 <;> simp at h2 <;> simp [h1, h2] @[simp] theorem support_erase (i : ι) (f : Π₀ i, β i) : (f.erase i).support = f.support.erase i := by ext j by_cases h1 : j = i · simp only [h1, mem_support_toFun, erase_apply, ite_true, ne_eq, not_true, not_not, Finset.mem_erase, false_and] by_cases h2 : f j ≠ 0 <;> simp at h2 <;> simp [h1, h2] theorem support_update_ne_zero (f : Π₀ i, β i) (i : ι) {b : β i} (h : b ≠ 0) : support (f.update i b) = insert i f.support := by ext j rcases eq_or_ne i j with (rfl | hi) · simp [h] · simp [hi.symm] theorem support_update (f : Π₀ i, β i) (i : ι) (b : β i) [Decidable (b = 0)] : support (f.update i b) = if b = 0 then support (f.erase i) else insert i f.support := by ext j split_ifs with hb · subst hb simp [update_eq_erase, support_erase] · rw [support_update_ne_zero f _ hb] section FilterAndSubtypeDomain variable {p : ι → Prop} [DecidablePred p] theorem filter_def (f : Π₀ i, β i) : f.filter p = mk (f.support.filter p) fun i => f i.1 := by ext i; by_cases h1 : p i <;> by_cases h2 : f i ≠ 0 <;> simp at h2 <;> simp [h1, h2] @[simp] theorem support_filter (f : Π₀ i, β i) : (f.filter p).support = f.support.filter p := by ext i; by_cases h : p i <;> simp [h] theorem subtypeDomain_def (f : Π₀ i, β i) : f.subtypeDomain p = mk (f.support.subtype p) fun i => f i := by ext i; by_cases h2 : f i ≠ 0 <;> try simp at h2; dsimp; simp [h2] @[simp, nolint simpNF] -- Porting note: simpNF claims that LHS does not simplify, but it does theorem support_subtypeDomain {f : Π₀ i, β i} : (subtypeDomain p f).support = f.support.subtype p := by ext i simp end FilterAndSubtypeDomain end SupportBasic theorem support_add [∀ i, AddZeroClass (β i)] [∀ (i) (x : β i), Decidable (x ≠ 0)] {g₁ g₂ : Π₀ i, β i} : (g₁ + g₂).support ⊆ g₁.support ∪ g₂.support := support_zipWith @[simp] theorem support_neg [∀ i, AddGroup (β i)] [∀ (i) (x : β i), Decidable (x ≠ 0)] {f : Π₀ i, β i} : support (-f) = support f := by ext i; simp theorem support_smul {γ : Type w} [Semiring γ] [∀ i, AddCommMonoid (β i)] [∀ i, Module γ (β i)] [∀ (i : ι) (x : β i), Decidable (x ≠ 0)] (b : γ) (v : Π₀ i, β i) : (b • v).support ⊆ v.support := support_mapRange instance [∀ i, Zero (β i)] [∀ i, DecidableEq (β i)] : DecidableEq (Π₀ i, β i) := fun f g => decidable_of_iff (f.support = g.support ∧ ∀ i ∈ f.support, f i = g i) ⟨fun ⟨h₁, h₂⟩ => ext fun i => if h : i ∈ f.support then h₂ i h else by have hf : f i = 0 := by rwa [mem_support_iff, not_not] at h have hg : g i = 0 := by rwa [h₁, mem_support_iff, not_not] at h rw [hf, hg], by rintro rfl; simp⟩ section Equiv open Finset variable {κ : Type*} /-- Reindexing (and possibly removing) terms of a dfinsupp. -/ noncomputable def comapDomain [∀ i, Zero (β i)] (h : κ → ι) (hh : Function.Injective h) (f : Π₀ i, β i) : Π₀ k, β (h k) where toFun x := f (h x) support' := f.support'.map fun s => ⟨(s.1.finite_toSet.preimage hh.injOn).toFinset.val, fun x => (s.prop (h x)).imp_left fun hx => (Set.Finite.mem_toFinset _).mpr <| hx⟩ @[simp] theorem comapDomain_apply [∀ i, Zero (β i)] (h : κ → ι) (hh : Function.Injective h) (f : Π₀ i, β i) (k : κ) : comapDomain h hh f k = f (h k) := rfl @[simp] theorem comapDomain_zero [∀ i, Zero (β i)] (h : κ → ι) (hh : Function.Injective h) : comapDomain h hh (0 : Π₀ i, β i) = 0 := by ext rw [zero_apply, comapDomain_apply, zero_apply] @[simp] theorem comapDomain_add [∀ i, AddZeroClass (β i)] (h : κ → ι) (hh : Function.Injective h) (f g : Π₀ i, β i) : comapDomain h hh (f + g) = comapDomain h hh f + comapDomain h hh g := by ext rw [add_apply, comapDomain_apply, comapDomain_apply, comapDomain_apply, add_apply] @[simp] theorem comapDomain_smul [Monoid γ] [∀ i, AddMonoid (β i)] [∀ i, DistribMulAction γ (β i)] (h : κ → ι) (hh : Function.Injective h) (r : γ) (f : Π₀ i, β i) : comapDomain h hh (r • f) = r • comapDomain h hh f := by ext rw [smul_apply, comapDomain_apply, smul_apply, comapDomain_apply] @[simp] theorem comapDomain_single [DecidableEq κ] [∀ i, Zero (β i)] (h : κ → ι) (hh : Function.Injective h) (k : κ) (x : β (h k)) : comapDomain h hh (single (h k) x) = single k x := by ext i rw [comapDomain_apply] obtain rfl | hik := Decidable.eq_or_ne i k · rw [single_eq_same, single_eq_same] · rw [single_eq_of_ne hik.symm, single_eq_of_ne (hh.ne hik.symm)] /-- A computable version of comap_domain when an explicit left inverse is provided. -/ def comapDomain' [∀ i, Zero (β i)] (h : κ → ι) {h' : ι → κ} (hh' : Function.LeftInverse h' h) (f : Π₀ i, β i) : Π₀ k, β (h k) where toFun x := f (h x) support' := f.support'.map fun s => ⟨Multiset.map h' s.1, fun x => (s.prop (h x)).imp_left fun hx => Multiset.mem_map.mpr ⟨_, hx, hh' _⟩⟩ @[simp] theorem comapDomain'_apply [∀ i, Zero (β i)] (h : κ → ι) {h' : ι → κ} (hh' : Function.LeftInverse h' h) (f : Π₀ i, β i) (k : κ) : comapDomain' h hh' f k = f (h k) := rfl @[simp] theorem comapDomain'_zero [∀ i, Zero (β i)] (h : κ → ι) {h' : ι → κ} (hh' : Function.LeftInverse h' h) : comapDomain' h hh' (0 : Π₀ i, β i) = 0 := by ext rw [zero_apply, comapDomain'_apply, zero_apply] @[simp] theorem comapDomain'_add [∀ i, AddZeroClass (β i)] (h : κ → ι) {h' : ι → κ} (hh' : Function.LeftInverse h' h) (f g : Π₀ i, β i) : comapDomain' h hh' (f + g) = comapDomain' h hh' f + comapDomain' h hh' g := by ext rw [add_apply, comapDomain'_apply, comapDomain'_apply, comapDomain'_apply, add_apply] @[simp] theorem comapDomain'_smul [Monoid γ] [∀ i, AddMonoid (β i)] [∀ i, DistribMulAction γ (β i)] (h : κ → ι) {h' : ι → κ} (hh' : Function.LeftInverse h' h) (r : γ) (f : Π₀ i, β i) : comapDomain' h hh' (r • f) = r • comapDomain' h hh' f := by ext rw [smul_apply, comapDomain'_apply, smul_apply, comapDomain'_apply] @[simp] theorem comapDomain'_single [DecidableEq ι] [DecidableEq κ] [∀ i, Zero (β i)] (h : κ → ι) {h' : ι → κ} (hh' : Function.LeftInverse h' h) (k : κ) (x : β (h k)) : comapDomain' h hh' (single (h k) x) = single k x := by ext i rw [comapDomain'_apply] obtain rfl | hik := Decidable.eq_or_ne i k · rw [single_eq_same, single_eq_same] · rw [single_eq_of_ne hik.symm, single_eq_of_ne (hh'.injective.ne hik.symm)] /-- Reindexing terms of a dfinsupp. This is the dfinsupp version of `Equiv.piCongrLeft'`. -/ @[simps apply] def equivCongrLeft [∀ i, Zero (β i)] (h : ι ≃ κ) : (Π₀ i, β i) ≃ Π₀ k, β (h.symm k) where toFun := comapDomain' h.symm h.right_inv invFun f := mapRange (fun i => Equiv.cast <| congr_arg β <| h.symm_apply_apply i) (fun i => (Equiv.cast_eq_iff_heq _).mpr <| by rw [Equiv.symm_apply_apply]) (@comapDomain' _ _ _ _ h _ h.left_inv f) left_inv f := by ext i rw [mapRange_apply, comapDomain'_apply, comapDomain'_apply, Equiv.cast_eq_iff_heq, h.symm_apply_apply] right_inv f := by ext k rw [comapDomain'_apply, mapRange_apply, comapDomain'_apply, Equiv.cast_eq_iff_heq, h.apply_symm_apply] section SigmaCurry variable {α : ι → Type*} {δ : ∀ i, α i → Type v} -- lean can't find these instances -- Porting note: but Lean 4 can!!! instance hasAdd₂ [∀ i j, AddZeroClass (δ i j)] : Add (Π₀ (i : ι) (j : α i), δ i j) := inferInstance -- @DFinsupp.hasAdd ι (fun i => Π₀ j, δ i j) _ instance addZeroClass₂ [∀ i j, AddZeroClass (δ i j)] : AddZeroClass (Π₀ (i : ι) (j : α i), δ i j) := inferInstance -- @DFinsupp.addZeroClass ι (fun i => Π₀ j, δ i j) _ instance addMonoid₂ [∀ i j, AddMonoid (δ i j)] : AddMonoid (Π₀ (i : ι) (j : α i), δ i j) := inferInstance -- @DFinsupp.addMonoid ι (fun i => Π₀ j, δ i j) _ instance distribMulAction₂ [Monoid γ] [∀ i j, AddMonoid (δ i j)] [∀ i j, DistribMulAction γ (δ i j)] : DistribMulAction γ (Π₀ (i : ι) (j : α i), δ i j) := @DFinsupp.distribMulAction ι _ (fun i => Π₀ j, δ i j) _ _ _ /-- The natural map between `Π₀ (i : Σ i, α i), δ i.1 i.2` and `Π₀ i (j : α i), δ i j`. -/ def sigmaCurry [∀ i j, Zero (δ i j)] (f : Π₀ (i : Σ _, _), δ i.1 i.2) : Π₀ (i) (j), δ i j where toFun := fun i ↦ { toFun := fun j ↦ f ⟨i, j⟩, support' := f.support'.map (fun ⟨m, hm⟩ ↦ ⟨m.filterMap (fun ⟨i', j'⟩ ↦ if h : i' = i then some <| h.rec j' else none), fun j ↦ (hm ⟨i, j⟩).imp_left (fun h ↦ (m.mem_filterMap _).mpr ⟨⟨i, j⟩, h, dif_pos rfl⟩)⟩) } support' := f.support'.map (fun ⟨m, hm⟩ ↦ ⟨m.map Sigma.fst, fun i ↦ Decidable.or_iff_not_imp_left.mpr (fun h ↦ DFinsupp.ext (fun j ↦ (hm ⟨i, j⟩).resolve_left (fun H ↦ (Multiset.mem_map.not.mp h) ⟨⟨i, j⟩, H, rfl⟩)))⟩) @[simp] theorem sigmaCurry_apply [∀ i j, Zero (δ i j)] (f : Π₀ (i : Σ _, _), δ i.1 i.2) (i : ι) (j : α i) : sigmaCurry f i j = f ⟨i, j⟩ := rfl @[simp] theorem sigmaCurry_zero [∀ i j, Zero (δ i j)] : sigmaCurry (0 : Π₀ (i : Σ _, _), δ i.1 i.2) = 0 := rfl @[simp] theorem sigmaCurry_add [∀ i j, AddZeroClass (δ i j)] (f g : Π₀ (i : Σ _, _), δ i.1 i.2) : sigmaCurry (f + g) = sigmaCurry f + sigmaCurry g := by ext (i j) rfl @[simp] theorem sigmaCurry_smul [Monoid γ] [∀ i j, AddMonoid (δ i j)] [∀ i j, DistribMulAction γ (δ i j)] (r : γ) (f : Π₀ (i : Σ _, _), δ i.1 i.2) : sigmaCurry (r • f) = r • sigmaCurry f := by ext (i j) rfl @[simp] theorem sigmaCurry_single [∀ i, DecidableEq (α i)] [∀ i j, Zero (δ i j)] (ij : Σ i, α i) (x : δ ij.1 ij.2) : sigmaCurry (single ij x) = single ij.1 (single ij.2 x : Π₀ j, δ ij.1 j) := by obtain ⟨i, j⟩ := ij ext i' j' dsimp only rw [sigmaCurry_apply] obtain rfl | hi := eq_or_ne i i' · rw [single_eq_same] obtain rfl | hj := eq_or_ne j j' · rw [single_eq_same, single_eq_same] · rw [single_eq_of_ne, single_eq_of_ne hj] simpa using hj · rw [single_eq_of_ne, single_eq_of_ne hi, zero_apply] simp [hi] /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ /-- The natural map between `Π₀ i (j : α i), δ i j` and `Π₀ (i : Σ i, α i), δ i.1 i.2`, inverse of `curry`. -/ def sigmaUncurry [∀ i j, Zero (δ i j)] [DecidableEq ι] (f : Π₀ (i) (j), δ i j) : Π₀ i : Σi, _, δ i.1 i.2 where toFun i := f i.1 i.2 support' := f.support'.bind fun s => (Trunc.finChoice (fun i : ↥s.val.toFinset => (f i).support')).map fun fs => ⟨s.val.toFinset.attach.val.bind fun i => (fs i).val.map (Sigma.mk i.val), by rintro ⟨i, a⟩ cases s.prop i with | inl hi => cases (fs ⟨i, Multiset.mem_toFinset.mpr hi⟩).prop a with | inl ha => left; rw [Multiset.mem_bind] use ⟨i, Multiset.mem_toFinset.mpr hi⟩ constructor case right => simp [ha] case left => apply Multiset.mem_attach | inr ha => right; simp [toFun_eq_coe (f i) ▸ ha] | inr hi => right; simp [toFun_eq_coe f ▸ hi]⟩ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ @[simp] theorem sigmaUncurry_apply [∀ i j, Zero (δ i j)] [DecidableEq ι] (f : Π₀ (i) (j), δ i j) (i : ι) (j : α i) : sigmaUncurry f ⟨i, j⟩ = f i j := rfl /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ @[simp] theorem sigmaUncurry_zero [∀ i j, Zero (δ i j)] [DecidableEq ι] : sigmaUncurry (0 : Π₀ (i) (j), δ i j) = 0 := rfl /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ @[simp] theorem sigmaUncurry_add [∀ i j, AddZeroClass (δ i j)] [DecidableEq ι] (f g : Π₀ (i) (j), δ i j) : sigmaUncurry (f + g) = sigmaUncurry f + sigmaUncurry g := DFunLike.coe_injective rfl /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ @[simp] theorem sigmaUncurry_smul [Monoid γ] [∀ i j, AddMonoid (δ i j)] [DecidableEq ι] [∀ i j, DistribMulAction γ (δ i j)] (r : γ) (f : Π₀ (i) (j), δ i j) : sigmaUncurry (r • f) = r • sigmaUncurry f := DFunLike.coe_injective rfl @[simp] theorem sigmaUncurry_single [∀ i j, Zero (δ i j)] [DecidableEq ι] [∀ i, DecidableEq (α i)] (i) (j : α i) (x : δ i j) : sigmaUncurry (single i (single j x : Π₀ j : α i, δ i j)) = single ⟨i, j⟩ (by exact x) := by ext ⟨i', j'⟩ dsimp only rw [sigmaUncurry_apply] obtain rfl | hi := eq_or_ne i i' · rw [single_eq_same] obtain rfl | hj := eq_or_ne j j' · rw [single_eq_same, single_eq_same] · rw [single_eq_of_ne hj, single_eq_of_ne] simpa using hj · rw [single_eq_of_ne hi, single_eq_of_ne, zero_apply] simp [hi] /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ /-- The natural bijection between `Π₀ (i : Σ i, α i), δ i.1 i.2` and `Π₀ i (j : α i), δ i j`. This is the dfinsupp version of `Equiv.piCurry`. -/ def sigmaCurryEquiv [∀ i j, Zero (δ i j)] [DecidableEq ι] : (Π₀ i : Σi, _, δ i.1 i.2) ≃ Π₀ (i) (j), δ i j where toFun := sigmaCurry invFun := sigmaUncurry left_inv f := by ext ⟨i, j⟩ rw [sigmaUncurry_apply, sigmaCurry_apply] right_inv f := by ext i j rw [sigmaCurry_apply, sigmaUncurry_apply] end SigmaCurry variable {α : Option ι → Type v} /-- Adds a term to a dfinsupp, making a dfinsupp indexed by an `Option`. This is the dfinsupp version of `Option.rec`. -/ def extendWith [∀ i, Zero (α i)] (a : α none) (f : Π₀ i, α (some i)) : Π₀ i, α i where toFun := fun i ↦ match i with | none => a | some _ => f _ support' := f.support'.map fun s => ⟨none ::ₘ Multiset.map some s.1, fun i => Option.rec (Or.inl <| Multiset.mem_cons_self _ _) (fun i => (s.prop i).imp_left fun h => Multiset.mem_cons_of_mem <| Multiset.mem_map_of_mem _ h) i⟩ @[simp] theorem extendWith_none [∀ i, Zero (α i)] (f : Π₀ i, α (some i)) (a : α none) : f.extendWith a none = a := rfl @[simp] theorem extendWith_some [∀ i, Zero (α i)] (f : Π₀ i, α (some i)) (a : α none) (i : ι) : f.extendWith a (some i) = f i := rfl @[simp] theorem extendWith_single_zero [DecidableEq ι] [∀ i, Zero (α i)] (i : ι) (x : α (some i)) : (single i x).extendWith 0 = single (some i) x := by ext (_ | j) · rw [extendWith_none, single_eq_of_ne (Option.some_ne_none _)] · rw [extendWith_some] obtain rfl | hij := Decidable.eq_or_ne i j · rw [single_eq_same, single_eq_same] · rw [single_eq_of_ne hij, single_eq_of_ne ((Option.some_injective _).ne hij)] @[simp] theorem extendWith_zero [DecidableEq ι] [∀ i, Zero (α i)] (x : α none) : (0 : Π₀ i, α (some i)).extendWith x = single none x := by ext (_ | j) · rw [extendWith_none, single_eq_same] · rw [extendWith_some, single_eq_of_ne (Option.some_ne_none _).symm, zero_apply] /-- Bijection obtained by separating the term of index `none` of a dfinsupp over `Option ι`. This is the dfinsupp version of `Equiv.piOptionEquivProd`. -/ @[simps] noncomputable def equivProdDFinsupp [∀ i, Zero (α i)] : (Π₀ i, α i) ≃ α none × Π₀ i, α (some i) where toFun f := (f none, comapDomain some (Option.some_injective _) f) invFun f := f.2.extendWith f.1 left_inv f := by ext i; cases' i with i · rw [extendWith_none] · rw [extendWith_some, comapDomain_apply] right_inv x := by dsimp only ext · exact extendWith_none x.snd _ · rw [comapDomain_apply, extendWith_some] theorem equivProdDFinsupp_add [∀ i, AddZeroClass (α i)] (f g : Π₀ i, α i) : equivProdDFinsupp (f + g) = equivProdDFinsupp f + equivProdDFinsupp g := Prod.ext (add_apply _ _ _) (comapDomain_add _ (Option.some_injective _) _ _) theorem equivProdDFinsupp_smul [Monoid γ] [∀ i, AddMonoid (α i)] [∀ i, DistribMulAction γ (α i)] (r : γ) (f : Π₀ i, α i) : equivProdDFinsupp (r • f) = r • equivProdDFinsupp f := Prod.ext (smul_apply _ _ _) (comapDomain_smul _ (Option.some_injective _) _ _) end Equiv section ProdAndSum /-- `DFinsupp.prod f g` is the product of `g i (f i)` over the support of `f`. -/ @[to_additive "`sum f g` is the sum of `g i (f i)` over the support of `f`."] def prod [∀ i, Zero (β i)] [∀ (i) (x : β i), Decidable (x ≠ 0)] [CommMonoid γ] (f : Π₀ i, β i) (g : ∀ i, β i → γ) : γ := ∏ i ∈ f.support, g i (f i) @[to_additive (attr := simp)] theorem _root_.map_dfinsupp_prod {R S H : Type*} [∀ i, Zero (β i)] [∀ (i) (x : β i), Decidable (x ≠ 0)] [CommMonoid R] [CommMonoid S] [FunLike H R S] [MonoidHomClass H R S] (h : H) (f : Π₀ i, β i) (g : ∀ i, β i → R) : h (f.prod g) = f.prod fun a b => h (g a b) := map_prod _ _ _ @[to_additive] theorem prod_mapRange_index {β₁ : ι → Type v₁} {β₂ : ι → Type v₂} [∀ i, Zero (β₁ i)] [∀ i, Zero (β₂ i)] [∀ (i) (x : β₁ i), Decidable (x ≠ 0)] [∀ (i) (x : β₂ i), Decidable (x ≠ 0)] [CommMonoid γ] {f : ∀ i, β₁ i → β₂ i} {hf : ∀ i, f i 0 = 0} {g : Π₀ i, β₁ i} {h : ∀ i, β₂ i → γ} (h0 : ∀ i, h i 0 = 1) : (mapRange f hf g).prod h = g.prod fun i b => h i (f i b) := by rw [mapRange_def] refine (Finset.prod_subset support_mk_subset ?_).trans ?_ · intro i h1 h2 simp only [mem_support_toFun, ne_eq] at h1 simp only [Finset.coe_sort_coe, mem_support_toFun, mk_apply, ne_eq, h1, not_false_iff, dite_eq_ite, ite_true, not_not] at h2 simp [h2, h0] · refine Finset.prod_congr rfl ?_ intro i h1 simp only [mem_support_toFun, ne_eq] at h1 simp [h1] @[to_additive] theorem prod_zero_index [∀ i, AddCommMonoid (β i)] [∀ (i) (x : β i), Decidable (x ≠ 0)] [CommMonoid γ] {h : ∀ i, β i → γ} : (0 : Π₀ i, β i).prod h = 1 := rfl @[to_additive] theorem prod_single_index [∀ i, Zero (β i)] [∀ (i) (x : β i), Decidable (x ≠ 0)] [CommMonoid γ] {i : ι} {b : β i} {h : ∀ i, β i → γ} (h_zero : h i 0 = 1) : (single i b).prod h = h i b := by by_cases h : b ≠ 0 · simp [DFinsupp.prod, support_single_ne_zero h] · rw [not_not] at h simp [h, prod_zero_index, h_zero] rfl @[to_additive] theorem prod_neg_index [∀ i, AddGroup (β i)] [∀ (i) (x : β i), Decidable (x ≠ 0)] [CommMonoid γ] {g : Π₀ i, β i} {h : ∀ i, β i → γ} (h0 : ∀ i, h i 0 = 1) : (-g).prod h = g.prod fun i b => h i (-b) := prod_mapRange_index h0 @[to_additive] theorem prod_comm {ι₁ ι₂ : Sort _} {β₁ : ι₁ → Type*} {β₂ : ι₂ → Type*} [DecidableEq ι₁] [DecidableEq ι₂] [∀ i, Zero (β₁ i)] [∀ i, Zero (β₂ i)] [∀ (i) (x : β₁ i), Decidable (x ≠ 0)] [∀ (i) (x : β₂ i), Decidable (x ≠ 0)] [CommMonoid γ] (f₁ : Π₀ i, β₁ i) (f₂ : Π₀ i, β₂ i) (h : ∀ i, β₁ i → ∀ i, β₂ i → γ) : (f₁.prod fun i₁ x₁ => f₂.prod fun i₂ x₂ => h i₁ x₁ i₂ x₂) = f₂.prod fun i₂ x₂ => f₁.prod fun i₁ x₁ => h i₁ x₁ i₂ x₂ := Finset.prod_comm @[simp] theorem sum_apply {ι₁ : Type u₁} [DecidableEq ι₁] {β₁ : ι₁ → Type v₁} [∀ i₁, Zero (β₁ i₁)] [∀ (i) (x : β₁ i), Decidable (x ≠ 0)] [∀ i, AddCommMonoid (β i)] {f : Π₀ i₁, β₁ i₁} {g : ∀ i₁, β₁ i₁ → Π₀ i, β i} {i₂ : ι} : (f.sum g) i₂ = f.sum fun i₁ b => g i₁ b i₂ := map_sum (evalAddMonoidHom i₂) _ f.support theorem support_sum {ι₁ : Type u₁} [DecidableEq ι₁] {β₁ : ι₁ → Type v₁} [∀ i₁, Zero (β₁ i₁)] [∀ (i) (x : β₁ i), Decidable (x ≠ 0)] [∀ i, AddCommMonoid (β i)] [∀ (i) (x : β i), Decidable (x ≠ 0)] {f : Π₀ i₁, β₁ i₁} {g : ∀ i₁, β₁ i₁ → Π₀ i, β i} : (f.sum g).support ⊆ f.support.biUnion fun i => (g i (f i)).support := by have : ∀ i₁ : ι, (f.sum fun (i : ι₁) (b : β₁ i) => (g i b) i₁) ≠ 0 → ∃ i : ι₁, f i ≠ 0 ∧ ¬(g i (f i)) i₁ = 0 := fun i₁ h => let ⟨i, hi, Ne⟩ := Finset.exists_ne_zero_of_sum_ne_zero h ⟨i, mem_support_iff.1 hi, Ne⟩ simpa [Finset.subset_iff, mem_support_iff, Finset.mem_biUnion, sum_apply] using this @[to_additive (attr := simp)] theorem prod_one [∀ i, AddCommMonoid (β i)] [∀ (i) (x : β i), Decidable (x ≠ 0)] [CommMonoid γ] {f : Π₀ i, β i} : (f.prod fun _ _ => (1 : γ)) = 1 := Finset.prod_const_one @[to_additive (attr := simp)] theorem prod_mul [∀ i, AddCommMonoid (β i)] [∀ (i) (x : β i), Decidable (x ≠ 0)] [CommMonoid γ] {f : Π₀ i, β i} {h₁ h₂ : ∀ i, β i → γ} : (f.prod fun i b => h₁ i b * h₂ i b) = f.prod h₁ * f.prod h₂ := Finset.prod_mul_distrib @[to_additive (attr := simp)] theorem prod_inv [∀ i, AddCommMonoid (β i)] [∀ (i) (x : β i), Decidable (x ≠ 0)] [CommGroup γ] {f : Π₀ i, β i} {h : ∀ i, β i → γ} : (f.prod fun i b => (h i b)⁻¹) = (f.prod h)⁻¹ := (map_prod (invMonoidHom : γ →* γ) _ f.support).symm @[to_additive] theorem prod_eq_one [∀ i, Zero (β i)] [∀ (i) (x : β i), Decidable (x ≠ 0)] [CommMonoid γ] {f : Π₀ i, β i} {h : ∀ i, β i → γ} (hyp : ∀ i, h i (f i) = 1) : f.prod h = 1 := Finset.prod_eq_one fun i _ => hyp i theorem smul_sum {α : Type*} [Monoid α] [∀ i, Zero (β i)] [∀ (i) (x : β i), Decidable (x ≠ 0)] [AddCommMonoid γ] [DistribMulAction α γ] {f : Π₀ i, β i} {h : ∀ i, β i → γ} {c : α} : c • f.sum h = f.sum fun a b => c • h a b := Finset.smul_sum @[to_additive] theorem prod_add_index [∀ i, AddCommMonoid (β i)] [∀ (i) (x : β i), Decidable (x ≠ 0)] [CommMonoid γ] {f g : Π₀ i, β i} {h : ∀ i, β i → γ} (h_zero : ∀ i, h i 0 = 1) (h_add : ∀ i b₁ b₂, h i (b₁ + b₂) = h i b₁ * h i b₂) : (f + g).prod h = f.prod h * g.prod h := have f_eq : (∏ i ∈ f.support ∪ g.support, h i (f i)) = f.prod h := (Finset.prod_subset Finset.subset_union_left <| by simp (config := { contextual := true }) [mem_support_iff, h_zero]).symm have g_eq : (∏ i ∈ f.support ∪ g.support, h i (g i)) = g.prod h := (Finset.prod_subset Finset.subset_union_right <| by simp (config := { contextual := true }) [mem_support_iff, h_zero]).symm calc (∏ i ∈ (f + g).support, h i ((f + g) i)) = ∏ i ∈ f.support ∪ g.support, h i ((f + g) i) := Finset.prod_subset support_add <| by simp (config := { contextual := true }) [mem_support_iff, h_zero] _ = (∏ i ∈ f.support ∪ g.support, h i (f i)) * ∏ i ∈ f.support ∪ g.support, h i (g i) := by { simp [h_add, Finset.prod_mul_distrib] } _ = _ := by rw [f_eq, g_eq] @[to_additive] theorem _root_.dfinsupp_prod_mem [∀ i, Zero (β i)] [∀ (i) (x : β i), Decidable (x ≠ 0)] [CommMonoid γ] {S : Type*} [SetLike S γ] [SubmonoidClass S γ] (s : S) (f : Π₀ i, β i) (g : ∀ i, β i → γ) (h : ∀ c, f c ≠ 0 → g c (f c) ∈ s) : f.prod g ∈ s := prod_mem fun _ hi => h _ <| mem_support_iff.1 hi @[to_additive (attr := simp)] theorem prod_eq_prod_fintype [Fintype ι] [∀ i, Zero (β i)] [∀ (i : ι) (x : β i), Decidable (x ≠ 0)] -- Porting note: `f` was a typeclass argument [CommMonoid γ] (v : Π₀ i, β i) {f : ∀ i, β i → γ} (hf : ∀ i, f i 0 = 1) : v.prod f = ∏ i, f i (DFinsupp.equivFunOnFintype v i) := by suffices (∏ i ∈ v.support, f i (v i)) = ∏ i, f i (v i) by simp [DFinsupp.prod, this] apply Finset.prod_subset v.support.subset_univ intro i _ hi rw [mem_support_iff, not_not] at hi rw [hi, hf] section CommMonoidWithZero variable [Π i, Zero (β i)] [CommMonoidWithZero γ] [Nontrivial γ] [NoZeroDivisors γ] [Π i, DecidableEq (β i)] {f : Π₀ i, β i} {g : Π i, β i → γ} @[simp] lemma prod_eq_zero_iff : f.prod g = 0 ↔ ∃ i ∈ f.support, g i (f i) = 0 := Finset.prod_eq_zero_iff lemma prod_ne_zero_iff : f.prod g ≠ 0 ↔ ∀ i ∈ f.support, g i (f i) ≠ 0 := Finset.prod_ne_zero_iff end CommMonoidWithZero /-- When summing over an `AddMonoidHom`, the decidability assumption is not needed, and the result is also an `AddMonoidHom`. -/ def sumAddHom [∀ i, AddZeroClass (β i)] [AddCommMonoid γ] (φ : ∀ i, β i →+ γ) : (Π₀ i, β i) →+ γ where toFun f := (f.support'.lift fun s => ∑ i ∈ Multiset.toFinset s.1, φ i (f i)) <| by rintro ⟨sx, hx⟩ ⟨sy, hy⟩ dsimp only [Subtype.coe_mk, toFun_eq_coe] at * have H1 : sx.toFinset ∩ sy.toFinset ⊆ sx.toFinset := Finset.inter_subset_left have H2 : sx.toFinset ∩ sy.toFinset ⊆ sy.toFinset := Finset.inter_subset_right refine (Finset.sum_subset H1 ?_).symm.trans ((Finset.sum_congr rfl ?_).trans (Finset.sum_subset H2 ?_)) · intro i H1 H2 rw [Finset.mem_inter] at H2 simp only [Multiset.mem_toFinset] at H1 H2 convert AddMonoidHom.map_zero (φ i) exact (hy i).resolve_left (mt (And.intro H1) H2) · intro i _ rfl · intro i H1 H2 rw [Finset.mem_inter] at H2 simp only [Multiset.mem_toFinset] at H1 H2 convert AddMonoidHom.map_zero (φ i) exact (hx i).resolve_left (mt (fun H3 => And.intro H3 H1) H2) map_add' := by rintro ⟨f, sf, hf⟩ ⟨g, sg, hg⟩ change (∑ i ∈ _, _) = (∑ i ∈ _, _) + ∑ i ∈ _, _ simp only [coe_add, coe_mk', Subtype.coe_mk, Pi.add_apply, map_add, Finset.sum_add_distrib] congr 1 · refine (Finset.sum_subset ?_ ?_).symm · intro i simp only [Multiset.mem_toFinset, Multiset.mem_add] exact Or.inl · intro i _ H2 simp only [Multiset.mem_toFinset, Multiset.mem_add] at H2 rw [(hf i).resolve_left H2, AddMonoidHom.map_zero] · refine (Finset.sum_subset ?_ ?_).symm · intro i simp only [Multiset.mem_toFinset, Multiset.mem_add] exact Or.inr · intro i _ H2 simp only [Multiset.mem_toFinset, Multiset.mem_add] at H2 rw [(hg i).resolve_left H2, AddMonoidHom.map_zero] map_zero' := by simp only [toFun_eq_coe, coe_zero, Pi.zero_apply, map_zero, Finset.sum_const_zero]; rfl @[simp] theorem sumAddHom_single [∀ i, AddZeroClass (β i)] [AddCommMonoid γ] (φ : ∀ i, β i →+ γ) (i) (x : β i) : sumAddHom φ (single i x) = φ i x := by dsimp [sumAddHom, single, Trunc.lift_mk] rw [Multiset.toFinset_singleton, Finset.sum_singleton, Pi.single_eq_same] @[simp] theorem sumAddHom_comp_single [∀ i, AddZeroClass (β i)] [AddCommMonoid γ] (f : ∀ i, β i →+ γ) (i : ι) : (sumAddHom f).comp (singleAddHom β i) = f i := AddMonoidHom.ext fun x => sumAddHom_single f i x /-- While we didn't need decidable instances to define it, we do to reduce it to a sum -/ theorem sumAddHom_apply [∀ i, AddZeroClass (β i)] [∀ (i) (x : β i), Decidable (x ≠ 0)] [AddCommMonoid γ] (φ : ∀ i, β i →+ γ) (f : Π₀ i, β i) : sumAddHom φ f = f.sum fun x => φ x := by rcases f with ⟨f, s, hf⟩ change (∑ i ∈ _, _) = ∑ i ∈ Finset.filter _ _, _ rw [Finset.sum_filter, Finset.sum_congr rfl] intro i _ dsimp only [coe_mk', Subtype.coe_mk] at * split_ifs with h · rfl · rw [not_not.mp h, AddMonoidHom.map_zero] theorem _root_.dfinsupp_sumAddHom_mem [∀ i, AddZeroClass (β i)] [AddCommMonoid γ] {S : Type*} [SetLike S γ] [AddSubmonoidClass S γ] (s : S) (f : Π₀ i, β i) (g : ∀ i, β i →+ γ) (h : ∀ c, f c ≠ 0 → g c (f c) ∈ s) : DFinsupp.sumAddHom g f ∈ s := by classical rw [DFinsupp.sumAddHom_apply] exact dfinsupp_sum_mem s f (g ·) h /-- The supremum of a family of commutative additive submonoids is equal to the range of `DFinsupp.sumAddHom`; that is, every element in the `iSup` can be produced from taking a finite number of non-zero elements of `S i`, coercing them to `γ`, and summing them. -/ theorem _root_.AddSubmonoid.iSup_eq_mrange_dfinsupp_sumAddHom [AddCommMonoid γ] (S : ι → AddSubmonoid γ) : iSup S = AddMonoidHom.mrange (DFinsupp.sumAddHom fun i => (S i).subtype) := by apply le_antisymm · apply iSup_le _ intro i y hy exact ⟨DFinsupp.single i ⟨y, hy⟩, DFinsupp.sumAddHom_single _ _ _⟩ · rintro x ⟨v, rfl⟩ exact dfinsupp_sumAddHom_mem _ v _ fun i _ => (le_iSup S i : S i ≤ _) (v i).prop /-- The bounded supremum of a family of commutative additive submonoids is equal to the range of `DFinsupp.sumAddHom` composed with `DFinsupp.filterAddMonoidHom`; that is, every element in the bounded `iSup` can be produced from taking a finite number of non-zero elements from the `S i` that satisfy `p i`, coercing them to `γ`, and summing them. -/ theorem _root_.AddSubmonoid.bsupr_eq_mrange_dfinsupp_sumAddHom (p : ι → Prop) [DecidablePred p] [AddCommMonoid γ] (S : ι → AddSubmonoid γ) : ⨆ (i) (_ : p i), S i = AddMonoidHom.mrange ((sumAddHom fun i => (S i).subtype).comp (filterAddMonoidHom _ p)) := by apply le_antisymm · refine iSup₂_le fun i hi y hy => ⟨DFinsupp.single i ⟨y, hy⟩, ?_⟩ rw [AddMonoidHom.comp_apply, filterAddMonoidHom_apply, filter_single_pos _ _ hi] exact sumAddHom_single _ _ _ · rintro x ⟨v, rfl⟩ refine dfinsupp_sumAddHom_mem _ _ _ fun i _ => ?_ refine AddSubmonoid.mem_iSup_of_mem i ?_ by_cases hp : p i · simp [hp] · simp [hp] theorem _root_.AddSubmonoid.mem_iSup_iff_exists_dfinsupp [AddCommMonoid γ] (S : ι → AddSubmonoid γ) (x : γ) : x ∈ iSup S ↔ ∃ f : Π₀ i, S i, DFinsupp.sumAddHom (fun i => (S i).subtype) f = x := SetLike.ext_iff.mp (AddSubmonoid.iSup_eq_mrange_dfinsupp_sumAddHom S) x /-- A variant of `AddSubmonoid.mem_iSup_iff_exists_dfinsupp` with the RHS fully unfolded. -/ theorem _root_.AddSubmonoid.mem_iSup_iff_exists_dfinsupp' [AddCommMonoid γ] (S : ι → AddSubmonoid γ) [∀ (i) (x : S i), Decidable (x ≠ 0)] (x : γ) : x ∈ iSup S ↔ ∃ f : Π₀ i, S i, (f.sum fun i xi => ↑xi) = x := by rw [AddSubmonoid.mem_iSup_iff_exists_dfinsupp] simp_rw [sumAddHom_apply] rfl theorem _root_.AddSubmonoid.mem_bsupr_iff_exists_dfinsupp (p : ι → Prop) [DecidablePred p] [AddCommMonoid γ] (S : ι → AddSubmonoid γ) (x : γ) : (x ∈ ⨆ (i) (_ : p i), S i) ↔ ∃ f : Π₀ i, S i, DFinsupp.sumAddHom (fun i => (S i).subtype) (f.filter p) = x := SetLike.ext_iff.mp (AddSubmonoid.bsupr_eq_mrange_dfinsupp_sumAddHom p S) x theorem sumAddHom_comm {ι₁ ι₂ : Sort _} {β₁ : ι₁ → Type*} {β₂ : ι₂ → Type*} {γ : Type*} [DecidableEq ι₁] [DecidableEq ι₂] [∀ i, AddZeroClass (β₁ i)] [∀ i, AddZeroClass (β₂ i)] [AddCommMonoid γ] (f₁ : Π₀ i, β₁ i) (f₂ : Π₀ i, β₂ i) (h : ∀ i j, β₁ i →+ β₂ j →+ γ) : sumAddHom (fun i₂ => sumAddHom (fun i₁ => h i₁ i₂) f₁) f₂ = sumAddHom (fun i₁ => sumAddHom (fun i₂ => (h i₁ i₂).flip) f₂) f₁ := by obtain ⟨⟨f₁, s₁, h₁⟩, ⟨f₂, s₂, h₂⟩⟩ := f₁, f₂ simp only [sumAddHom, AddMonoidHom.finset_sum_apply, Quotient.liftOn_mk, AddMonoidHom.coe_mk, AddMonoidHom.flip_apply, Trunc.lift, toFun_eq_coe, ZeroHom.coe_mk, coe_mk'] exact Finset.sum_comm /-- The `DFinsupp` version of `Finsupp.liftAddHom`,-/ @[simps apply symm_apply] def liftAddHom [∀ i, AddZeroClass (β i)] [AddCommMonoid γ] : (∀ i, β i →+ γ) ≃+ ((Π₀ i, β i) →+ γ) where toFun := sumAddHom invFun F i := F.comp (singleAddHom β i) left_inv x := by ext; simp right_inv ψ := by ext; simp map_add' F G := by ext; simp -- Porting note: The elaborator is struggling with `liftAddHom`. Passing it `β` explicitly helps. -- This applies to roughly the remainder of the file. /-- The `DFinsupp` version of `Finsupp.liftAddHom_singleAddHom`,-/ @[simp, nolint simpNF] -- Porting note: linter claims that simp can prove this, but it can not theorem liftAddHom_singleAddHom [∀ i, AddCommMonoid (β i)] : liftAddHom (β := β) (singleAddHom β) = AddMonoidHom.id (Π₀ i, β i) := (liftAddHom (β := β)).toEquiv.apply_eq_iff_eq_symm_apply.2 rfl /-- The `DFinsupp` version of `Finsupp.liftAddHom_apply_single`,-/ theorem liftAddHom_apply_single [∀ i, AddZeroClass (β i)] [AddCommMonoid γ] (f : ∀ i, β i →+ γ) (i : ι) (x : β i) : liftAddHom (β := β) f (single i x) = f i x := by simp /-- The `DFinsupp` version of `Finsupp.liftAddHom_comp_single`,-/ theorem liftAddHom_comp_single [∀ i, AddZeroClass (β i)] [AddCommMonoid γ] (f : ∀ i, β i →+ γ) (i : ι) : (liftAddHom (β := β) f).comp (singleAddHom β i) = f i := by simp /-- The `DFinsupp` version of `Finsupp.comp_liftAddHom`,-/ theorem comp_liftAddHom {δ : Type*} [∀ i, AddZeroClass (β i)] [AddCommMonoid γ] [AddCommMonoid δ] (g : γ →+ δ) (f : ∀ i, β i →+ γ) : g.comp (liftAddHom (β := β) f) = liftAddHom (β := β) fun a => g.comp (f a) := (liftAddHom (β := β)).symm_apply_eq.1 <| funext fun a => by rw [liftAddHom_symm_apply, AddMonoidHom.comp_assoc, liftAddHom_comp_single] @[simp] theorem sumAddHom_zero [∀ i, AddZeroClass (β i)] [AddCommMonoid γ] : (sumAddHom fun i => (0 : β i →+ γ)) = 0 := (liftAddHom (β := β) : (∀ i, β i →+ γ) ≃+ _).map_zero @[simp] theorem sumAddHom_add [∀ i, AddZeroClass (β i)] [AddCommMonoid γ] (g : ∀ i, β i →+ γ) (h : ∀ i, β i →+ γ) : (sumAddHom fun i => g i + h i) = sumAddHom g + sumAddHom h := (liftAddHom (β := β)).map_add _ _ @[simp] theorem sumAddHom_singleAddHom [∀ i, AddCommMonoid (β i)] : sumAddHom (singleAddHom β) = AddMonoidHom.id _ := liftAddHom_singleAddHom theorem comp_sumAddHom {δ : Type*} [∀ i, AddZeroClass (β i)] [AddCommMonoid γ] [AddCommMonoid δ] (g : γ →+ δ) (f : ∀ i, β i →+ γ) : g.comp (sumAddHom f) = sumAddHom fun a => g.comp (f a) := comp_liftAddHom _ _ theorem sum_sub_index [∀ i, AddGroup (β i)] [∀ (i) (x : β i), Decidable (x ≠ 0)] [AddCommGroup γ] {f g : Π₀ i, β i} {h : ∀ i, β i → γ} (h_sub : ∀ i b₁ b₂, h i (b₁ - b₂) = h i b₁ - h i b₂) : (f - g).sum h = f.sum h - g.sum h := by have := (liftAddHom (β := β) fun a => AddMonoidHom.ofMapSub (h a) (h_sub a)).map_sub f g rw [liftAddHom_apply, sumAddHom_apply, sumAddHom_apply, sumAddHom_apply] at this exact this @[to_additive] theorem prod_finset_sum_index {γ : Type w} {α : Type x} [∀ i, AddCommMonoid (β i)] [∀ (i) (x : β i), Decidable (x ≠ 0)] [CommMonoid γ] {s : Finset α} {g : α → Π₀ i, β i} {h : ∀ i, β i → γ} (h_zero : ∀ i, h i 0 = 1) (h_add : ∀ i b₁ b₂, h i (b₁ + b₂) = h i b₁ * h i b₂) : (∏ i ∈ s, (g i).prod h) = (∑ i ∈ s, g i).prod h := by classical exact Finset.induction_on s (by simp [prod_zero_index]) (by simp (config := { contextual := true }) [prod_add_index, h_zero, h_add]) @[to_additive] theorem prod_sum_index {ι₁ : Type u₁} [DecidableEq ι₁] {β₁ : ι₁ → Type v₁} [∀ i₁, Zero (β₁ i₁)] [∀ (i) (x : β₁ i), Decidable (x ≠ 0)] [∀ i, AddCommMonoid (β i)] [∀ (i) (x : β i), Decidable (x ≠ 0)] [CommMonoid γ] {f : Π₀ i₁, β₁ i₁} {g : ∀ i₁, β₁ i₁ → Π₀ i, β i} {h : ∀ i, β i → γ} (h_zero : ∀ i, h i 0 = 1) (h_add : ∀ i b₁ b₂, h i (b₁ + b₂) = h i b₁ * h i b₂) : (f.sum g).prod h = f.prod fun i b => (g i b).prod h := (prod_finset_sum_index h_zero h_add).symm @[simp] theorem sum_single [∀ i, AddCommMonoid (β i)] [∀ (i) (x : β i), Decidable (x ≠ 0)] {f : Π₀ i, β i} : f.sum single = f := by have := DFunLike.congr_fun (liftAddHom_singleAddHom (β := β)) f rw [liftAddHom_apply, sumAddHom_apply] at this exact this @[to_additive] theorem prod_subtypeDomain_index [∀ i, Zero (β i)] [∀ (i) (x : β i), Decidable (x ≠ 0)] [CommMonoid γ] {v : Π₀ i, β i} {p : ι → Prop} [DecidablePred p] {h : ∀ i, β i → γ} (hp : ∀ x ∈ v.support, p x) : (v.subtypeDomain p).prod (fun i b => h i b) = v.prod h := by refine Finset.prod_bij (fun p _ ↦ p) ?_ ?_ ?_ ?_ <;> aesop theorem subtypeDomain_sum [∀ i, AddCommMonoid (β i)] {s : Finset γ} {h : γ → Π₀ i, β i} {p : ι → Prop} [DecidablePred p] : (∑ c ∈ s, h c).subtypeDomain p = ∑ c ∈ s, (h c).subtypeDomain p := map_sum (subtypeDomainAddMonoidHom β p) _ s theorem subtypeDomain_finsupp_sum {δ : γ → Type x} [DecidableEq γ] [∀ c, Zero (δ c)] [∀ (c) (x : δ c), Decidable (x ≠ 0)] [∀ i, AddCommMonoid (β i)] {p : ι → Prop} [DecidablePred p] {s : Π₀ c, δ c} {h : ∀ c, δ c → Π₀ i, β i} : (s.sum h).subtypeDomain p = s.sum fun c d => (h c d).subtypeDomain p := subtypeDomain_sum end ProdAndSum /-! ### Bundled versions of `DFinsupp.mapRange` The names should match the equivalent bundled `Finsupp.mapRange` definitions. -/ section MapRange variable [∀ i, AddZeroClass (β i)] [∀ i, AddZeroClass (β₁ i)] [∀ i, AddZeroClass (β₂ i)] theorem mapRange_add (f : ∀ i, β₁ i → β₂ i) (hf : ∀ i, f i 0 = 0) (hf' : ∀ i x y, f i (x + y) = f i x + f i y) (g₁ g₂ : Π₀ i, β₁ i) : mapRange f hf (g₁ + g₂) = mapRange f hf g₁ + mapRange f hf g₂ := by ext simp only [mapRange_apply f, coe_add, Pi.add_apply, hf'] /-- `DFinsupp.mapRange` as an `AddMonoidHom`. -/ @[simps apply] def mapRange.addMonoidHom (f : ∀ i, β₁ i →+ β₂ i) : (Π₀ i, β₁ i) →+ Π₀ i, β₂ i where toFun := mapRange (fun i x => f i x) fun i => (f i).map_zero map_zero' := mapRange_zero _ _ map_add' := mapRange_add _ (fun i => (f i).map_zero) fun i => (f i).map_add @[simp] theorem mapRange.addMonoidHom_id : (mapRange.addMonoidHom fun i => AddMonoidHom.id (β₂ i)) = AddMonoidHom.id _ := AddMonoidHom.ext mapRange_id theorem mapRange.addMonoidHom_comp (f : ∀ i, β₁ i →+ β₂ i) (f₂ : ∀ i, β i →+ β₁ i) : (mapRange.addMonoidHom fun i => (f i).comp (f₂ i)) = (mapRange.addMonoidHom f).comp (mapRange.addMonoidHom f₂) := by refine AddMonoidHom.ext <| mapRange_comp (fun i x => f i x) (fun i x => f₂ i x) ?_ ?_ ?_ · intros; apply map_zero · intros; apply map_zero · intros; dsimp; simp only [map_zero] /-- `DFinsupp.mapRange.addMonoidHom` as an `AddEquiv`. -/ @[simps apply] def mapRange.addEquiv (e : ∀ i, β₁ i ≃+ β₂ i) : (Π₀ i, β₁ i) ≃+ Π₀ i, β₂ i := { mapRange.addMonoidHom fun i => (e i).toAddMonoidHom with toFun := mapRange (fun i x => e i x) fun i => (e i).map_zero invFun := mapRange (fun i x => (e i).symm x) fun i => (e i).symm.map_zero left_inv := fun x => by rw [← mapRange_comp] <;> · simp_rw [AddEquiv.symm_comp_self] simp right_inv := fun x => by rw [← mapRange_comp] <;> · simp_rw [AddEquiv.self_comp_symm] simp } @[simp] theorem mapRange.addEquiv_refl : (mapRange.addEquiv fun i => AddEquiv.refl (β₁ i)) = AddEquiv.refl _ := AddEquiv.ext mapRange_id theorem mapRange.addEquiv_trans (f : ∀ i, β i ≃+ β₁ i) (f₂ : ∀ i, β₁ i ≃+ β₂ i) : (mapRange.addEquiv fun i => (f i).trans (f₂ i)) = (mapRange.addEquiv f).trans (mapRange.addEquiv f₂) := by refine AddEquiv.ext <| mapRange_comp (fun i x => f₂ i x) (fun i x => f i x) ?_ ?_ ?_ · intros; apply map_zero · intros; apply map_zero · intros; dsimp; simp only [map_zero] @[simp] theorem mapRange.addEquiv_symm (e : ∀ i, β₁ i ≃+ β₂ i) : (mapRange.addEquiv e).symm = mapRange.addEquiv fun i => (e i).symm := rfl end MapRange end DFinsupp /-! ### Product and sum lemmas for bundled morphisms. In this section, we provide analogues of `AddMonoidHom.map_sum`, `AddMonoidHom.coe_finset_sum`, and `AddMonoidHom.finset_sum_apply` for `DFinsupp.sum` and `DFinsupp.sumAddHom` instead of `Finset.sum`. We provide these for `AddMonoidHom`, `MonoidHom`, `RingHom`, `AddEquiv`, and `MulEquiv`. Lemmas for `LinearMap` and `LinearEquiv` are in another file. -/ section variable [DecidableEq ι] namespace MonoidHom variable {R S : Type*} variable [∀ i, Zero (β i)] [∀ (i) (x : β i), Decidable (x ≠ 0)] @[to_additive (attr := simp, norm_cast)] theorem coe_dfinsupp_prod [Monoid R] [CommMonoid S] (f : Π₀ i, β i) (g : ∀ i, β i → R →* S) : ⇑(f.prod g) = f.prod fun a b => ⇑(g a b) := coe_finset_prod _ _ @[to_additive] theorem dfinsupp_prod_apply [Monoid R] [CommMonoid S] (f : Π₀ i, β i) (g : ∀ i, β i → R →* S) (r : R) : (f.prod g) r = f.prod fun a b => (g a b) r := finset_prod_apply _ _ _ end MonoidHom /-! The above lemmas, repeated for `DFinsupp.sumAddHom`. -/ namespace AddMonoidHom variable {R S : Type*} open DFinsupp @[simp] theorem map_dfinsupp_sumAddHom [AddCommMonoid R] [AddCommMonoid S] [∀ i, AddZeroClass (β i)] (h : R →+ S) (f : Π₀ i, β i) (g : ∀ i, β i →+ R) : h (sumAddHom g f) = sumAddHom (fun i => h.comp (g i)) f := DFunLike.congr_fun (comp_liftAddHom h g) f theorem dfinsupp_sumAddHom_apply [AddZeroClass R] [AddCommMonoid S] [∀ i, AddZeroClass (β i)] (f : Π₀ i, β i) (g : ∀ i, β i →+ R →+ S) (r : R) : (sumAddHom g f) r = sumAddHom (fun i => (eval r).comp (g i)) f := map_dfinsupp_sumAddHom (eval r) f g @[simp, norm_cast] theorem coe_dfinsupp_sumAddHom [AddZeroClass R] [AddCommMonoid S] [∀ i, AddZeroClass (β i)] (f : Π₀ i, β i) (g : ∀ i, β i →+ R →+ S) : ⇑(sumAddHom g f) = sumAddHom (fun i => (coeFn R S).comp (g i)) f := map_dfinsupp_sumAddHom (coeFn R S) f g end AddMonoidHom namespace RingHom variable {R S : Type*} open DFinsupp @[simp] theorem map_dfinsupp_sumAddHom [NonAssocSemiring R] [NonAssocSemiring S] [∀ i, AddZeroClass (β i)] (h : R →+* S) (f : Π₀ i, β i) (g : ∀ i, β i →+ R) : h (sumAddHom g f) = sumAddHom (fun i => h.toAddMonoidHom.comp (g i)) f := DFunLike.congr_fun (comp_liftAddHom h.toAddMonoidHom g) f end RingHom namespace AddEquiv variable {R S : Type*} open DFinsupp @[simp] theorem map_dfinsupp_sumAddHom [AddCommMonoid R] [AddCommMonoid S] [∀ i, AddZeroClass (β i)] (h : R ≃+ S) (f : Π₀ i, β i) (g : ∀ i, β i →+ R) : h (sumAddHom g f) = sumAddHom (fun i => h.toAddMonoidHom.comp (g i)) f := DFunLike.congr_fun (comp_liftAddHom h.toAddMonoidHom g) f end AddEquiv end section FiniteInfinite instance DFinsupp.fintype {ι : Sort _} {π : ι → Sort _} [DecidableEq ι] [∀ i, Zero (π i)] [Fintype ι] [∀ i, Fintype (π i)] : Fintype (Π₀ i, π i) := Fintype.ofEquiv (∀ i, π i) DFinsupp.equivFunOnFintype.symm instance DFinsupp.infinite_of_left {ι : Sort _} {π : ι → Sort _} [∀ i, Nontrivial (π i)] [∀ i, Zero (π i)] [Infinite ι] : Infinite (Π₀ i, π i) := by letI := Classical.decEq ι; choose m hm using fun i => exists_ne (0 : π i) exact Infinite.of_injective _ (DFinsupp.single_left_injective hm) /-- See `DFinsupp.infinite_of_right` for this in instance form, with the drawback that it needs all `π i` to be infinite. -/ theorem DFinsupp.infinite_of_exists_right {ι : Sort _} {π : ι → Sort _} (i : ι) [Infinite (π i)] [∀ i, Zero (π i)] : Infinite (Π₀ i, π i) := letI := Classical.decEq ι Infinite.of_injective (fun j => DFinsupp.single i j) DFinsupp.single_injective /-- See `DFinsupp.infinite_of_exists_right` for the case that only one `π ι` is infinite. -/ instance DFinsupp.infinite_of_right {ι : Sort _} {π : ι → Sort _} [∀ i, Infinite (π i)] [∀ i, Zero (π i)] [Nonempty ι] : Infinite (Π₀ i, π i) := DFinsupp.infinite_of_exists_right (Classical.arbitrary ι) end FiniteInfinite
Data\DFinsupp\Encodable.lean
/- Copyright (c) 2023 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import Mathlib.Data.DFinsupp.Basic import Mathlib.Logic.Equiv.List /-! # `Encodable` and `Countable` instances for `Π₀ i, α i` In this file we provide instances for `Encodable (Π₀ i, α i)` and `Countable (Π₀ i, α i)`. -/ variable {ι : Type*} {α : ι → Type*} [∀ i, Zero (α i)] instance [Encodable ι] [∀ i, Encodable (α i)] [∀ i (x : α i), Decidable (x ≠ 0)] : Encodable (Π₀ i, α i) := letI : DecidableEq ι := Encodable.decidableEqOfEncodable _ letI : ∀ s : Finset ι, Encodable (∀ i : s, {x : α i // x ≠ 0}) := fun _ ↦ .ofEquiv _ <| .piCongrLeft' _ Encodable.fintypeEquivFin .ofEquiv _ DFinsupp.sigmaFinsetFunEquiv instance [Countable ι] [∀ i, Countable (α i)] : Countable (Π₀ i, α i) := by classical let _ := Encodable.ofCountable ι let _ := fun i ↦ Encodable.ofCountable (α i) infer_instance
Data\DFinsupp\Interval.lean
/- Copyright (c) 2021 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import Mathlib.Data.Finset.Pointwise import Mathlib.Data.Fintype.BigOperators import Mathlib.Data.DFinsupp.Order import Mathlib.Order.Interval.Finset.Basic /-! # Finite intervals of finitely supported functions This file provides the `LocallyFiniteOrder` instance for `Π₀ i, α i` when `α` itself is locally finite and calculates the cardinality of its finite intervals. -/ open DFinsupp Finset open Pointwise variable {ι : Type*} {α : ι → Type*} namespace Finset variable [DecidableEq ι] [∀ i, Zero (α i)] {s : Finset ι} {f : Π₀ i, α i} {t : ∀ i, Finset (α i)} /-- Finitely supported product of finsets. -/ def dfinsupp (s : Finset ι) (t : ∀ i, Finset (α i)) : Finset (Π₀ i, α i) := (s.pi t).map ⟨fun f => DFinsupp.mk s fun i => f i i.2, by refine (mk_injective _).comp fun f g h => ?_ ext i hi convert congr_fun h ⟨i, hi⟩⟩ @[simp] theorem card_dfinsupp (s : Finset ι) (t : ∀ i, Finset (α i)) : (s.dfinsupp t).card = ∏ i ∈ s, (t i).card := (card_map _).trans <| card_pi _ _ variable [∀ i, DecidableEq (α i)] theorem mem_dfinsupp_iff : f ∈ s.dfinsupp t ↔ f.support ⊆ s ∧ ∀ i ∈ s, f i ∈ t i := by refine mem_map.trans ⟨?_, ?_⟩ · rintro ⟨f, hf, rfl⟩ rw [Function.Embedding.coeFn_mk] -- Porting note: added to avoid heartbeat timeout refine ⟨support_mk_subset, fun i hi => ?_⟩ convert mem_pi.1 hf i hi exact mk_of_mem hi · refine fun h => ⟨fun i _ => f i, mem_pi.2 h.2, ?_⟩ ext i dsimp exact ite_eq_left_iff.2 fun hi => (not_mem_support_iff.1 fun H => hi <| h.1 H).symm /-- When `t` is supported on `s`, `f ∈ s.dfinsupp t` precisely means that `f` is pointwise in `t`. -/ @[simp] theorem mem_dfinsupp_iff_of_support_subset {t : Π₀ i, Finset (α i)} (ht : t.support ⊆ s) : f ∈ s.dfinsupp t ↔ ∀ i, f i ∈ t i := by refine mem_dfinsupp_iff.trans (forall_and.symm.trans <| forall_congr' fun i => ⟨ fun h => ?_, fun h => ⟨fun hi => ht <| mem_support_iff.2 fun H => mem_support_iff.1 hi ?_, fun _ => h⟩⟩) · by_cases hi : i ∈ s · exact h.2 hi · rw [not_mem_support_iff.1 (mt h.1 hi), not_mem_support_iff.1 (not_mem_mono ht hi)] exact zero_mem_zero · rwa [H, mem_zero] at h end Finset open Finset namespace DFinsupp section BundledSingleton variable [∀ i, Zero (α i)] {f : Π₀ i, α i} {i : ι} {a : α i} /-- Pointwise `Finset.singleton` bundled as a `DFinsupp`. -/ def singleton (f : Π₀ i, α i) : Π₀ i, Finset (α i) where toFun i := {f i} support' := f.support'.map fun s => ⟨s.1, fun i => (s.prop i).imp id (congr_arg _)⟩ theorem mem_singleton_apply_iff : a ∈ f.singleton i ↔ a = f i := mem_singleton end BundledSingleton section BundledIcc variable [∀ i, Zero (α i)] [∀ i, PartialOrder (α i)] [∀ i, LocallyFiniteOrder (α i)] {f g : Π₀ i, α i} {i : ι} {a : α i} /-- Pointwise `Finset.Icc` bundled as a `DFinsupp`. -/ def rangeIcc (f g : Π₀ i, α i) : Π₀ i, Finset (α i) where toFun i := Icc (f i) (g i) support' := f.support'.bind fun fs => g.support'.map fun gs => ⟨ fs.1 + gs.1, fun i => or_iff_not_imp_left.2 fun h => by have hf : f i = 0 := (fs.prop i).resolve_left (Multiset.not_mem_mono (Multiset.Le.subset <| Multiset.le_add_right _ _) h) have hg : g i = 0 := (gs.prop i).resolve_left (Multiset.not_mem_mono (Multiset.Le.subset <| Multiset.le_add_left _ _) h) -- Porting note: was rw, but was rewriting under lambda, so changed to simp_rw simp_rw [hf, hg] exact Icc_self _⟩ @[simp] theorem rangeIcc_apply (f g : Π₀ i, α i) (i : ι) : f.rangeIcc g i = Icc (f i) (g i) := rfl theorem mem_rangeIcc_apply_iff : a ∈ f.rangeIcc g i ↔ f i ≤ a ∧ a ≤ g i := mem_Icc theorem support_rangeIcc_subset [DecidableEq ι] [∀ i, DecidableEq (α i)] : (f.rangeIcc g).support ⊆ f.support ∪ g.support := by refine fun x hx => ?_ by_contra h refine not_mem_support_iff.2 ?_ hx rw [rangeIcc_apply, not_mem_support_iff.1 (not_mem_mono subset_union_left h), not_mem_support_iff.1 (not_mem_mono subset_union_right h)] exact Icc_self _ end BundledIcc section Pi variable [∀ i, Zero (α i)] [DecidableEq ι] [∀ i, DecidableEq (α i)] /-- Given a finitely supported function `f : Π₀ i, Finset (α i)`, one can define the finset `f.pi` of all finitely supported functions whose value at `i` is in `f i` for all `i`. -/ def pi (f : Π₀ i, Finset (α i)) : Finset (Π₀ i, α i) := f.support.dfinsupp f @[simp] theorem mem_pi {f : Π₀ i, Finset (α i)} {g : Π₀ i, α i} : g ∈ f.pi ↔ ∀ i, g i ∈ f i := mem_dfinsupp_iff_of_support_subset <| Subset.refl _ @[simp] theorem card_pi (f : Π₀ i, Finset (α i)) : f.pi.card = f.prod fun i => (f i).card := by rw [pi, card_dfinsupp] exact Finset.prod_congr rfl fun i _ => by simp only [Pi.natCast_apply, Nat.cast_id] end Pi section PartialOrder variable [DecidableEq ι] [∀ i, DecidableEq (α i)] variable [∀ i, PartialOrder (α i)] [∀ i, Zero (α i)] [∀ i, LocallyFiniteOrder (α i)] instance instLocallyFiniteOrder : LocallyFiniteOrder (Π₀ i, α i) := LocallyFiniteOrder.ofIcc (Π₀ i, α i) (fun f g => (f.support ∪ g.support).dfinsupp <| f.rangeIcc g) (fun f g x => by refine (mem_dfinsupp_iff_of_support_subset <| support_rangeIcc_subset).trans ?_ simp_rw [mem_rangeIcc_apply_iff, forall_and] rfl) variable (f g : Π₀ i, α i) theorem Icc_eq : Icc f g = (f.support ∪ g.support).dfinsupp (f.rangeIcc g) := rfl theorem card_Icc : (Icc f g).card = ∏ i ∈ f.support ∪ g.support, (Icc (f i) (g i)).card := card_dfinsupp _ _ theorem card_Ico : (Ico f g).card = (∏ i ∈ f.support ∪ g.support, (Icc (f i) (g i)).card) - 1 := by rw [card_Ico_eq_card_Icc_sub_one, card_Icc] theorem card_Ioc : (Ioc f g).card = (∏ i ∈ f.support ∪ g.support, (Icc (f i) (g i)).card) - 1 := by rw [card_Ioc_eq_card_Icc_sub_one, card_Icc] theorem card_Ioo : (Ioo f g).card = (∏ i ∈ f.support ∪ g.support, (Icc (f i) (g i)).card) - 2 := by rw [card_Ioo_eq_card_Icc_sub_two, card_Icc] end PartialOrder section Lattice variable [DecidableEq ι] [∀ i, DecidableEq (α i)] [∀ i, Lattice (α i)] [∀ i, Zero (α i)] [∀ i, LocallyFiniteOrder (α i)] (f g : Π₀ i, α i) theorem card_uIcc : (uIcc f g).card = ∏ i ∈ f.support ∪ g.support, (uIcc (f i) (g i)).card := by rw [← support_inf_union_support_sup]; exact card_Icc _ _ end Lattice section CanonicallyOrdered variable [DecidableEq ι] [∀ i, DecidableEq (α i)] variable [∀ i, CanonicallyOrderedAddCommMonoid (α i)] [∀ i, LocallyFiniteOrder (α i)] variable (f : Π₀ i, α i) theorem card_Iic : (Iic f).card = ∏ i ∈ f.support, (Iic (f i)).card := by simp_rw [Iic_eq_Icc, card_Icc, DFinsupp.bot_eq_zero, support_zero, empty_union, zero_apply, bot_eq_zero] theorem card_Iio : (Iio f).card = (∏ i ∈ f.support, (Iic (f i)).card) - 1 := by rw [card_Iio_eq_card_Iic_sub_one, card_Iic] end CanonicallyOrdered end DFinsupp
Data\DFinsupp\Lex.lean
/- Copyright (c) 2022 Junyan Xu. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Damiano Testa, Junyan Xu -/ import Mathlib.Algebra.Order.Group.PiLex import Mathlib.Data.DFinsupp.Order import Mathlib.Data.DFinsupp.NeLocus import Mathlib.Order.WellFoundedSet /-! # Lexicographic order on finitely supported dependent functions This file defines the lexicographic order on `DFinsupp`. -/ variable {ι : Type*} {α : ι → Type*} namespace DFinsupp section Zero variable [∀ i, Zero (α i)] /-- `DFinsupp.Lex r s` is the lexicographic relation on `Π₀ i, α i`, where `ι` is ordered by `r`, and `α i` is ordered by `s i`. The type synonym `Lex (Π₀ i, α i)` has an order given by `DFinsupp.Lex (· < ·) (· < ·)`. -/ protected def Lex (r : ι → ι → Prop) (s : ∀ i, α i → α i → Prop) (x y : Π₀ i, α i) : Prop := Pi.Lex r (s _) x y -- Porting note: Added `_root_` to match more closely with Lean 3. Also updated `s`'s type. theorem _root_.Pi.lex_eq_dfinsupp_lex {r : ι → ι → Prop} {s : ∀ i, α i → α i → Prop} (a b : Π₀ i, α i) : Pi.Lex r (s _) (a : ∀ i, α i) b = DFinsupp.Lex r s a b := rfl -- Porting note: Updated `s`'s type. theorem lex_def {r : ι → ι → Prop} {s : ∀ i, α i → α i → Prop} {a b : Π₀ i, α i} : DFinsupp.Lex r s a b ↔ ∃ j, (∀ d, r d j → a d = b d) ∧ s j (a j) (b j) := Iff.rfl instance [LT ι] [∀ i, LT (α i)] : LT (Lex (Π₀ i, α i)) := ⟨fun f g ↦ DFinsupp.Lex (· < ·) (fun _ ↦ (· < ·)) (ofLex f) (ofLex g)⟩ theorem lex_lt_of_lt_of_preorder [∀ i, Preorder (α i)] (r) [IsStrictOrder ι r] {x y : Π₀ i, α i} (hlt : x < y) : ∃ i, (∀ j, r j i → x j ≤ y j ∧ y j ≤ x j) ∧ x i < y i := by obtain ⟨hle, j, hlt⟩ := Pi.lt_def.1 hlt classical have : (x.neLocus y : Set ι).WellFoundedOn r := (x.neLocus y).finite_toSet.wellFoundedOn obtain ⟨i, hi, hl⟩ := this.has_min { i | x i < y i } ⟨⟨j, mem_neLocus.2 hlt.ne⟩, hlt⟩ refine ⟨i, fun k hk ↦ ⟨hle k, ?_⟩, hi⟩ exact of_not_not fun h ↦ hl ⟨k, mem_neLocus.2 (ne_of_not_le h).symm⟩ ((hle k).lt_of_not_le h) hk theorem lex_lt_of_lt [∀ i, PartialOrder (α i)] (r) [IsStrictOrder ι r] {x y : Π₀ i, α i} (hlt : x < y) : Pi.Lex r (· < ·) x y := by simp_rw [Pi.Lex, le_antisymm_iff] exact lex_lt_of_lt_of_preorder r hlt variable [LinearOrder ι] instance Lex.isStrictOrder [∀ i, PartialOrder (α i)] : IsStrictOrder (Lex (Π₀ i, α i)) (· < ·) := let i : IsStrictOrder (Lex (∀ i, α i)) (· < ·) := Pi.Lex.isStrictOrder { irrefl := toLex.surjective.forall.2 fun _ ↦ @irrefl _ _ i.toIsIrrefl _ trans := toLex.surjective.forall₃.2 fun _ _ _ ↦ @trans _ _ i.toIsTrans _ _ _ } /-- The partial order on `DFinsupp`s obtained by the lexicographic ordering. See `DFinsupp.Lex.linearOrder` for a proof that this partial order is in fact linear. -/ instance Lex.partialOrder [∀ i, PartialOrder (α i)] : PartialOrder (Lex (Π₀ i, α i)) where lt := (· < ·) le x y := ⇑(ofLex x) = ⇑(ofLex y) ∨ x < y __ := PartialOrder.lift (fun x : Lex (Π₀ i, α i) ↦ toLex (⇑(ofLex x))) (DFunLike.coe_injective (F := DFinsupp α)) section LinearOrder variable [∀ i, LinearOrder (α i)] /-- Auxiliary helper to case split computably. There is no need for this to be public, as it can be written with `Or.by_cases` on `lt_trichotomy` once the instances below are constructed. -/ private def lt_trichotomy_rec {P : Lex (Π₀ i, α i) → Lex (Π₀ i, α i) → Sort*} (h_lt : ∀ {f g}, toLex f < toLex g → P (toLex f) (toLex g)) (h_eq : ∀ {f g}, toLex f = toLex g → P (toLex f) (toLex g)) (h_gt : ∀ {f g}, toLex g < toLex f → P (toLex f) (toLex g)) : ∀ f g, P f g := Lex.rec fun f ↦ Lex.rec fun g ↦ match (motive := ∀ y, (f.neLocus g).min = y → _) _, rfl with | ⊤, h => h_eq (neLocus_eq_empty.mp <| Finset.min_eq_top.mp h) | (wit : ι), h => by apply (mem_neLocus.mp <| Finset.mem_of_min h).lt_or_lt.by_cases <;> intro hwit · exact h_lt ⟨wit, fun j hj ↦ not_mem_neLocus.mp (Finset.not_mem_of_lt_min hj h), hwit⟩ · exact h_gt ⟨wit, fun j hj ↦ not_mem_neLocus.mp (Finset.not_mem_of_lt_min hj <| by rwa [neLocus_comm]), hwit⟩ /-- The less-or-equal relation for the lexicographic ordering is decidable. -/ irreducible_def Lex.decidableLE : @DecidableRel (Lex (Π₀ i, α i)) (· ≤ ·) := lt_trichotomy_rec (fun h ↦ isTrue <| Or.inr h) (fun h ↦ isTrue <| Or.inl <| congr_arg _ h) fun h ↦ isFalse fun h' ↦ lt_irrefl _ (h.trans_le h') /-- The less-than relation for the lexicographic ordering is decidable. -/ irreducible_def Lex.decidableLT : @DecidableRel (Lex (Π₀ i, α i)) (· < ·) := lt_trichotomy_rec (fun h ↦ isTrue h) (fun h ↦ isFalse h.not_lt) fun h ↦ isFalse h.asymm -- Porting note: Added `DecidableEq` for `LinearOrder`. instance : DecidableEq (Lex (Π₀ i, α i)) := lt_trichotomy_rec (fun h ↦ isFalse fun h' ↦ h'.not_lt h) isTrue fun h ↦ isFalse fun h' ↦ h'.symm.not_lt h /-- The linear order on `DFinsupp`s obtained by the lexicographic ordering. -/ instance Lex.linearOrder : LinearOrder (Lex (Π₀ i, α i)) where __ := Lex.partialOrder le_total := lt_trichotomy_rec (fun h ↦ Or.inl h.le) (fun h ↦ Or.inl h.le) fun h ↦ Or.inr h.le decidableLT := decidableLT decidableLE := decidableLE decidableEq := inferInstance end LinearOrder variable [∀ i, PartialOrder (α i)] theorem toLex_monotone : Monotone (@toLex (Π₀ i, α i)) := by intro a b h refine le_of_lt_or_eq (or_iff_not_imp_right.2 fun hne ↦ ?_) classical exact ⟨Finset.min' _ (nonempty_neLocus_iff.2 hne), fun j hj ↦ not_mem_neLocus.1 fun h ↦ (Finset.min'_le _ _ h).not_lt hj, (h _).lt_of_ne (mem_neLocus.1 <| Finset.min'_mem _ _)⟩ theorem lt_of_forall_lt_of_lt (a b : Lex (Π₀ i, α i)) (i : ι) : (∀ j < i, ofLex a j = ofLex b j) → ofLex a i < ofLex b i → a < b := fun h1 h2 ↦ ⟨i, h1, h2⟩ end Zero section Covariants variable [LinearOrder ι] [∀ i, AddMonoid (α i)] [∀ i, LinearOrder (α i)] /-! We are about to sneak in a hypothesis that might appear to be too strong. We assume `CovariantClass` with *strict* inequality `<` also when proving the one with the *weak* inequality `≤`. This is actually necessary: addition on `Lex (Π₀ i, α i)` may fail to be monotone, when it is "just" monotone on `α i`. -/ section Left variable [∀ i, CovariantClass (α i) (α i) (· + ·) (· < ·)] instance Lex.covariantClass_lt_left : CovariantClass (Lex (Π₀ i, α i)) (Lex (Π₀ i, α i)) (· + ·) (· < ·) := ⟨fun _ _ _ ⟨a, lta, ha⟩ ↦ ⟨a, fun j ja ↦ congr_arg _ (lta j ja), add_lt_add_left ha _⟩⟩ instance Lex.covariantClass_le_left : CovariantClass (Lex (Π₀ i, α i)) (Lex (Π₀ i, α i)) (· + ·) (· ≤ ·) := covariantClass_le_of_lt _ _ _ end Left section Right variable [∀ i, CovariantClass (α i) (α i) (Function.swap (· + ·)) (· < ·)] instance Lex.covariantClass_lt_right : CovariantClass (Lex (Π₀ i, α i)) (Lex (Π₀ i, α i)) (Function.swap (· + ·)) (· < ·) := ⟨fun f _ _ ⟨a, lta, ha⟩ ↦ ⟨a, fun j ja ↦ congr_arg (· + ofLex f j) (lta j ja), add_lt_add_right ha _⟩⟩ instance Lex.covariantClass_le_right : CovariantClass (Lex (Π₀ i, α i)) (Lex (Π₀ i, α i)) (Function.swap (· + ·)) (· ≤ ·) := covariantClass_le_of_lt _ _ _ end Right end Covariants section OrderedAddMonoid variable [LinearOrder ι] instance Lex.orderBot [∀ i, CanonicallyOrderedAddCommMonoid (α i)] : OrderBot (Lex (Π₀ i, α i)) where bot := 0 bot_le _ := DFinsupp.toLex_monotone bot_le instance Lex.orderedAddCancelCommMonoid [∀ i, OrderedCancelAddCommMonoid (α i)] : OrderedCancelAddCommMonoid (Lex (Π₀ i, α i)) where add_le_add_left _ _ h _ := add_le_add_left (α := Lex (∀ i, α i)) h _ le_of_add_le_add_left _ _ _ := le_of_add_le_add_left (α := Lex (∀ i, α i)) instance Lex.orderedAddCommGroup [∀ i, OrderedAddCommGroup (α i)] : OrderedAddCommGroup (Lex (Π₀ i, α i)) where add_le_add_left _ _ := add_le_add_left instance Lex.linearOrderedCancelAddCommMonoid [∀ i, LinearOrderedCancelAddCommMonoid (α i)] : LinearOrderedCancelAddCommMonoid (Lex (Π₀ i, α i)) where __ : LinearOrder (Lex (Π₀ i, α i)) := inferInstance __ : OrderedCancelAddCommMonoid (Lex (Π₀ i, α i)) := inferInstance instance Lex.linearOrderedAddCommGroup [∀ i, LinearOrderedAddCommGroup (α i)] : LinearOrderedAddCommGroup (Lex (Π₀ i, α i)) where __ : LinearOrder (Lex (Π₀ i, α i)) := inferInstance add_le_add_left _ _ := add_le_add_left end OrderedAddMonoid end DFinsupp
Data\DFinsupp\Multiset.lean
/- Copyright (c) 2022 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import Mathlib.Data.DFinsupp.Order /-! # Equivalence between `Multiset` and `ℕ`-valued finitely supported functions This defines `DFinsupp.toMultiset` the equivalence between `Π₀ a : α, ℕ` and `Multiset α`, along with `Multiset.toDFinsupp` the reverse equivalence. -/ open Function variable {α : Type*} {β : α → Type*} namespace DFinsupp /-- Non-dependent special case of `DFinsupp.addZeroClass` to help typeclass search. -/ instance addZeroClass' {β} [AddZeroClass β] : AddZeroClass (Π₀ _ : α, β) := @DFinsupp.addZeroClass α (fun _ ↦ β) _ variable [DecidableEq α] {s t : Multiset α} /-- A DFinsupp version of `Finsupp.toMultiset`. -/ def toMultiset : (Π₀ _ : α, ℕ) →+ Multiset α := DFinsupp.sumAddHom fun a : α ↦ Multiset.replicateAddMonoidHom a @[simp] theorem toMultiset_single (a : α) (n : ℕ) : toMultiset (DFinsupp.single a n) = Multiset.replicate n a := DFinsupp.sumAddHom_single _ _ _ end DFinsupp namespace Multiset variable [DecidableEq α] {s t : Multiset α} /-- A DFinsupp version of `Multiset.toFinsupp`. -/ def toDFinsupp : Multiset α →+ Π₀ _ : α, ℕ where toFun s := { toFun := fun n ↦ s.count n support' := Trunc.mk ⟨s, fun i ↦ (em (i ∈ s)).imp_right Multiset.count_eq_zero_of_not_mem⟩ } map_zero' := rfl map_add' _ _ := DFinsupp.ext fun _ ↦ Multiset.count_add _ _ _ @[simp] theorem toDFinsupp_apply (s : Multiset α) (a : α) : Multiset.toDFinsupp s a = s.count a := rfl @[simp] theorem toDFinsupp_support (s : Multiset α) : s.toDFinsupp.support = s.toFinset := Finset.filter_true_of_mem fun _ hx ↦ count_ne_zero.mpr <| Multiset.mem_toFinset.1 hx @[simp] theorem toDFinsupp_replicate (a : α) (n : ℕ) : toDFinsupp (Multiset.replicate n a) = DFinsupp.single a n := by ext i dsimp [toDFinsupp] simp [count_replicate, eq_comm] @[simp] theorem toDFinsupp_singleton (a : α) : toDFinsupp {a} = DFinsupp.single a 1 := by rw [← replicate_one, toDFinsupp_replicate] /-- `Multiset.toDFinsupp` as an `AddEquiv`. -/ @[simps! apply symm_apply] def equivDFinsupp : Multiset α ≃+ Π₀ _ : α, ℕ := AddMonoidHom.toAddEquiv Multiset.toDFinsupp DFinsupp.toMultiset (by ext; simp) (by ext; simp) @[simp] theorem toDFinsupp_toMultiset (s : Multiset α) : DFinsupp.toMultiset (Multiset.toDFinsupp s) = s := equivDFinsupp.symm_apply_apply s theorem toDFinsupp_injective : Injective (toDFinsupp : Multiset α → Π₀ _a, ℕ) := equivDFinsupp.injective @[simp] theorem toDFinsupp_inj : toDFinsupp s = toDFinsupp t ↔ s = t := toDFinsupp_injective.eq_iff @[simp] theorem toDFinsupp_le_toDFinsupp : toDFinsupp s ≤ toDFinsupp t ↔ s ≤ t := by simp [Multiset.le_iff_count, DFinsupp.le_def] @[simp] theorem toDFinsupp_lt_toDFinsupp : toDFinsupp s < toDFinsupp t ↔ s < t := lt_iff_lt_of_le_iff_le' toDFinsupp_le_toDFinsupp toDFinsupp_le_toDFinsupp @[simp] theorem toDFinsupp_inter (s t : Multiset α) : toDFinsupp (s ∩ t) = toDFinsupp s ⊓ toDFinsupp t := by ext i; simp [inf_eq_min] @[simp] theorem toDFinsupp_union (s t : Multiset α) : toDFinsupp (s ∪ t) = toDFinsupp s ⊔ toDFinsupp t := by ext i; simp [sup_eq_max] end Multiset namespace DFinsupp variable [DecidableEq α] {f g : Π₀ _a : α, ℕ} @[simp] theorem toMultiset_toDFinsupp (f : Π₀ _ : α, ℕ) : Multiset.toDFinsupp (DFinsupp.toMultiset f) = f := Multiset.equivDFinsupp.apply_symm_apply f theorem toMultiset_injective : Injective (toMultiset : (Π₀ _a, ℕ) → Multiset α) := Multiset.equivDFinsupp.symm.injective @[simp] theorem toMultiset_inj : toMultiset f = toMultiset g ↔ f = g := toMultiset_injective.eq_iff @[simp] theorem toMultiset_le_toMultiset : toMultiset f ≤ toMultiset g ↔ f ≤ g := by simp_rw [← Multiset.toDFinsupp_le_toDFinsupp, toMultiset_toDFinsupp] @[simp] theorem toMultiset_lt_toMultiset : toMultiset f < toMultiset g ↔ f < g := by simp_rw [← Multiset.toDFinsupp_lt_toDFinsupp, toMultiset_toDFinsupp] variable (f g) @[simp] theorem toMultiset_inf : toMultiset (f ⊓ g) = toMultiset f ∩ toMultiset g := Multiset.toDFinsupp_injective <| by simp @[simp] theorem toMultiset_sup : toMultiset (f ⊔ g) = toMultiset f∪ toMultiset g := Multiset.toDFinsupp_injective <| by simp end DFinsupp
Data\DFinsupp\NeLocus.lean
/- Copyright (c) 2022 Junyan Xu. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Damiano Testa, Junyan Xu -/ import Mathlib.Data.DFinsupp.Basic /-! # Locus of unequal values of finitely supported dependent functions Let `N : α → Type*` be a type family, assume that `N a` has a `0` for all `a : α` and let `f g : Π₀ a, N a` be finitely supported dependent functions. ## Main definition * `DFinsupp.neLocus f g : Finset α`, the finite subset of `α` where `f` and `g` differ. In the case in which `N a` is an additive group for all `a`, `DFinsupp.neLocus f g` coincides with `DFinsupp.support (f - g)`. -/ variable {α : Type*} {N : α → Type*} namespace DFinsupp variable [DecidableEq α] section NHasZero variable [∀ a, DecidableEq (N a)] [∀ a, Zero (N a)] (f g : Π₀ a, N a) /-- Given two finitely supported functions `f g : α →₀ N`, `Finsupp.neLocus f g` is the `Finset` where `f` and `g` differ. This generalizes `(f - g).support` to situations without subtraction. -/ def neLocus (f g : Π₀ a, N a) : Finset α := (f.support ∪ g.support).filter fun x ↦ f x ≠ g x @[simp] theorem mem_neLocus {f g : Π₀ a, N a} {a : α} : a ∈ f.neLocus g ↔ f a ≠ g a := by simpa only [neLocus, Finset.mem_filter, Finset.mem_union, mem_support_iff, and_iff_right_iff_imp] using Ne.ne_or_ne _ theorem not_mem_neLocus {f g : Π₀ a, N a} {a : α} : a ∉ f.neLocus g ↔ f a = g a := mem_neLocus.not.trans not_ne_iff @[simp] theorem coe_neLocus : ↑(f.neLocus g) = { x | f x ≠ g x } := Set.ext fun _x ↦ mem_neLocus @[simp] theorem neLocus_eq_empty {f g : Π₀ a, N a} : f.neLocus g = ∅ ↔ f = g := ⟨fun h ↦ ext fun a ↦ not_not.mp (mem_neLocus.not.mp (Finset.eq_empty_iff_forall_not_mem.mp h a)), fun h ↦ h ▸ by simp only [neLocus, Ne, eq_self_iff_true, not_true, Finset.filter_False]⟩ @[simp] theorem nonempty_neLocus_iff {f g : Π₀ a, N a} : (f.neLocus g).Nonempty ↔ f ≠ g := Finset.nonempty_iff_ne_empty.trans neLocus_eq_empty.not theorem neLocus_comm : f.neLocus g = g.neLocus f := by simp_rw [neLocus, Finset.union_comm, ne_comm] @[simp] theorem neLocus_zero_right : f.neLocus 0 = f.support := by ext rw [mem_neLocus, mem_support_iff, coe_zero, Pi.zero_apply] @[simp] theorem neLocus_zero_left : (0 : Π₀ a, N a).neLocus f = f.support := (neLocus_comm _ _).trans (neLocus_zero_right _) end NHasZero section NeLocusAndMaps variable {M P : α → Type*} [∀ a, Zero (N a)] [∀ a, Zero (M a)] [∀ a, Zero (P a)] theorem subset_mapRange_neLocus [∀ a, DecidableEq (N a)] [∀ a, DecidableEq (M a)] (f g : Π₀ a, N a) {F : ∀ a, N a → M a} (F0 : ∀ a, F a 0 = 0) : (f.mapRange F F0).neLocus (g.mapRange F F0) ⊆ f.neLocus g := fun a ↦ by simpa only [mem_neLocus, mapRange_apply, not_imp_not] using congr_arg (F a) theorem zipWith_neLocus_eq_left [∀ a, DecidableEq (N a)] [∀ a, DecidableEq (P a)] {F : ∀ a, M a → N a → P a} (F0 : ∀ a, F a 0 0 = 0) (f : Π₀ a, M a) (g₁ g₂ : Π₀ a, N a) (hF : ∀ a f, Function.Injective fun g ↦ F a f g) : (zipWith F F0 f g₁).neLocus (zipWith F F0 f g₂) = g₁.neLocus g₂ := by ext a simpa only [mem_neLocus] using (hF a _).ne_iff theorem zipWith_neLocus_eq_right [∀ a, DecidableEq (M a)] [∀ a, DecidableEq (P a)] {F : ∀ a, M a → N a → P a} (F0 : ∀ a, F a 0 0 = 0) (f₁ f₂ : Π₀ a, M a) (g : Π₀ a, N a) (hF : ∀ a g, Function.Injective fun f ↦ F a f g) : (zipWith F F0 f₁ g).neLocus (zipWith F F0 f₂ g) = f₁.neLocus f₂ := by ext a simpa only [mem_neLocus] using (hF a _).ne_iff theorem mapRange_neLocus_eq [∀ a, DecidableEq (N a)] [∀ a, DecidableEq (M a)] (f g : Π₀ a, N a) {F : ∀ a, N a → M a} (F0 : ∀ a, F a 0 = 0) (hF : ∀ a, Function.Injective (F a)) : (f.mapRange F F0).neLocus (g.mapRange F F0) = f.neLocus g := by ext a simpa only [mem_neLocus] using (hF a).ne_iff end NeLocusAndMaps variable [∀ a, DecidableEq (N a)] @[simp] theorem neLocus_add_left [∀ a, AddLeftCancelMonoid (N a)] (f g h : Π₀ a, N a) : (f + g).neLocus (f + h) = g.neLocus h := zipWith_neLocus_eq_left _ _ _ _ fun _a ↦ add_right_injective @[simp] theorem neLocus_add_right [∀ a, AddRightCancelMonoid (N a)] (f g h : Π₀ a, N a) : (f + h).neLocus (g + h) = f.neLocus g := zipWith_neLocus_eq_right _ _ _ _ fun _a ↦ add_left_injective section AddGroup variable [∀ a, AddGroup (N a)] (f f₁ f₂ g g₁ g₂ : Π₀ a, N a) @[simp] theorem neLocus_neg_neg : neLocus (-f) (-g) = f.neLocus g := mapRange_neLocus_eq _ _ (fun _a ↦ neg_zero) fun _a ↦ neg_injective theorem neLocus_neg : neLocus (-f) g = f.neLocus (-g) := by rw [← neLocus_neg_neg, neg_neg] theorem neLocus_eq_support_sub : f.neLocus g = (f - g).support := by rw [← @neLocus_add_right α N _ _ _ _ _ (-g), add_right_neg, neLocus_zero_right, sub_eq_add_neg] @[simp] theorem neLocus_sub_left : neLocus (f - g₁) (f - g₂) = neLocus g₁ g₂ := by simp only [sub_eq_add_neg, @neLocus_add_left α N _ _ _, neLocus_neg_neg] @[simp] theorem neLocus_sub_right : neLocus (f₁ - g) (f₂ - g) = neLocus f₁ f₂ := by simpa only [sub_eq_add_neg] using @neLocus_add_right α N _ _ _ _ _ _ @[simp] theorem neLocus_self_add_right : neLocus f (f + g) = g.support := by rw [← neLocus_zero_left, ← @neLocus_add_left α N _ _ _ f 0 g, add_zero] @[simp] theorem neLocus_self_add_left : neLocus (f + g) f = g.support := by rw [neLocus_comm, neLocus_self_add_right] @[simp] theorem neLocus_self_sub_right : neLocus f (f - g) = g.support := by rw [sub_eq_add_neg, neLocus_self_add_right, support_neg] @[simp] theorem neLocus_self_sub_left : neLocus (f - g) f = g.support := by rw [neLocus_comm, neLocus_self_sub_right] end AddGroup end DFinsupp
Data\DFinsupp\Notation.lean
/- Copyright (c) 2023 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import Mathlib.Data.DFinsupp.Basic import Mathlib.Data.Finsupp.Notation /-! # Notation for `DFinsupp` This file extends the existing `fun₀ | 3 => a | 7 => b` notation to work for `DFinsupp`, which desugars to `DFinsupp.update` and `DFinsupp.single`, in the same way that `{a, b}` desugars to `insert` and `singleton`. Note that this syntax is for `Finsupp` by default, but works for `DFinsupp` if the expected type is correct. -/ namespace DFinsupp open Lean open Lean.Parser open Lean.Parser.Term attribute [term_parser] Finsupp.stxSingle₀ Finsupp.stxUpdate₀ /-- `DFinsupp` elaborator for `single₀`. -/ @[term_elab Finsupp.stxSingle₀] def elabSingle₀ : Elab.Term.TermElab | `(term| single₀ $i $x) => fun ty? => do Elab.Term.tryPostponeIfNoneOrMVar ty? let .some ty := ty? | Elab.throwUnsupportedSyntax let_expr DFinsupp _ _ _ := ← Meta.withReducible (Meta.whnf ty) | Elab.throwUnsupportedSyntax Elab.Term.elabTerm (← `(DFinsupp.single $i $x)) ty? | _ => fun _ => Elab.throwUnsupportedSyntax /-- `DFinsupp` elaborator for `update₀`. -/ @[term_elab Finsupp.stxUpdate₀] def elabUpdate₀ : Elab.Term.TermElab | `(term| update₀ $f $i $x) => fun ty? => do Elab.Term.tryPostponeIfNoneOrMVar ty? let .some ty := ty? | Elab.throwUnsupportedSyntax let_expr DFinsupp _ _ _ := ← Meta.withReducible (Meta.whnf ty) | Elab.throwUnsupportedSyntax Elab.Term.elabTerm (← `(DFinsupp.update $i $f $x)) ty? | _ => fun _ => Elab.throwUnsupportedSyntax /-- Unexpander for the `fun₀ | i => x` notation. -/ @[app_unexpander Finsupp.single] def singleUnexpander : Lean.PrettyPrinter.Unexpander | `($_ $pat $val) => `(fun₀ | $pat => $val) | _ => throw () /-- Unexpander for the `fun₀ | i => x` notation. -/ @[app_unexpander Finsupp.update] def updateUnexpander : Lean.PrettyPrinter.Unexpander | `($_ $f $pat $val) => match f with | `(fun₀ $xs:matchAlt*) => `(fun₀ $xs:matchAlt* | $pat => $val) | _ => throw () | _ => throw () /-- Display `DFinsupp` using `fun₀` notation. -/ unsafe instance {α : Type*} {β : α → Type*} [Repr α] [∀ i, Repr (β i)] [∀ i, Zero (β i)] : Repr (Π₀ a, β a) where reprPrec f p := let vals := ((f.support'.unquot.val.map fun i => (repr i, repr (f i))).filter (fun p => toString p.2 != "0")).unquot let vals_dedup := vals.foldl (fun xs x => x :: xs.eraseP (toString ·.1 == toString x.1)) [] if vals.length = 0 then "0" else let ret := "fun₀" ++ Std.Format.join (vals_dedup.map <| fun a => f!" | " ++ a.1 ++ f!" => " ++ a.2) if p ≥ leadPrec then Format.paren ret else ret end DFinsupp
Data\DFinsupp\Order.lean
/- Copyright (c) 2021 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import Mathlib.Algebra.Order.Module.Defs import Mathlib.Data.DFinsupp.Basic /-! # Pointwise order on finitely supported dependent functions This file lifts order structures on the `α i` to `Π₀ i, α i`. ## Main declarations * `DFinsupp.orderEmbeddingToFun`: The order embedding from finitely supported dependent functions to functions. -/ open Finset variable {ι : Type*} {α : ι → Type*} namespace DFinsupp /-! ### Order structures -/ section Zero variable [∀ i, Zero (α i)] section LE variable [∀ i, LE (α i)] {f g : Π₀ i, α i} instance : LE (Π₀ i, α i) := ⟨fun f g ↦ ∀ i, f i ≤ g i⟩ lemma le_def : f ≤ g ↔ ∀ i, f i ≤ g i := Iff.rfl @[simp, norm_cast] lemma coe_le_coe : ⇑f ≤ g ↔ f ≤ g := Iff.rfl /-- The order on `DFinsupp`s over a partial order embeds into the order on functions -/ def orderEmbeddingToFun : (Π₀ i, α i) ↪o ∀ i, α i where toFun := DFunLike.coe inj' := DFunLike.coe_injective map_rel_iff' := by rfl @[simp, norm_cast] lemma coe_orderEmbeddingToFun : ⇑(orderEmbeddingToFun (α := α)) = DFunLike.coe := rfl -- Porting note: we added implicit arguments here in #3414. theorem orderEmbeddingToFun_apply {f : Π₀ i, α i} {i : ι} : (@orderEmbeddingToFun ι α _ _ f) i = f i := rfl end LE section Preorder variable [∀ i, Preorder (α i)] {f g : Π₀ i, α i} instance : Preorder (Π₀ i, α i) := { (inferInstance : LE (DFinsupp α)) with le_refl := fun f i ↦ le_rfl le_trans := fun f g h hfg hgh i ↦ (hfg i).trans (hgh i) } lemma lt_def : f < g ↔ f ≤ g ∧ ∃ i, f i < g i := Pi.lt_def @[simp, norm_cast] lemma coe_lt_coe : ⇑f < g ↔ f < g := Iff.rfl lemma coe_mono : Monotone ((⇑) : (Π₀ i, α i) → ∀ i, α i) := fun _ _ ↦ id lemma coe_strictMono : Monotone ((⇑) : (Π₀ i, α i) → ∀ i, α i) := fun _ _ ↦ id end Preorder instance [∀ i, PartialOrder (α i)] : PartialOrder (Π₀ i, α i) := { (inferInstance : Preorder (DFinsupp α)) with le_antisymm := fun _ _ hfg hgf ↦ ext fun i ↦ (hfg i).antisymm (hgf i) } instance [∀ i, SemilatticeInf (α i)] : SemilatticeInf (Π₀ i, α i) := { (inferInstance : PartialOrder (DFinsupp α)) with inf := zipWith (fun _ ↦ (· ⊓ ·)) fun _ ↦ inf_idem _ inf_le_left := fun _ _ _ ↦ inf_le_left inf_le_right := fun _ _ _ ↦ inf_le_right le_inf := fun _ _ _ hf hg i ↦ le_inf (hf i) (hg i) } @[simp, norm_cast] lemma coe_inf [∀ i, SemilatticeInf (α i)] (f g : Π₀ i, α i) : f ⊓ g = ⇑f ⊓ g := rfl theorem inf_apply [∀ i, SemilatticeInf (α i)] (f g : Π₀ i, α i) (i : ι) : (f ⊓ g) i = f i ⊓ g i := zipWith_apply _ _ _ _ _ instance [∀ i, SemilatticeSup (α i)] : SemilatticeSup (Π₀ i, α i) := { (inferInstance : PartialOrder (DFinsupp α)) with sup := zipWith (fun _ ↦ (· ⊔ ·)) fun _ ↦ sup_idem _ le_sup_left := fun _ _ _ ↦ le_sup_left le_sup_right := fun _ _ _ ↦ le_sup_right sup_le := fun _ _ _ hf hg i ↦ sup_le (hf i) (hg i) } @[simp, norm_cast] lemma coe_sup [∀ i, SemilatticeSup (α i)] (f g : Π₀ i, α i) : f ⊔ g = ⇑f ⊔ g := rfl theorem sup_apply [∀ i, SemilatticeSup (α i)] (f g : Π₀ i, α i) (i : ι) : (f ⊔ g) i = f i ⊔ g i := zipWith_apply _ _ _ _ _ section Lattice variable [∀ i, Lattice (α i)] (f g : Π₀ i, α i) instance lattice : Lattice (Π₀ i, α i) := { (inferInstance : SemilatticeInf (DFinsupp α)), (inferInstance : SemilatticeSup (DFinsupp α)) with } variable [DecidableEq ι] [∀ (i) (x : α i), Decidable (x ≠ 0)] theorem support_inf_union_support_sup : (f ⊓ g).support ∪ (f ⊔ g).support = f.support ∪ g.support := coe_injective <| compl_injective <| by ext; simp [inf_eq_and_sup_eq_iff] theorem support_sup_union_support_inf : (f ⊔ g).support ∪ (f ⊓ g).support = f.support ∪ g.support := (union_comm _ _).trans <| support_inf_union_support_sup _ _ end Lattice end Zero /-! ### Algebraic order structures -/ instance (α : ι → Type*) [∀ i, OrderedAddCommMonoid (α i)] : OrderedAddCommMonoid (Π₀ i, α i) := { (inferInstance : AddCommMonoid (DFinsupp α)), (inferInstance : PartialOrder (DFinsupp α)) with add_le_add_left := fun _ _ h c i ↦ add_le_add_left (h i) (c i) } instance (α : ι → Type*) [∀ i, OrderedCancelAddCommMonoid (α i)] : OrderedCancelAddCommMonoid (Π₀ i, α i) := { (inferInstance : OrderedAddCommMonoid (DFinsupp α)) with le_of_add_le_add_left := fun _ _ _ H i ↦ le_of_add_le_add_left (H i) } instance [∀ i, OrderedAddCommMonoid (α i)] [∀ i, ContravariantClass (α i) (α i) (· + ·) (· ≤ ·)] : ContravariantClass (Π₀ i, α i) (Π₀ i, α i) (· + ·) (· ≤ ·) := ⟨fun _ _ _ H i ↦ le_of_add_le_add_left (H i)⟩ section Module variable {α : Type*} {β : ι → Type*} [Semiring α] [Preorder α] [∀ i, AddCommMonoid (β i)] [∀ i, Preorder (β i)] [∀ i, Module α (β i)] instance instPosSMulMono [∀ i, PosSMulMono α (β i)] : PosSMulMono α (Π₀ i, β i) := PosSMulMono.lift _ coe_le_coe coe_smul instance instSMulPosMono [∀ i, SMulPosMono α (β i)] : SMulPosMono α (Π₀ i, β i) := SMulPosMono.lift _ coe_le_coe coe_smul coe_zero instance instPosSMulReflectLE [∀ i, PosSMulReflectLE α (β i)] : PosSMulReflectLE α (Π₀ i, β i) := PosSMulReflectLE.lift _ coe_le_coe coe_smul instance instSMulPosReflectLE [∀ i, SMulPosReflectLE α (β i)] : SMulPosReflectLE α (Π₀ i, β i) := SMulPosReflectLE.lift _ coe_le_coe coe_smul coe_zero end Module section Module variable {α : Type*} {β : ι → Type*} [Semiring α] [PartialOrder α] [∀ i, AddCommMonoid (β i)] [∀ i, PartialOrder (β i)] [∀ i, Module α (β i)] instance instPosSMulStrictMono [∀ i, PosSMulStrictMono α (β i)] : PosSMulStrictMono α (Π₀ i, β i) := PosSMulStrictMono.lift _ coe_le_coe coe_smul instance instSMulPosStrictMono [∀ i, SMulPosStrictMono α (β i)] : SMulPosStrictMono α (Π₀ i, β i) := SMulPosStrictMono.lift _ coe_le_coe coe_smul coe_zero -- Note: There is no interesting instance for `PosSMulReflectLT α (Π₀ i, β i)` that's not already -- implied by the other instances instance instSMulPosReflectLT [∀ i, SMulPosReflectLT α (β i)] : SMulPosReflectLT α (Π₀ i, β i) := SMulPosReflectLT.lift _ coe_le_coe coe_smul coe_zero end Module section CanonicallyOrderedAddCommMonoid -- Porting note: Split into 2 lines to satisfy the unusedVariables linter. variable (α) variable [∀ i, CanonicallyOrderedAddCommMonoid (α i)] instance : OrderBot (Π₀ i, α i) where bot := 0 bot_le := by simp only [le_def, coe_zero, Pi.zero_apply, imp_true_iff, zero_le] variable {α} protected theorem bot_eq_zero : (⊥ : Π₀ i, α i) = 0 := rfl @[simp] theorem add_eq_zero_iff (f g : Π₀ i, α i) : f + g = 0 ↔ f = 0 ∧ g = 0 := by simp [DFunLike.ext_iff, forall_and] section LE variable [DecidableEq ι] section variable [∀ (i) (x : α i), Decidable (x ≠ 0)] {f g : Π₀ i, α i} {s : Finset ι} theorem le_iff' (hf : f.support ⊆ s) : f ≤ g ↔ ∀ i ∈ s, f i ≤ g i := ⟨fun h s _ ↦ h s, fun h s ↦ if H : s ∈ f.support then h s (hf H) else (not_mem_support_iff.1 H).symm ▸ zero_le (g s)⟩ theorem le_iff : f ≤ g ↔ ∀ i ∈ f.support, f i ≤ g i := le_iff' <| Subset.refl _ lemma support_monotone : Monotone (support (ι := ι) (β := α)) := fun f g h a ha ↦ by rw [mem_support_iff, ← pos_iff_ne_zero] at ha ⊢; exact ha.trans_le (h _) lemma support_mono (hfg : f ≤ g) : f.support ⊆ g.support := support_monotone hfg variable (α) instance decidableLE [∀ i, DecidableRel (@LE.le (α i) _)] : DecidableRel (@LE.le (Π₀ i, α i) _) := fun _ _ ↦ decidable_of_iff _ le_iff.symm variable {α} end @[simp] theorem single_le_iff {f : Π₀ i, α i} {i : ι} {a : α i} : single i a ≤ f ↔ a ≤ f i := by classical exact (le_iff' support_single_subset).trans <| by simp end LE -- Porting note: Split into 2 lines to satisfy the unusedVariables linter. variable (α) variable [∀ i, Sub (α i)] [∀ i, OrderedSub (α i)] {f g : Π₀ i, α i} {i : ι} {a b : α i} /-- This is called `tsub` for truncated subtraction, to distinguish it with subtraction in an additive group. -/ instance tsub : Sub (Π₀ i, α i) := ⟨zipWith (fun _ m n ↦ m - n) fun _ ↦ tsub_self 0⟩ variable {α} theorem tsub_apply (f g : Π₀ i, α i) (i : ι) : (f - g) i = f i - g i := zipWith_apply _ _ _ _ _ @[simp, norm_cast] theorem coe_tsub (f g : Π₀ i, α i) : ⇑(f - g) = f - g := by ext i exact tsub_apply f g i variable (α) instance : OrderedSub (Π₀ i, α i) := ⟨fun _ _ _ ↦ forall_congr' fun _ ↦ tsub_le_iff_right⟩ instance : CanonicallyOrderedAddCommMonoid (Π₀ i, α i) := { (inferInstance : OrderBot (DFinsupp α)), (inferInstance : OrderedAddCommMonoid (DFinsupp α)) with exists_add_of_le := by intro f g h exists g - f ext i exact (add_tsub_cancel_of_le <| h i).symm le_self_add := fun _ _ _ ↦ le_self_add } variable {α} [DecidableEq ι] @[simp] theorem single_tsub : single i (a - b) = single i a - single i b := by ext j obtain rfl | h := eq_or_ne i j · rw [tsub_apply, single_eq_same, single_eq_same, single_eq_same] · rw [tsub_apply, single_eq_of_ne h, single_eq_of_ne h, single_eq_of_ne h, tsub_self] variable [∀ (i) (x : α i), Decidable (x ≠ 0)] theorem support_tsub : (f - g).support ⊆ f.support := by simp (config := { contextual := true }) only [subset_iff, tsub_eq_zero_iff_le, mem_support_iff, Ne, coe_tsub, Pi.sub_apply, not_imp_not, zero_le, imp_true_iff] theorem subset_support_tsub : f.support \ g.support ⊆ (f - g).support := by simp (config := { contextual := true }) [subset_iff] end CanonicallyOrderedAddCommMonoid section CanonicallyLinearOrderedAddCommMonoid variable [∀ i, CanonicallyLinearOrderedAddCommMonoid (α i)] [DecidableEq ι] {f g : Π₀ i, α i} @[simp] theorem support_inf : (f ⊓ g).support = f.support ∩ g.support := by ext simp only [inf_apply, mem_support_iff, Ne, Finset.mem_inter] simp only [inf_eq_min, ← nonpos_iff_eq_zero, min_le_iff, not_or] @[simp] theorem support_sup : (f ⊔ g).support = f.support ∪ g.support := by ext simp only [Finset.mem_union, mem_support_iff, sup_apply, Ne, ← bot_eq_zero] rw [_root_.sup_eq_bot_iff, not_and_or] nonrec theorem disjoint_iff : Disjoint f g ↔ Disjoint f.support g.support := by rw [disjoint_iff, disjoint_iff, DFinsupp.bot_eq_zero, ← DFinsupp.support_eq_empty, DFinsupp.support_inf] rfl end CanonicallyLinearOrderedAddCommMonoid end DFinsupp
Data\DFinsupp\WellFounded.lean
/- Copyright (c) 2022 Junyan Xu. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Junyan Xu -/ import Mathlib.Data.DFinsupp.Lex import Mathlib.Order.GameAdd import Mathlib.Order.Antisymmetrization import Mathlib.SetTheory.Ordinal.Basic import Mathlib.Tactic.AdaptationNote /-! # Well-foundedness of the lexicographic and product orders on `DFinsupp` and `Pi` The primary results are `DFinsupp.Lex.wellFounded` and the two variants that follow it, which essentially say that if `(· > ·)` is a well order on `ι`, `(· < ·)` is well-founded on each `α i`, and `0` is a bottom element in `α i`, then the lexicographic `(· < ·)` is well-founded on `Π₀ i, α i`. The proof is modelled on the proof of `WellFounded.cutExpand`. The results are used to prove `Pi.Lex.wellFounded` and two variants, which say that if `ι` is finite and equipped with a linear order and `(· < ·)` is well-founded on each `α i`, then the lexicographic `(· < ·)` is well-founded on `Π i, α i`, and the same is true for `Π₀ i, α i` (`DFinsupp.Lex.wellFounded_of_finite`), because `DFinsupp` is order-isomorphic to `pi` when `ι` is finite. Finally, we deduce `DFinsupp.wellFoundedLT`, `Pi.wellFoundedLT`, `DFinsupp.wellFoundedLT_of_finite` and variants, which concern the product order rather than the lexicographic one. An order on `ι` is not required in these results, but we deduce them from the well-foundedness of the lexicographic order by choosing a well order on `ι` so that the product order `(· < ·)` becomes a subrelation of the lexicographic `(· < ·)`. All results are provided in two forms whenever possible: a general form where the relations can be arbitrary (not the `(· < ·)` of a preorder, or not even transitive, etc.) and a specialized form provided as `WellFoundedLT` instances where the `(d)Finsupp/pi` type (or their `Lex` type synonyms) carries a natural `(· < ·)`. Notice that the definition of `DFinsupp.Lex` says that `x < y` according to `DFinsupp.Lex r s` iff there exists a coordinate `i : ι` such that `x i < y i` according to `s i`, and at all `r`-smaller coordinates `j` (i.e. satisfying `r j i`), `x` remains unchanged relative to `y`; in other words, coordinates `j` such that `¬ r j i` and `j ≠ i` are exactly where changes can happen arbitrarily. This explains the appearance of `rᶜ ⊓ (≠)` in `dfinsupp.acc_single` and `dfinsupp.well_founded`. When `r` is trichotomous (e.g. the `(· < ·)` of a linear order), `¬ r j i ∧ j ≠ i` implies `r i j`, so it suffices to require `r.swap` to be well-founded. -/ variable {ι : Type*} {α : ι → Type*} namespace DFinsupp open Relation Prod section Zero variable [∀ i, Zero (α i)] (r : ι → ι → Prop) (s : ∀ i, α i → α i → Prop) /-- This key lemma says that if a finitely supported dependent function `x₀` is obtained by merging two such functions `x₁` and `x₂`, and if we evolve `x₀` down the `DFinsupp.Lex` relation one step and get `x`, we can always evolve one of `x₁` and `x₂` down the `DFinsupp.Lex` relation one step while keeping the other unchanged, and merge them back (possibly in a different way) to get back `x`. In other words, the two parts evolve essentially independently under `DFinsupp.Lex`. This is used to show that a function `x` is accessible if `DFinsupp.single i (x i)` is accessible for each `i` in the (finite) support of `x` (`DFinsupp.Lex.acc_of_single`). -/ theorem lex_fibration [∀ (i) (s : Set ι), Decidable (i ∈ s)] : Fibration (InvImage (GameAdd (DFinsupp.Lex r s) (DFinsupp.Lex r s)) snd) (DFinsupp.Lex r s) fun x => piecewise x.2.1 x.2.2 x.1 := by rintro ⟨p, x₁, x₂⟩ x ⟨i, hr, hs⟩ simp_rw [piecewise_apply] at hs hr split_ifs at hs with hp · refine ⟨⟨{ j | r j i → j ∈ p }, piecewise x₁ x { j | r j i }, x₂⟩, .fst ⟨i, fun j hj ↦ ?_, ?_⟩, ?_⟩ <;> simp only [piecewise_apply, Set.mem_setOf_eq] · simp only [if_pos hj] · split_ifs with hi · rwa [hr i hi, if_pos hp] at hs · assumption · ext1 j simp only [piecewise_apply, Set.mem_setOf_eq] split_ifs with h₁ h₂ <;> try rfl · rw [hr j h₂, if_pos (h₁ h₂)] · rw [Classical.not_imp] at h₁ rw [hr j h₁.1, if_neg h₁.2] · refine ⟨⟨{ j | r j i ∧ j ∈ p }, x₁, piecewise x₂ x { j | r j i }⟩, .snd ⟨i, fun j hj ↦ ?_, ?_⟩, ?_⟩ <;> simp only [piecewise_apply, Set.mem_setOf_eq] · exact if_pos hj · split_ifs with hi · rwa [hr i hi, if_neg hp] at hs · assumption · ext1 j simp only [piecewise_apply, Set.mem_setOf_eq] split_ifs with h₁ h₂ <;> try rfl · rw [hr j h₁.1, if_pos h₁.2] · rw [hr j h₂, if_neg] simpa [h₂] using h₁ variable {r s} theorem Lex.acc_of_single_erase [DecidableEq ι] {x : Π₀ i, α i} (i : ι) (hs : Acc (DFinsupp.Lex r s) <| single i (x i)) (hu : Acc (DFinsupp.Lex r s) <| x.erase i) : Acc (DFinsupp.Lex r s) x := by classical convert ← @Acc.of_fibration _ _ _ _ _ (lex_fibration r s) ⟨{i}, _⟩ (InvImage.accessible snd <| hs.prod_gameAdd hu) convert piecewise_single_erase x i theorem Lex.acc_zero (hbot : ∀ ⦃i a⦄, ¬s i a 0) : Acc (DFinsupp.Lex r s) 0 := Acc.intro 0 fun _ ⟨_, _, h⟩ => (hbot h).elim theorem Lex.acc_of_single (hbot : ∀ ⦃i a⦄, ¬s i a 0) [DecidableEq ι] [∀ (i) (x : α i), Decidable (x ≠ 0)] (x : Π₀ i, α i) : (∀ i ∈ x.support, Acc (DFinsupp.Lex r s) <| single i (x i)) → Acc (DFinsupp.Lex r s) x := by generalize ht : x.support = t; revert x classical induction' t using Finset.induction with b t hb ih · intro x ht rw [support_eq_empty.1 ht] exact fun _ => Lex.acc_zero hbot refine fun x ht h => Lex.acc_of_single_erase b (h b <| t.mem_insert_self b) ?_ refine ih _ (by rw [support_erase, ht, Finset.erase_insert hb]) fun a ha => ?_ rw [erase_ne (ha.ne_of_not_mem hb)] exact h a (Finset.mem_insert_of_mem ha) theorem Lex.acc_single (hbot : ∀ ⦃i a⦄, ¬s i a 0) (hs : ∀ i, WellFounded (s i)) [DecidableEq ι] {i : ι} (hi : Acc (rᶜ ⊓ (· ≠ ·)) i) : ∀ a, Acc (DFinsupp.Lex r s) (single i a) := by induction' hi with i _ ih refine fun a => WellFounded.induction (hs i) (C := fun x ↦ Acc (DFinsupp.Lex r s) (single i x)) a fun a ha ↦ ?_ refine Acc.intro _ fun x ↦ ?_ rintro ⟨k, hr, hs⟩ rw [single_apply] at hs split_ifs at hs with hik swap · exact (hbot hs).elim subst hik classical refine Lex.acc_of_single hbot x fun j hj ↦ ?_ obtain rfl | hij := eq_or_ne i j · exact ha _ hs by_cases h : r j i · rw [hr j h, single_eq_of_ne hij, single_zero] exact Lex.acc_zero hbot · exact ih _ ⟨h, hij.symm⟩ _ theorem Lex.acc (hbot : ∀ ⦃i a⦄, ¬s i a 0) (hs : ∀ i, WellFounded (s i)) [DecidableEq ι] [∀ (i) (x : α i), Decidable (x ≠ 0)] (x : Π₀ i, α i) (h : ∀ i ∈ x.support, Acc (rᶜ ⊓ (· ≠ ·)) i) : Acc (DFinsupp.Lex r s) x := Lex.acc_of_single hbot x fun i hi => Lex.acc_single hbot hs (h i hi) _ theorem Lex.wellFounded (hbot : ∀ ⦃i a⦄, ¬s i a 0) (hs : ∀ i, WellFounded (s i)) (hr : WellFounded <| rᶜ ⊓ (· ≠ ·)) : WellFounded (DFinsupp.Lex r s) := ⟨fun x => by classical exact Lex.acc hbot hs x fun i _ => hr.apply i⟩ theorem Lex.wellFounded' (hbot : ∀ ⦃i a⦄, ¬s i a 0) (hs : ∀ i, WellFounded (s i)) [IsTrichotomous ι r] (hr : WellFounded (Function.swap r)) : WellFounded (DFinsupp.Lex r s) := Lex.wellFounded hbot hs <| Subrelation.wf (fun {i j} h => ((@IsTrichotomous.trichotomous ι r _ i j).resolve_left h.1).resolve_left h.2) hr end Zero instance Lex.wellFoundedLT [LT ι] [IsTrichotomous ι (· < ·)] [hι : WellFoundedGT ι] [∀ i, CanonicallyOrderedAddCommMonoid (α i)] [hα : ∀ i, WellFoundedLT (α i)] : WellFoundedLT (Lex (Π₀ i, α i)) := ⟨Lex.wellFounded' (fun _ a => (zero_le a).not_lt) (fun i => (hα i).wf) hι.wf⟩ end DFinsupp open DFinsupp variable (r : ι → ι → Prop) {s : ∀ i, α i → α i → Prop} theorem Pi.Lex.wellFounded [IsStrictTotalOrder ι r] [Finite ι] (hs : ∀ i, WellFounded (s i)) : WellFounded (Pi.Lex r (fun {i} ↦ s i)) := by obtain h | ⟨⟨x⟩⟩ := isEmpty_or_nonempty (∀ i, α i) · convert emptyWf.wf letI : ∀ i, Zero (α i) := fun i => ⟨(hs i).min ⊤ ⟨x i, trivial⟩⟩ haveI := IsTrans.swap r; haveI := IsIrrefl.swap r; haveI := Fintype.ofFinite ι refine InvImage.wf equivFunOnFintype.symm (Lex.wellFounded' (fun i a => ?_) hs ?_) exacts [(hs i).not_lt_min ⊤ _ trivial, Finite.wellFounded_of_trans_of_irrefl (Function.swap r)] instance Pi.Lex.wellFoundedLT [LinearOrder ι] [Finite ι] [∀ i, LT (α i)] [hwf : ∀ i, WellFoundedLT (α i)] : WellFoundedLT (Lex (∀ i, α i)) := ⟨Pi.Lex.wellFounded (· < ·) fun i => (hwf i).1⟩ instance Function.Lex.wellFoundedLT {α} [LinearOrder ι] [Finite ι] [LT α] [WellFoundedLT α] : WellFoundedLT (Lex (ι → α)) := Pi.Lex.wellFoundedLT theorem DFinsupp.Lex.wellFounded_of_finite [IsStrictTotalOrder ι r] [Finite ι] [∀ i, Zero (α i)] (hs : ∀ i, WellFounded (s i)) : WellFounded (DFinsupp.Lex r s) := have := Fintype.ofFinite ι InvImage.wf equivFunOnFintype (Pi.Lex.wellFounded r hs) instance DFinsupp.Lex.wellFoundedLT_of_finite [LinearOrder ι] [Finite ι] [∀ i, Zero (α i)] [∀ i, LT (α i)] [hwf : ∀ i, WellFoundedLT (α i)] : WellFoundedLT (Lex (Π₀ i, α i)) := ⟨DFinsupp.Lex.wellFounded_of_finite (· < ·) fun i => (hwf i).1⟩ protected theorem DFinsupp.wellFoundedLT [∀ i, Zero (α i)] [∀ i, Preorder (α i)] [∀ i, WellFoundedLT (α i)] (hbot : ∀ ⦃i⦄ ⦃a : α i⦄, ¬a < 0) : WellFoundedLT (Π₀ i, α i) := ⟨by set β := fun i ↦ Antisymmetrization (α i) (· ≤ ·) set e : (i : ι) → α i → β i := fun i ↦ toAntisymmetrization (· ≤ ·) let _ : ∀ i, Zero (β i) := fun i ↦ ⟨e i 0⟩ have : WellFounded (DFinsupp.Lex (Function.swap <| @WellOrderingRel ι) (fun _ ↦ (· < ·) : (i : ι) → β i → β i → Prop)) := by have := IsTrichotomous.swap (@WellOrderingRel ι) refine Lex.wellFounded' ?_ (fun i ↦ IsWellFounded.wf) ?_ · rintro i ⟨a⟩ apply hbot · #adaptation_note /-- nightly-2024-03-16: simp was simp (config := { unfoldPartialApp := true }) only [Function.swap] -/ simp only [Function.swap_def] exact IsWellFounded.wf refine Subrelation.wf (fun h => ?_) <| InvImage.wf (mapRange (fun i ↦ e i) fun _ ↦ rfl) this have := IsStrictOrder.swap (@WellOrderingRel ι) obtain ⟨i, he, hl⟩ := lex_lt_of_lt_of_preorder (Function.swap WellOrderingRel) h exact ⟨i, fun j hj ↦ Quot.sound (he j hj), hl⟩⟩ instance DFinsupp.wellFoundedLT' [∀ i, CanonicallyOrderedAddCommMonoid (α i)] [∀ i, WellFoundedLT (α i)] : WellFoundedLT (Π₀ i, α i) := DFinsupp.wellFoundedLT fun _i a => (zero_le a).not_lt instance Pi.wellFoundedLT [Finite ι] [∀ i, Preorder (α i)] [hw : ∀ i, WellFoundedLT (α i)] : WellFoundedLT (∀ i, α i) := ⟨by obtain h | ⟨⟨x⟩⟩ := isEmpty_or_nonempty (∀ i, α i) · convert emptyWf.wf letI : ∀ i, Zero (α i) := fun i => ⟨(hw i).wf.min ⊤ ⟨x i, trivial⟩⟩ haveI := Fintype.ofFinite ι refine InvImage.wf equivFunOnFintype.symm (DFinsupp.wellFoundedLT fun i a => ?_).wf exact (hw i).wf.not_lt_min ⊤ _ trivial⟩ instance Function.wellFoundedLT {α} [Finite ι] [Preorder α] [WellFoundedLT α] : WellFoundedLT (ι → α) := Pi.wellFoundedLT instance DFinsupp.wellFoundedLT_of_finite [Finite ι] [∀ i, Zero (α i)] [∀ i, Preorder (α i)] [∀ i, WellFoundedLT (α i)] : WellFoundedLT (Π₀ i, α i) := have := Fintype.ofFinite ι ⟨InvImage.wf equivFunOnFintype Pi.wellFoundedLT.wf⟩
Data\DList\Basic.lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import Mathlib.Data.DList.Defs import Mathlib.Tactic.TypeStar /-! # Difference list This file provides a few results about `DList`, which is defined in `Batteries`. A difference list is a function that, given a list, returns the original content of the difference list prepended to the given list. It is useful to represent elements of a given type as `a₁ + ... + aₙ` where `+ : α → α → α` is any operation, without actually computing. This structure supports `O(1)` `append` and `push` operations on lists, making it useful for append-heavy uses such as logging and pretty printing. -/ namespace Batteries /-- Concatenates a list of difference lists to form a single difference list. Similar to `List.join`. -/ def DList.join {α : Type*} : List (DList α) → DList α | [] => DList.empty | x :: xs => x ++ DList.join xs @[simp] theorem DList_singleton {α : Type*} {a : α} : DList.singleton a = DList.lazy_ofList [a] := rfl @[simp] theorem DList_lazy {α : Type*} {l : List α} : DList.lazy_ofList l = Batteries.DList.ofList l := rfl end Batteries
Data\DList\Defs.lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Batteries.Data.DList import Mathlib.Tactic.Cases /-! # Difference list This file provides a few results about `DList`, which is defined in `Batteries`. A difference list is a function that, given a list, returns the original content of the difference list prepended to the given list. It is useful to represent elements of a given type as `a₁ + ... + aₙ` where `+ : α → α → α` is any operation, without actually computing. This structure supports `O(1)` `append` and `push` operations on lists, making it useful for append-heavy uses such as logging and pretty printing. -/ universe u namespace Batteries.DList open Function variable {α : Type u} /-- Convert a lazily-evaluated `List` to a `DList` -/ def lazy_ofList (l : Thunk (List α)) : DList α := ⟨fun xs => l.get ++ xs, fun t => by simp⟩ attribute [local simp] Function.comp attribute [local simp] ofList toList empty singleton cons push append theorem toList_ofList (l : List α) : DList.toList (DList.ofList l) = l := by cases l; rfl; simp only [DList.toList, DList.ofList, List.cons_append, List.append_nil] theorem ofList_toList (l : DList α) : DList.ofList (DList.toList l) = l := by cases' l with app inv simp only [ofList, toList, mk.injEq] funext x rw [(inv x)] theorem toList_empty : toList (@empty α) = [] := by simp theorem toList_singleton (x : α) : toList (singleton x) = [x] := by simp theorem toList_append (l₁ l₂ : DList α) : toList (l₁ ++ l₂) = toList l₁ ++ toList l₂ := show toList (DList.append l₁ l₂) = toList l₁ ++ toList l₂ by cases' l₁ with _ l₁_invariant; cases' l₂; simp; rw [l₁_invariant] theorem toList_cons (x : α) (l : DList α) : toList (cons x l) = x :: toList l := by cases l; simp theorem toList_push (x : α) (l : DList α) : toList (push l x) = toList l ++ [x] := by cases' l with _ l_invariant; simp; rw [l_invariant] end Batteries.DList
Data\DList\Instances.lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import Mathlib.Data.DList.Defs import Mathlib.Control.Traversable.Equiv import Mathlib.Control.Traversable.Instances /-! # Traversable instance for DLists This file provides the equivalence between `List α` and `DList α` and the traversable instance for `DList`. -/ open Function Equiv namespace Batteries variable (α : Type*) /-- The natural equivalence between lists and difference lists, using `DList.ofList` and `DList.toList`. -/ def DList.listEquivDList : List α ≃ DList α where toFun := DList.ofList invFun := DList.toList left_inv _ := DList.toList_ofList _ right_inv _ := DList.ofList_toList _ instance : Traversable DList := Equiv.traversable DList.listEquivDList instance : LawfulTraversable DList := Equiv.isLawfulTraversable DList.listEquivDList instance {α} : Inhabited (DList α) := ⟨DList.empty⟩ end Batteries
Data\ENat\Basic.lean
/- Copyright (c) 2022 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import Mathlib.Data.Nat.SuccPred import Mathlib.Algebra.CharZero.Lemmas import Mathlib.Algebra.Order.Sub.WithTop import Mathlib.Algebra.Order.Ring.WithTop import Mathlib.Data.Nat.Cast.Order.Basic /-! # Definition and basic properties of extended natural numbers In this file we define `ENat` (notation: `ℕ∞`) to be `WithTop ℕ` and prove some basic lemmas about this type. ## Implementation details There are two natural coercions from `ℕ` to `WithTop ℕ = ENat`: `WithTop.some` and `Nat.cast`. In Lean 3, this difference was hidden in typeclass instances. Since these instances were definitionally equal, we did not duplicate generic lemmas about `WithTop α` and `WithTop.some` coercion for `ENat` and `Nat.cast` coercion. If you need to apply a lemma about `WithTop`, you may either rewrite back and forth using `ENat.some_eq_coe`, or restate the lemma for `ENat`. -/ /-- Extended natural numbers `ℕ∞ = WithTop ℕ`. -/ def ENat : Type := WithTop ℕ deriving Zero, -- AddCommMonoidWithOne, CanonicallyOrderedCommSemiring, Nontrivial, LinearOrder, Bot, Top, CanonicallyLinearOrderedAddCommMonoid, Sub, LinearOrderedAddCommMonoidWithTop, WellFoundedRelation, Inhabited -- OrderBot, OrderTop, OrderedSub, SuccOrder, WellFoundedLt, CharZero -- Porting Note: In `Data.Nat.ENatPart` proofs timed out when having -- the `deriving AddCommMonoidWithOne`, and it seems to work without. /-- Extended natural numbers `ℕ∞ = WithTop ℕ`. -/ notation "ℕ∞" => ENat namespace ENat -- Porting note: instances that derive failed to find instance : OrderBot ℕ∞ := WithTop.orderBot instance : OrderTop ℕ∞ := WithTop.orderTop instance : OrderedSub ℕ∞ := inferInstanceAs (OrderedSub (WithTop ℕ)) instance : SuccOrder ℕ∞ := inferInstanceAs (SuccOrder (WithTop ℕ)) instance : WellFoundedLT ℕ∞ := inferInstanceAs (WellFoundedLT (WithTop ℕ)) instance : CharZero ℕ∞ := inferInstanceAs (CharZero (WithTop ℕ)) instance : IsWellOrder ℕ∞ (· < ·) where variable {m n : ℕ∞} /-- Lemmas about `WithTop` expect (and can output) `WithTop.some` but the normal form for coercion `ℕ → ℕ∞` is `Nat.cast`. -/ @[simp] theorem some_eq_coe : (WithTop.some : ℕ → ℕ∞) = Nat.cast := rfl -- Porting note: `simp` and `norm_cast` can prove it --@[simp, norm_cast] theorem coe_zero : ((0 : ℕ) : ℕ∞) = 0 := rfl -- Porting note: `simp` and `norm_cast` can prove it --@[simp, norm_cast] theorem coe_one : ((1 : ℕ) : ℕ∞) = 1 := rfl -- Porting note: `simp` and `norm_cast` can prove it --@[simp, norm_cast] theorem coe_add (m n : ℕ) : ↑(m + n) = (m + n : ℕ∞) := rfl @[simp, norm_cast] theorem coe_sub (m n : ℕ) : ↑(m - n) = (m - n : ℕ∞) := rfl @[simp] lemma coe_mul (m n : ℕ) : ↑(m * n) = (m * n : ℕ∞) := rfl @[simp] theorem mul_top (hm : m ≠ 0) : m * ⊤ = ⊤ := WithTop.mul_top hm @[simp] theorem top_mul (hm : m ≠ 0) : ⊤ * m = ⊤ := WithTop.top_mul hm theorem top_pow {n : ℕ} (n_pos : 0 < n) : (⊤ : ℕ∞) ^ n = ⊤ := WithTop.top_pow n_pos instance canLift : CanLift ℕ∞ ℕ (↑) (· ≠ ⊤) := WithTop.canLift instance : WellFoundedRelation ℕ∞ where rel := (· < ·) wf := IsWellFounded.wf /-- Conversion of `ℕ∞` to `ℕ` sending `∞` to `0`. -/ def toNat : ℕ∞ → ℕ := WithTop.untop' 0 /-- Homomorphism from `ℕ∞` to `ℕ` sending `∞` to `0`. -/ def toNatHom : MonoidWithZeroHom ℕ∞ ℕ where toFun := toNat map_one' := rfl map_zero' := rfl map_mul' := WithTop.untop'_zero_mul @[simp, norm_cast] lemma coe_toNatHom : toNatHom = toNat := rfl lemma toNatHom_apply (n : ℕ) : toNatHom n = toNat n := rfl @[simp] theorem toNat_coe (n : ℕ) : toNat n = n := rfl -- See note [no_index around OfNat.ofNat] @[simp] theorem toNat_ofNat (n : ℕ) [n.AtLeastTwo] : toNat (no_index (OfNat.ofNat n)) = n := rfl @[simp] theorem toNat_top : toNat ⊤ = 0 := rfl @[simp] theorem toNat_eq_zero : toNat n = 0 ↔ n = 0 ∨ n = ⊤ := WithTop.untop'_eq_self_iff -- Porting note (#11445): new definition copied from `WithTop` /-- Recursor for `ENat` using the preferred forms `⊤` and `↑a`. -/ @[elab_as_elim, induction_eliminator, cases_eliminator] def recTopCoe {C : ℕ∞ → Sort*} (top : C ⊤) (coe : ∀ a : ℕ, C a) : ∀ n : ℕ∞, C n | none => top | Option.some a => coe a @[simp] theorem recTopCoe_top {C : ℕ∞ → Sort*} (d : C ⊤) (f : ∀ a : ℕ, C a) : @recTopCoe C d f ⊤ = d := rfl @[simp] theorem recTopCoe_coe {C : ℕ∞ → Sort*} (d : C ⊤) (f : ∀ a : ℕ, C a) (x : ℕ) : @recTopCoe C d f ↑x = f x := rfl @[simp] theorem recTopCoe_zero {C : ℕ∞ → Sort*} (d : C ⊤) (f : ∀ a : ℕ, C a) : @recTopCoe C d f 0 = f 0 := rfl @[simp] theorem recTopCoe_one {C : ℕ∞ → Sort*} (d : C ⊤) (f : ∀ a : ℕ, C a) : @recTopCoe C d f 1 = f 1 := rfl -- See note [no_index around OfNat.ofNat] @[simp] theorem recTopCoe_ofNat {C : ℕ∞ → Sort*} (d : C ⊤) (f : ∀ a : ℕ, C a) (x : ℕ) [x.AtLeastTwo] : @recTopCoe C d f (no_index (OfNat.ofNat x)) = f (OfNat.ofNat x) := rfl @[simp] theorem top_ne_coe (a : ℕ) : ⊤ ≠ (a : ℕ∞) := nofun -- See note [no_index around OfNat.ofNat] @[simp] theorem top_ne_ofNat (a : ℕ) [a.AtLeastTwo] : ⊤ ≠ (no_index (OfNat.ofNat a : ℕ∞)) := nofun @[simp] lemma top_ne_zero : (⊤ : ℕ∞) ≠ 0 := nofun @[simp] lemma top_ne_one : (⊤ : ℕ∞) ≠ 1 := nofun @[simp] theorem coe_ne_top (a : ℕ) : (a : ℕ∞) ≠ ⊤ := nofun -- See note [no_index around OfNat.ofNat] @[simp] theorem ofNat_ne_top (a : ℕ) [a.AtLeastTwo] : (no_index (OfNat.ofNat a : ℕ∞)) ≠ ⊤ := nofun @[simp] lemma zero_ne_top : 0 ≠ (⊤ : ℕ∞) := nofun @[simp] lemma one_ne_top : 1 ≠ (⊤ : ℕ∞) := nofun @[simp] theorem top_sub_coe (a : ℕ) : (⊤ : ℕ∞) - a = ⊤ := WithTop.top_sub_coe @[simp] theorem top_sub_one : (⊤ : ℕ∞) - 1 = ⊤ := top_sub_coe 1 -- See note [no_index around OfNat.ofNat] @[simp] theorem top_sub_ofNat (a : ℕ) [a.AtLeastTwo] : (⊤ : ℕ∞) - (no_index (OfNat.ofNat a)) = ⊤ := top_sub_coe a @[simp] theorem zero_lt_top : (0 : ℕ∞) < ⊤ := WithTop.zero_lt_top theorem sub_top (a : ℕ∞) : a - ⊤ = 0 := WithTop.sub_top @[simp] theorem coe_toNat_eq_self : ENat.toNat n = n ↔ n ≠ ⊤ := ENat.recTopCoe (by decide) (fun _ => by simp [toNat_coe]) n alias ⟨_, coe_toNat⟩ := coe_toNat_eq_self theorem coe_toNat_le_self (n : ℕ∞) : ↑(toNat n) ≤ n := ENat.recTopCoe le_top (fun _ => le_rfl) n theorem toNat_add {m n : ℕ∞} (hm : m ≠ ⊤) (hn : n ≠ ⊤) : toNat (m + n) = toNat m + toNat n := by lift m to ℕ using hm lift n to ℕ using hn rfl theorem toNat_sub {n : ℕ∞} (hn : n ≠ ⊤) (m : ℕ∞) : toNat (m - n) = toNat m - toNat n := by lift n to ℕ using hn induction m · rw [top_sub_coe, toNat_top, zero_tsub] · rw [← coe_sub, toNat_coe, toNat_coe, toNat_coe] theorem toNat_eq_iff {m : ℕ∞} {n : ℕ} (hn : n ≠ 0) : toNat m = n ↔ m = n := by induction m <;> simp [hn.symm] lemma toNat_le_of_le_coe {m : ℕ∞} {n : ℕ} (h : m ≤ n) : toNat m ≤ n := by lift m to ℕ using ne_top_of_le_ne_top (coe_ne_top n) h simpa using h @[gcongr] lemma toNat_le_toNat {m n : ℕ∞} (h : m ≤ n) (hn : n ≠ ⊤) : toNat m ≤ toNat n := toNat_le_of_le_coe <| h.trans_eq (coe_toNat hn).symm @[simp] theorem succ_def (m : ℕ∞) : Order.succ m = m + 1 := by cases m <;> rfl theorem add_one_le_of_lt (h : m < n) : m + 1 ≤ n := m.succ_def ▸ Order.succ_le_of_lt h theorem add_one_le_iff (hm : m ≠ ⊤) : m + 1 ≤ n ↔ m < n := m.succ_def ▸ (Order.succ_le_iff_of_not_isMax <| by rwa [isMax_iff_eq_top]) theorem one_le_iff_pos : 1 ≤ n ↔ 0 < n := add_one_le_iff WithTop.zero_ne_top theorem one_le_iff_ne_zero : 1 ≤ n ↔ n ≠ 0 := one_le_iff_pos.trans pos_iff_ne_zero lemma lt_one_iff_eq_zero : n < 1 ↔ n = 0 := not_le.symm.trans one_le_iff_ne_zero.not_left theorem le_of_lt_add_one (h : m < n + 1) : m ≤ n := Order.le_of_lt_succ <| n.succ_def.symm ▸ h theorem lt_add_one_iff (hm : n ≠ ⊤) : m < n + 1 ↔ m ≤ n := n.succ_def ▸ Order.lt_succ_iff_of_not_isMax (not_isMax_iff_ne_top.mpr hm) theorem le_coe_iff {n : ℕ∞} {k : ℕ} : n ≤ ↑k ↔ ∃ (n₀ : ℕ), n = n₀ ∧ n₀ ≤ k := WithTop.le_coe_iff @[simp] lemma not_lt_zero (n : ℕ∞) : ¬ n < 0 := by cases n <;> simp @[simp] lemma coe_lt_top (n : ℕ) : (n : ℕ∞) < ⊤ := WithTop.coe_lt_top n @[elab_as_elim] theorem nat_induction {P : ℕ∞ → Prop} (a : ℕ∞) (h0 : P 0) (hsuc : ∀ n : ℕ, P n → P n.succ) (htop : (∀ n : ℕ, P n) → P ⊤) : P a := by have A : ∀ n : ℕ, P n := fun n => Nat.recOn n h0 hsuc cases a · exact htop A · exact A _ end ENat
Data\ENat\Lattice.lean
/- Copyright (c) 2022 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import Mathlib.Data.Nat.Lattice import Mathlib.Data.ENat.Basic /-! # Extended natural numbers form a complete linear order This instance is not in `Data.ENat.Basic` to avoid dependency on `Finset`s. We also restate some lemmas about `WithTop` for `ENat` to have versions that use `Nat.cast` instead of `WithTop.some`. -/ open Set -- Porting note: was `deriving instance` but "default handlers have not been implemented yet" -- Porting note: `noncomputable` through 'Nat.instConditionallyCompleteLinearOrderBotNat' noncomputable instance : CompleteLinearOrder ENat := inferInstanceAs (CompleteLinearOrder (WithTop ℕ)) noncomputable instance : CompleteLinearOrder (WithBot ENat) := inferInstanceAs (CompleteLinearOrder (WithBot (WithTop ℕ))) namespace ENat variable {ι : Sort*} {f : ι → ℕ} {s : Set ℕ} lemma iSup_coe_eq_top : ⨆ i, (f i : ℕ∞) = ⊤ ↔ ¬ BddAbove (range f) := WithTop.iSup_coe_eq_top lemma iSup_coe_ne_top : ⨆ i, (f i : ℕ∞) ≠ ⊤ ↔ BddAbove (range f) := iSup_coe_eq_top.not_left lemma iSup_coe_lt_top : ⨆ i, (f i : ℕ∞) < ⊤ ↔ BddAbove (range f) := WithTop.iSup_coe_lt_top lemma iInf_coe_eq_top : ⨅ i, (f i : ℕ∞) = ⊤ ↔ IsEmpty ι := WithTop.iInf_coe_eq_top lemma iInf_coe_ne_top : ⨅ i, (f i : ℕ∞) ≠ ⊤ ↔ Nonempty ι := by rw [Ne, iInf_coe_eq_top, not_isEmpty_iff] lemma iInf_coe_lt_top : ⨅ i, (f i : ℕ∞) < ⊤ ↔ Nonempty ι := WithTop.iInf_coe_lt_top lemma coe_sSup : BddAbove s → ↑(sSup s) = ⨆ a ∈ s, (a : ℕ∞) := WithTop.coe_sSup lemma coe_sInf (hs : s.Nonempty) : ↑(sInf s) = ⨅ a ∈ s, (a : ℕ∞) := WithTop.coe_sInf hs (OrderBot.bddBelow s) lemma coe_iSup : BddAbove (range f) → ↑(⨆ i, f i) = ⨆ i, (f i : ℕ∞) := WithTop.coe_iSup _ @[norm_cast] lemma coe_iInf [Nonempty ι] : ↑(⨅ i, f i) = ⨅ i, (f i : ℕ∞) := WithTop.coe_iInf (OrderBot.bddBelow _) @[simp] lemma iInf_eq_top_of_isEmpty [IsEmpty ι] : ⨅ i, (f i : ℕ∞) = ⊤ := iInf_coe_eq_top.mpr ‹_› lemma iInf_toNat : (⨅ i, (f i : ℕ∞)).toNat = ⨅ i, f i := by cases isEmpty_or_nonempty ι · simp · norm_cast lemma iInf_eq_zero : ⨅ i, (f i : ℕ∞) = 0 ↔ ∃ i, f i = 0 := by cases isEmpty_or_nonempty ι · simp · norm_cast rw [iInf, Nat.sInf_eq_zero] exact ⟨fun h ↦ by simp_all, .inl⟩ variable {f : ι → ℕ∞} {s : Set ℕ∞} lemma sSup_eq_zero : sSup s = 0 ↔ ∀ a ∈ s, a = 0 := sSup_eq_bot lemma sInf_eq_zero : sInf s = 0 ↔ 0 ∈ s := by rw [← lt_one_iff_eq_zero] simp only [sInf_lt_iff, lt_one_iff_eq_zero, exists_eq_right] lemma sSup_eq_zero' : sSup s = 0 ↔ s = ∅ ∨ s = {0} := sSup_eq_bot' lemma iSup_eq_zero : iSup f = 0 ↔ ∀ i, f i = 0 := iSup_eq_bot lemma sSup_eq_top_of_infinite (h : s.Infinite) : sSup s = ⊤ := by apply (sSup_eq_top ..).mpr intro x hx cases x with | top => simp at hx | coe x => contrapose! h simp only [not_infinite] apply Finite.subset <| Finite.Set.finite_image {n : ℕ | n ≤ x} (fun (n : ℕ) => (n : ℕ∞)) intro y hy specialize h y hy have hxt : y < ⊤ := lt_of_le_of_lt h hx use y.toNat simp [toNat_le_of_le_coe h, LT.lt.ne_top hxt] lemma finite_of_sSup_lt_top (h : sSup s < ⊤) : s.Finite := by contrapose! h simp only [top_le_iff] exact sSup_eq_top_of_infinite h lemma sSup_mem_of_Nonempty_of_lt_top [Nonempty s] (hs' : sSup s < ⊤) : sSup s ∈ s := Nonempty.csSup_mem nonempty_of_nonempty_subtype (finite_of_sSup_lt_top hs') end ENat
Data\ENNReal\Basic.lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Yury Kudryashov -/ import Mathlib.Algebra.Order.Ring.WithTop import Mathlib.Algebra.Order.Sub.WithTop import Mathlib.Data.NNReal.Basic import Mathlib.Order.Interval.Set.WithBotTop /-! # Extended non-negative reals We define `ENNReal = ℝ≥0∞ := WithTop ℝ≥0` to be the type of extended nonnegative real numbers, i.e., the interval `[0, +∞]`. This type is used as the codomain of a `MeasureTheory.Measure`, and of the extended distance `edist` in an `EMetricSpace`. In this file we set up many of the instances on `ℝ≥0∞`, and provide relationships between `ℝ≥0∞` and `ℝ≥0`, and between `ℝ≥0∞` and `ℝ`. In particular, we provide a coercion from `ℝ≥0` to `ℝ≥0∞` as well as functions `ENNReal.toNNReal`, `ENNReal.ofReal` and `ENNReal.toReal`, all of which take the value zero wherever they cannot be the identity. Also included is the relationship between `ℝ≥0∞` and `ℕ`. The interaction of these functions, especially `ENNReal.ofReal` and `ENNReal.toReal`, with the algebraic and lattice structure can be found in `Data.ENNReal.Real`. This file proves many of the order properties of `ℝ≥0∞`, with the exception of the ways those relate to the algebraic structure, which are included in `Data.ENNReal.Operations`. This file also defines inversion and division: this includes `Inv` and `Div` instances on `ℝ≥0∞` making it into a `DivInvOneMonoid`. As a consequence of being a `DivInvOneMonoid`, `ℝ≥0∞` inherits a power operation with integer exponent: this and other properties is shown in `Data.ENNReal.Inv`. ## Main definitions * `ℝ≥0∞`: the extended nonnegative real numbers `[0, ∞]`; defined as `WithTop ℝ≥0`; it is equipped with the following structures: - coercion from `ℝ≥0` defined in the natural way; - the natural structure of a complete dense linear order: `↑p ≤ ↑q ↔ p ≤ q` and `∀ a, a ≤ ∞`; - `a + b` is defined so that `↑p + ↑q = ↑(p + q)` for `(p q : ℝ≥0)` and `a + ∞ = ∞ + a = ∞`; - `a * b` is defined so that `↑p * ↑q = ↑(p * q)` for `(p q : ℝ≥0)`, `0 * ∞ = ∞ * 0 = 0`, and `a * ∞ = ∞ * a = ∞` for `a ≠ 0`; - `a - b` is defined as the minimal `d` such that `a ≤ d + b`; this way we have `↑p - ↑q = ↑(p - q)`, `∞ - ↑p = ∞`, `↑p - ∞ = ∞ - ∞ = 0`; note that there is no negation, only subtraction; The addition and multiplication defined this way together with `0 = ↑0` and `1 = ↑1` turn `ℝ≥0∞` into a canonically ordered commutative semiring of characteristic zero. - `a⁻¹` is defined as `Inf {b | 1 ≤ a * b}`. This way we have `(↑p)⁻¹ = ↑(p⁻¹)` for `p : ℝ≥0`, `p ≠ 0`, `0⁻¹ = ∞`, and `∞⁻¹ = 0`. - `a / b` is defined as `a * b⁻¹`. This inversion and division include `Inv` and `Div` instances on `ℝ≥0∞`, making it into a `DivInvOneMonoid`. Further properties of these are shown in `Data.ENNReal.Inv`. * Coercions to/from other types: - coercion `ℝ≥0 → ℝ≥0∞` is defined as `Coe`, so one can use `(p : ℝ≥0)` in a context that expects `a : ℝ≥0∞`, and Lean will apply `coe` automatically; - `ENNReal.toNNReal` sends `↑p` to `p` and `∞` to `0`; - `ENNReal.toReal := coe ∘ ENNReal.toNNReal` sends `↑p`, `p : ℝ≥0` to `(↑p : ℝ)` and `∞` to `0`; - `ENNReal.ofReal := coe ∘ Real.toNNReal` sends `x : ℝ` to `↑⟨max x 0, _⟩` - `ENNReal.neTopEquivNNReal` is an equivalence between `{a : ℝ≥0∞ // a ≠ 0}` and `ℝ≥0`. ## Implementation notes We define a `CanLift ℝ≥0∞ ℝ≥0` instance, so one of the ways to prove theorems about an `ℝ≥0∞` number `a` is to consider the cases `a = ∞` and `a ≠ ∞`, and use the tactic `lift a to ℝ≥0 using ha` in the second case. This instance is even more useful if one already has `ha : a ≠ ∞` in the context, or if we have `(f : α → ℝ≥0∞) (hf : ∀ x, f x ≠ ∞)`. ## Notations * `ℝ≥0∞`: the type of the extended nonnegative real numbers; * `ℝ≥0`: the type of nonnegative real numbers `[0, ∞)`; defined in `Data.Real.NNReal`; * `∞`: a localized notation in `ENNReal` for `⊤ : ℝ≥0∞`. -/ open Function Set NNReal variable {α : Type*} /-- The extended nonnegative real numbers. This is usually denoted [0, ∞], and is relevant as the codomain of a measure. -/ def ENNReal := WithTop ℝ≥0 deriving Zero, AddCommMonoidWithOne, SemilatticeSup, DistribLattice, Nontrivial @[inherit_doc] scoped[ENNReal] notation "ℝ≥0∞" => ENNReal /-- Notation for infinity as an `ENNReal` number. -/ scoped[ENNReal] notation "∞" => (⊤ : ENNReal) namespace ENNReal instance : OrderBot ℝ≥0∞ := inferInstanceAs (OrderBot (WithTop ℝ≥0)) instance : BoundedOrder ℝ≥0∞ := inferInstanceAs (BoundedOrder (WithTop ℝ≥0)) instance : CharZero ℝ≥0∞ := inferInstanceAs (CharZero (WithTop ℝ≥0)) noncomputable instance : CanonicallyOrderedCommSemiring ℝ≥0∞ := inferInstanceAs (CanonicallyOrderedCommSemiring (WithTop ℝ≥0)) noncomputable instance : CompleteLinearOrder ℝ≥0∞ := inferInstanceAs (CompleteLinearOrder (WithTop ℝ≥0)) instance : DenselyOrdered ℝ≥0∞ := inferInstanceAs (DenselyOrdered (WithTop ℝ≥0)) noncomputable instance : CanonicallyLinearOrderedAddCommMonoid ℝ≥0∞ := inferInstanceAs (CanonicallyLinearOrderedAddCommMonoid (WithTop ℝ≥0)) noncomputable instance instSub : Sub ℝ≥0∞ := inferInstanceAs (Sub (WithTop ℝ≥0)) noncomputable instance : OrderedSub ℝ≥0∞ := inferInstanceAs (OrderedSub (WithTop ℝ≥0)) noncomputable instance : LinearOrderedAddCommMonoidWithTop ℝ≥0∞ := inferInstanceAs (LinearOrderedAddCommMonoidWithTop (WithTop ℝ≥0)) -- Porting note: rfc: redefine using pattern matching? noncomputable instance : Inv ℝ≥0∞ := ⟨fun a => sInf { b | 1 ≤ a * b }⟩ noncomputable instance : DivInvMonoid ℝ≥0∞ where variable {a b c d : ℝ≥0∞} {r p q : ℝ≥0} -- Porting note: are these 2 instances still required in Lean 4? instance covariantClass_mul_le : CovariantClass ℝ≥0∞ ℝ≥0∞ (· * ·) (· ≤ ·) := inferInstance instance covariantClass_add_le : CovariantClass ℝ≥0∞ ℝ≥0∞ (· + ·) (· ≤ ·) := inferInstance -- Porting note (#11215): TODO: add a `WithTop` instance and use it here noncomputable instance : LinearOrderedCommMonoidWithZero ℝ≥0∞ := { inferInstanceAs (LinearOrderedAddCommMonoidWithTop ℝ≥0∞), inferInstanceAs (CommSemiring ℝ≥0∞) with mul_le_mul_left := fun _ _ => mul_le_mul_left' zero_le_one := zero_le 1 } noncomputable instance : Unique (AddUnits ℝ≥0∞) where default := 0 uniq a := AddUnits.ext <| le_zero_iff.1 <| by rw [← a.add_neg]; exact le_self_add instance : Inhabited ℝ≥0∞ := ⟨0⟩ /-- Coercion from `ℝ≥0` to `ℝ≥0∞`. -/ @[coe, match_pattern] def ofNNReal : ℝ≥0 → ℝ≥0∞ := WithTop.some instance : Coe ℝ≥0 ℝ≥0∞ := ⟨ofNNReal⟩ /-- A version of `WithTop.recTopCoe` that uses `ENNReal.ofNNReal`. -/ @[elab_as_elim, induction_eliminator, cases_eliminator] def recTopCoe {C : ℝ≥0∞ → Sort*} (top : C ∞) (coe : ∀ x : ℝ≥0, C x) (x : ℝ≥0∞) : C x := WithTop.recTopCoe top coe x instance canLift : CanLift ℝ≥0∞ ℝ≥0 ofNNReal (· ≠ ∞) := WithTop.canLift @[simp] theorem none_eq_top : (none : ℝ≥0∞) = ∞ := rfl @[simp] theorem some_eq_coe (a : ℝ≥0) : (Option.some a : ℝ≥0∞) = (↑a : ℝ≥0∞) := rfl @[simp] theorem some_eq_coe' (a : ℝ≥0) : (WithTop.some a : ℝ≥0∞) = (↑a : ℝ≥0∞) := rfl lemma coe_injective : Injective ((↑) : ℝ≥0 → ℝ≥0∞) := WithTop.coe_injective @[simp, norm_cast] lemma coe_inj : (p : ℝ≥0∞) = q ↔ p = q := coe_injective.eq_iff lemma coe_ne_coe : (p : ℝ≥0∞) ≠ q ↔ p ≠ q := coe_inj.not theorem range_coe' : range ofNNReal = Iio ∞ := WithTop.range_coe theorem range_coe : range ofNNReal = {∞}ᶜ := (isCompl_range_some_none ℝ≥0).symm.compl_eq.symm /-- `toNNReal x` returns `x` if it is real, otherwise 0. -/ protected def toNNReal : ℝ≥0∞ → ℝ≥0 := WithTop.untop' 0 /-- `toReal x` returns `x` if it is real, `0` otherwise. -/ protected def toReal (a : ℝ≥0∞) : Real := a.toNNReal /-- `ofReal x` returns `x` if it is nonnegative, `0` otherwise. -/ protected noncomputable def ofReal (r : Real) : ℝ≥0∞ := r.toNNReal @[simp, norm_cast] theorem toNNReal_coe : (r : ℝ≥0∞).toNNReal = r := rfl @[simp] theorem coe_toNNReal : ∀ {a : ℝ≥0∞}, a ≠ ∞ → ↑a.toNNReal = a | ofNNReal _, _ => rfl | ⊤, h => (h rfl).elim @[simp] theorem ofReal_toReal {a : ℝ≥0∞} (h : a ≠ ∞) : ENNReal.ofReal a.toReal = a := by simp [ENNReal.toReal, ENNReal.ofReal, h] @[simp] theorem toReal_ofReal {r : ℝ} (h : 0 ≤ r) : (ENNReal.ofReal r).toReal = r := max_eq_left h theorem toReal_ofReal' {r : ℝ} : (ENNReal.ofReal r).toReal = max r 0 := rfl theorem coe_toNNReal_le_self : ∀ {a : ℝ≥0∞}, ↑a.toNNReal ≤ a | ofNNReal r => by rw [toNNReal_coe] | ⊤ => le_top theorem coe_nnreal_eq (r : ℝ≥0) : (r : ℝ≥0∞) = ENNReal.ofReal r := by rw [ENNReal.ofReal, Real.toNNReal_coe] theorem ofReal_eq_coe_nnreal {x : ℝ} (h : 0 ≤ x) : ENNReal.ofReal x = ofNNReal ⟨x, h⟩ := (coe_nnreal_eq ⟨x, h⟩).symm @[simp] theorem ofReal_coe_nnreal : ENNReal.ofReal p = p := (coe_nnreal_eq p).symm @[simp, norm_cast] theorem coe_zero : ↑(0 : ℝ≥0) = (0 : ℝ≥0∞) := rfl @[simp, norm_cast] theorem coe_one : ↑(1 : ℝ≥0) = (1 : ℝ≥0∞) := rfl @[simp] theorem toReal_nonneg {a : ℝ≥0∞} : 0 ≤ a.toReal := a.toNNReal.2 @[norm_cast] theorem coe_toNNReal_eq_toReal (z : ℝ≥0∞) : (z.toNNReal : ℝ) = z.toReal := rfl @[simp] theorem toNNReal_toReal_eq (z : ℝ≥0∞) : z.toReal.toNNReal = z.toNNReal := by ext; simp [coe_toNNReal_eq_toReal] @[simp] theorem top_toNNReal : ∞.toNNReal = 0 := rfl @[simp] theorem top_toReal : ∞.toReal = 0 := rfl @[simp] theorem one_toReal : (1 : ℝ≥0∞).toReal = 1 := rfl @[simp] theorem one_toNNReal : (1 : ℝ≥0∞).toNNReal = 1 := rfl @[simp] theorem coe_toReal (r : ℝ≥0) : (r : ℝ≥0∞).toReal = r := rfl @[simp] theorem zero_toNNReal : (0 : ℝ≥0∞).toNNReal = 0 := rfl @[simp] theorem zero_toReal : (0 : ℝ≥0∞).toReal = 0 := rfl @[simp] theorem ofReal_zero : ENNReal.ofReal (0 : ℝ) = 0 := by simp [ENNReal.ofReal] @[simp] theorem ofReal_one : ENNReal.ofReal (1 : ℝ) = (1 : ℝ≥0∞) := by simp [ENNReal.ofReal] theorem ofReal_toReal_le {a : ℝ≥0∞} : ENNReal.ofReal a.toReal ≤ a := if ha : a = ∞ then ha.symm ▸ le_top else le_of_eq (ofReal_toReal ha) theorem forall_ennreal {p : ℝ≥0∞ → Prop} : (∀ a, p a) ↔ (∀ r : ℝ≥0, p r) ∧ p ∞ := Option.forall.trans and_comm theorem forall_ne_top {p : ℝ≥0∞ → Prop} : (∀ a, a ≠ ∞ → p a) ↔ ∀ r : ℝ≥0, p r := Option.ball_ne_none theorem exists_ne_top {p : ℝ≥0∞ → Prop} : (∃ a ≠ ∞, p a) ↔ ∃ r : ℝ≥0, p r := Option.exists_ne_none theorem toNNReal_eq_zero_iff (x : ℝ≥0∞) : x.toNNReal = 0 ↔ x = 0 ∨ x = ∞ := WithTop.untop'_eq_self_iff theorem toReal_eq_zero_iff (x : ℝ≥0∞) : x.toReal = 0 ↔ x = 0 ∨ x = ∞ := by simp [ENNReal.toReal, toNNReal_eq_zero_iff] theorem toNNReal_ne_zero : a.toNNReal ≠ 0 ↔ a ≠ 0 ∧ a ≠ ∞ := a.toNNReal_eq_zero_iff.not.trans not_or theorem toReal_ne_zero : a.toReal ≠ 0 ↔ a ≠ 0 ∧ a ≠ ∞ := a.toReal_eq_zero_iff.not.trans not_or theorem toNNReal_eq_one_iff (x : ℝ≥0∞) : x.toNNReal = 1 ↔ x = 1 := WithTop.untop'_eq_iff.trans <| by simp theorem toReal_eq_one_iff (x : ℝ≥0∞) : x.toReal = 1 ↔ x = 1 := by rw [ENNReal.toReal, NNReal.coe_eq_one, ENNReal.toNNReal_eq_one_iff] theorem toNNReal_ne_one : a.toNNReal ≠ 1 ↔ a ≠ 1 := a.toNNReal_eq_one_iff.not theorem toReal_ne_one : a.toReal ≠ 1 ↔ a ≠ 1 := a.toReal_eq_one_iff.not @[simp] theorem coe_ne_top : (r : ℝ≥0∞) ≠ ∞ := WithTop.coe_ne_top @[simp] theorem top_ne_coe : ∞ ≠ (r : ℝ≥0∞) := WithTop.top_ne_coe @[simp] theorem coe_lt_top : (r : ℝ≥0∞) < ∞ := WithTop.coe_lt_top r @[simp] theorem ofReal_ne_top {r : ℝ} : ENNReal.ofReal r ≠ ∞ := coe_ne_top @[simp] theorem ofReal_lt_top {r : ℝ} : ENNReal.ofReal r < ∞ := coe_lt_top @[simp] theorem top_ne_ofReal {r : ℝ} : ∞ ≠ ENNReal.ofReal r := top_ne_coe @[simp] theorem ofReal_toReal_eq_iff : ENNReal.ofReal a.toReal = a ↔ a ≠ ⊤ := ⟨fun h => by rw [← h] exact ofReal_ne_top, ofReal_toReal⟩ @[simp] theorem toReal_ofReal_eq_iff {a : ℝ} : (ENNReal.ofReal a).toReal = a ↔ 0 ≤ a := ⟨fun h => by rw [← h] exact toReal_nonneg, toReal_ofReal⟩ @[simp] theorem zero_ne_top : 0 ≠ ∞ := coe_ne_top @[simp] theorem top_ne_zero : ∞ ≠ 0 := top_ne_coe @[simp] theorem one_ne_top : 1 ≠ ∞ := coe_ne_top @[simp] theorem top_ne_one : ∞ ≠ 1 := top_ne_coe @[simp] theorem zero_lt_top : 0 < ∞ := coe_lt_top @[simp, norm_cast] theorem coe_le_coe : (↑r : ℝ≥0∞) ≤ ↑q ↔ r ≤ q := WithTop.coe_le_coe @[simp, norm_cast] theorem coe_lt_coe : (↑r : ℝ≥0∞) < ↑q ↔ r < q := WithTop.coe_lt_coe -- Needed until `@[gcongr]` accepts iff statements alias ⟨_, coe_le_coe_of_le⟩ := coe_le_coe attribute [gcongr] ENNReal.coe_le_coe_of_le -- Needed until `@[gcongr]` accepts iff statements alias ⟨_, coe_lt_coe_of_lt⟩ := coe_lt_coe attribute [gcongr] ENNReal.coe_lt_coe_of_lt theorem coe_mono : Monotone ofNNReal := fun _ _ => coe_le_coe.2 theorem coe_strictMono : StrictMono ofNNReal := fun _ _ => coe_lt_coe.2 @[simp, norm_cast] theorem coe_eq_zero : (↑r : ℝ≥0∞) = 0 ↔ r = 0 := coe_inj @[simp, norm_cast] theorem zero_eq_coe : 0 = (↑r : ℝ≥0∞) ↔ 0 = r := coe_inj @[simp, norm_cast] theorem coe_eq_one : (↑r : ℝ≥0∞) = 1 ↔ r = 1 := coe_inj @[simp, norm_cast] theorem one_eq_coe : 1 = (↑r : ℝ≥0∞) ↔ 1 = r := coe_inj @[simp, norm_cast] theorem coe_pos : 0 < (r : ℝ≥0∞) ↔ 0 < r := coe_lt_coe theorem coe_ne_zero : (r : ℝ≥0∞) ≠ 0 ↔ r ≠ 0 := coe_eq_zero.not lemma coe_ne_one : (r : ℝ≥0∞) ≠ 1 ↔ r ≠ 1 := coe_eq_one.not @[simp, norm_cast] lemma coe_add (x y : ℝ≥0) : (↑(x + y) : ℝ≥0∞) = x + y := rfl @[simp, norm_cast] lemma coe_mul (x y : ℝ≥0) : (↑(x * y) : ℝ≥0∞) = x * y := rfl @[norm_cast] lemma coe_nsmul (n : ℕ) (x : ℝ≥0) : (↑(n • x) : ℝ≥0∞) = n • x := rfl @[simp, norm_cast] lemma coe_pow (x : ℝ≥0) (n : ℕ) : (↑(x ^ n) : ℝ≥0∞) = x ^ n := rfl -- See note [no_index around OfNat.ofNat] @[simp, norm_cast] theorem coe_ofNat (n : ℕ) [n.AtLeastTwo] : ((no_index (OfNat.ofNat n) : ℝ≥0) : ℝ≥0∞) = OfNat.ofNat n := rfl -- Porting note (#11215): TODO: add lemmas about `OfNat.ofNat` and `<`/`≤` theorem coe_two : ((2 : ℝ≥0) : ℝ≥0∞) = 2 := rfl theorem toNNReal_eq_toNNReal_iff (x y : ℝ≥0∞) : x.toNNReal = y.toNNReal ↔ x = y ∨ x = 0 ∧ y = ⊤ ∨ x = ⊤ ∧ y = 0 := WithTop.untop'_eq_untop'_iff theorem toReal_eq_toReal_iff (x y : ℝ≥0∞) : x.toReal = y.toReal ↔ x = y ∨ x = 0 ∧ y = ⊤ ∨ x = ⊤ ∧ y = 0 := by simp only [ENNReal.toReal, NNReal.coe_inj, toNNReal_eq_toNNReal_iff] theorem toNNReal_eq_toNNReal_iff' {x y : ℝ≥0∞} (hx : x ≠ ⊤) (hy : y ≠ ⊤) : x.toNNReal = y.toNNReal ↔ x = y := by simp only [ENNReal.toNNReal_eq_toNNReal_iff x y, hx, hy, and_false, false_and, or_false] theorem toReal_eq_toReal_iff' {x y : ℝ≥0∞} (hx : x ≠ ⊤) (hy : y ≠ ⊤) : x.toReal = y.toReal ↔ x = y := by simp only [ENNReal.toReal, NNReal.coe_inj, toNNReal_eq_toNNReal_iff' hx hy] theorem one_lt_two : (1 : ℝ≥0∞) < 2 := Nat.one_lt_ofNat @[simp] theorem two_ne_top : (2 : ℝ≥0∞) ≠ ∞ := coe_ne_top @[simp] theorem two_lt_top : (2 : ℝ≥0∞) < ∞ := coe_lt_top /-- `(1 : ℝ≥0∞) ≤ 1`, recorded as a `Fact` for use with `Lp` spaces. -/ instance _root_.fact_one_le_one_ennreal : Fact ((1 : ℝ≥0∞) ≤ 1) := ⟨le_rfl⟩ /-- `(1 : ℝ≥0∞) ≤ 2`, recorded as a `Fact` for use with `Lp` spaces. -/ instance _root_.fact_one_le_two_ennreal : Fact ((1 : ℝ≥0∞) ≤ 2) := ⟨one_le_two⟩ /-- `(1 : ℝ≥0∞) ≤ ∞`, recorded as a `Fact` for use with `Lp` spaces. -/ instance _root_.fact_one_le_top_ennreal : Fact ((1 : ℝ≥0∞) ≤ ∞) := ⟨le_top⟩ /-- The set of numbers in `ℝ≥0∞` that are not equal to `∞` is equivalent to `ℝ≥0`. -/ def neTopEquivNNReal : { a | a ≠ ∞ } ≃ ℝ≥0 where toFun x := ENNReal.toNNReal x invFun x := ⟨x, coe_ne_top⟩ left_inv := fun x => Subtype.eq <| coe_toNNReal x.2 right_inv _ := toNNReal_coe theorem cinfi_ne_top [InfSet α] (f : ℝ≥0∞ → α) : ⨅ x : { x // x ≠ ∞ }, f x = ⨅ x : ℝ≥0, f x := Eq.symm <| neTopEquivNNReal.symm.surjective.iInf_congr _ fun _ => rfl theorem iInf_ne_top [CompleteLattice α] (f : ℝ≥0∞ → α) : ⨅ (x) (_ : x ≠ ∞), f x = ⨅ x : ℝ≥0, f x := by rw [iInf_subtype', cinfi_ne_top] theorem csupr_ne_top [SupSet α] (f : ℝ≥0∞ → α) : ⨆ x : { x // x ≠ ∞ }, f x = ⨆ x : ℝ≥0, f x := @cinfi_ne_top αᵒᵈ _ _ theorem iSup_ne_top [CompleteLattice α] (f : ℝ≥0∞ → α) : ⨆ (x) (_ : x ≠ ∞), f x = ⨆ x : ℝ≥0, f x := @iInf_ne_top αᵒᵈ _ _ theorem iInf_ennreal {α : Type*} [CompleteLattice α] {f : ℝ≥0∞ → α} : ⨅ n, f n = (⨅ n : ℝ≥0, f n) ⊓ f ∞ := (iInf_option f).trans (inf_comm _ _) theorem iSup_ennreal {α : Type*} [CompleteLattice α] {f : ℝ≥0∞ → α} : ⨆ n, f n = (⨆ n : ℝ≥0, f n) ⊔ f ∞ := @iInf_ennreal αᵒᵈ _ _ /-- Coercion `ℝ≥0 → ℝ≥0∞` as a `RingHom`. -/ def ofNNRealHom : ℝ≥0 →+* ℝ≥0∞ where toFun := some map_one' := coe_one map_mul' _ _ := coe_mul _ _ map_zero' := coe_zero map_add' _ _ := coe_add _ _ @[simp] theorem coe_ofNNRealHom : ⇑ofNNRealHom = some := rfl @[simp, norm_cast] theorem coe_indicator {α} (s : Set α) (f : α → ℝ≥0) (a : α) : ((s.indicator f a : ℝ≥0) : ℝ≥0∞) = s.indicator (fun x => ↑(f x)) a := (ofNNRealHom : ℝ≥0 →+ ℝ≥0∞).map_indicator _ _ _ section Order theorem bot_eq_zero : (⊥ : ℝ≥0∞) = 0 := rfl -- `coe_lt_top` moved up theorem not_top_le_coe : ¬∞ ≤ ↑r := WithTop.not_top_le_coe r @[simp, norm_cast] theorem one_le_coe_iff : (1 : ℝ≥0∞) ≤ ↑r ↔ 1 ≤ r := coe_le_coe @[simp, norm_cast] theorem coe_le_one_iff : ↑r ≤ (1 : ℝ≥0∞) ↔ r ≤ 1 := coe_le_coe @[simp, norm_cast] theorem coe_lt_one_iff : (↑p : ℝ≥0∞) < 1 ↔ p < 1 := coe_lt_coe @[simp, norm_cast] theorem one_lt_coe_iff : 1 < (↑p : ℝ≥0∞) ↔ 1 < p := coe_lt_coe @[simp, norm_cast] theorem coe_natCast (n : ℕ) : ((n : ℝ≥0) : ℝ≥0∞) = n := rfl @[simp, norm_cast] lemma ofReal_natCast (n : ℕ) : ENNReal.ofReal n = n := by simp [ENNReal.ofReal] -- See note [no_index around OfNat.ofNat] @[simp] theorem ofReal_ofNat (n : ℕ) [n.AtLeastTwo] : ENNReal.ofReal (no_index (OfNat.ofNat n)) = OfNat.ofNat n := ofReal_natCast n @[simp] theorem natCast_ne_top (n : ℕ) : (n : ℝ≥0∞) ≠ ∞ := WithTop.natCast_ne_top n @[simp] theorem top_ne_natCast (n : ℕ) : ∞ ≠ n := WithTop.top_ne_natCast n @[simp] theorem one_lt_top : 1 < ∞ := coe_lt_top @[simp, norm_cast] theorem toNNReal_nat (n : ℕ) : (n : ℝ≥0∞).toNNReal = n := by rw [← ENNReal.coe_natCast n, ENNReal.toNNReal_coe] @[simp, norm_cast] theorem toReal_nat (n : ℕ) : (n : ℝ≥0∞).toReal = n := by rw [← ENNReal.ofReal_natCast n, ENNReal.toReal_ofReal (Nat.cast_nonneg _)] -- See note [no_index around OfNat.ofNat] @[simp] theorem toReal_ofNat (n : ℕ) [n.AtLeastTwo] : ENNReal.toReal (no_index (OfNat.ofNat n)) = OfNat.ofNat n := toReal_nat n theorem le_coe_iff : a ≤ ↑r ↔ ∃ p : ℝ≥0, a = p ∧ p ≤ r := WithTop.le_coe_iff theorem coe_le_iff : ↑r ≤ a ↔ ∀ p : ℝ≥0, a = p → r ≤ p := WithTop.coe_le_iff theorem lt_iff_exists_coe : a < b ↔ ∃ p : ℝ≥0, a = p ∧ ↑p < b := WithTop.lt_iff_exists_coe theorem toReal_le_coe_of_le_coe {a : ℝ≥0∞} {b : ℝ≥0} (h : a ≤ b) : a.toReal ≤ b := by lift a to ℝ≥0 using ne_top_of_le_ne_top coe_ne_top h simpa using h @[simp, norm_cast] theorem coe_finset_sup {s : Finset α} {f : α → ℝ≥0} : ↑(s.sup f) = s.sup fun x => (f x : ℝ≥0∞) := Finset.comp_sup_eq_sup_comp_of_is_total _ coe_mono rfl @[simp] theorem max_eq_zero_iff : max a b = 0 ↔ a = 0 ∧ b = 0 := max_eq_bot theorem max_zero_left : max 0 a = a := max_eq_right (zero_le a) theorem max_zero_right : max a 0 = a := max_eq_left (zero_le a) @[simp] theorem sup_eq_max : a ⊔ b = max a b := rfl -- Porting note: moved `le_of_forall_pos_le_add` down theorem lt_iff_exists_rat_btwn : a < b ↔ ∃ q : ℚ, 0 ≤ q ∧ a < Real.toNNReal q ∧ (Real.toNNReal q : ℝ≥0∞) < b := ⟨fun h => by rcases lt_iff_exists_coe.1 h with ⟨p, rfl, _⟩ rcases exists_between h with ⟨c, pc, cb⟩ rcases lt_iff_exists_coe.1 cb with ⟨r, rfl, _⟩ rcases (NNReal.lt_iff_exists_rat_btwn _ _).1 (coe_lt_coe.1 pc) with ⟨q, hq0, pq, qr⟩ exact ⟨q, hq0, coe_lt_coe.2 pq, lt_trans (coe_lt_coe.2 qr) cb⟩, fun ⟨q, _, qa, qb⟩ => lt_trans qa qb⟩ theorem lt_iff_exists_real_btwn : a < b ↔ ∃ r : ℝ, 0 ≤ r ∧ a < ENNReal.ofReal r ∧ (ENNReal.ofReal r : ℝ≥0∞) < b := ⟨fun h => let ⟨q, q0, aq, qb⟩ := ENNReal.lt_iff_exists_rat_btwn.1 h ⟨q, Rat.cast_nonneg.2 q0, aq, qb⟩, fun ⟨_, _, qa, qb⟩ => lt_trans qa qb⟩ theorem lt_iff_exists_nnreal_btwn : a < b ↔ ∃ r : ℝ≥0, a < r ∧ (r : ℝ≥0∞) < b := WithTop.lt_iff_exists_coe_btwn theorem lt_iff_exists_add_pos_lt : a < b ↔ ∃ r : ℝ≥0, 0 < r ∧ a + r < b := by refine ⟨fun hab => ?_, fun ⟨r, _, hr⟩ => lt_of_le_of_lt le_self_add hr⟩ rcases lt_iff_exists_nnreal_btwn.1 hab with ⟨c, ac, cb⟩ lift a to ℝ≥0 using ac.ne_top rw [coe_lt_coe] at ac refine ⟨c - a, tsub_pos_iff_lt.2 ac, ?_⟩ rwa [← coe_add, add_tsub_cancel_of_le ac.le] theorem le_of_forall_pos_le_add (h : ∀ ε : ℝ≥0, 0 < ε → b < ∞ → a ≤ b + ε) : a ≤ b := by contrapose! h rcases lt_iff_exists_add_pos_lt.1 h with ⟨r, hr0, hr⟩ exact ⟨r, hr0, h.trans_le le_top, hr⟩ theorem natCast_lt_coe {n : ℕ} : n < (r : ℝ≥0∞) ↔ n < r := ENNReal.coe_natCast n ▸ coe_lt_coe theorem coe_lt_natCast {n : ℕ} : (r : ℝ≥0∞) < n ↔ r < n := ENNReal.coe_natCast n ▸ coe_lt_coe @[deprecated (since := "2024-04-05")] alias coe_nat := coe_natCast @[deprecated (since := "2024-04-05")] alias ofReal_coe_nat := ofReal_natCast @[deprecated (since := "2024-04-05")] alias nat_ne_top := natCast_ne_top @[deprecated (since := "2024-04-05")] alias top_ne_nat := top_ne_natCast @[deprecated (since := "2024-04-05")] alias coe_nat_lt_coe := natCast_lt_coe @[deprecated (since := "2024-04-05")] alias coe_lt_coe_nat := coe_lt_natCast protected theorem exists_nat_gt {r : ℝ≥0∞} (h : r ≠ ∞) : ∃ n : ℕ, r < n := by lift r to ℝ≥0 using h rcases exists_nat_gt r with ⟨n, hn⟩ exact ⟨n, coe_lt_natCast.2 hn⟩ @[simp] theorem iUnion_Iio_coe_nat : ⋃ n : ℕ, Iio (n : ℝ≥0∞) = {∞}ᶜ := by ext x rw [mem_iUnion] exact ⟨fun ⟨n, hn⟩ => ne_top_of_lt hn, ENNReal.exists_nat_gt⟩ @[simp] theorem iUnion_Iic_coe_nat : ⋃ n : ℕ, Iic (n : ℝ≥0∞) = {∞}ᶜ := Subset.antisymm (iUnion_subset fun n _x hx => ne_top_of_le_ne_top (natCast_ne_top n) hx) <| iUnion_Iio_coe_nat ▸ iUnion_mono fun _ => Iio_subset_Iic_self @[simp] theorem iUnion_Ioc_coe_nat : ⋃ n : ℕ, Ioc a n = Ioi a \ {∞} := by simp only [← Ioi_inter_Iic, ← inter_iUnion, iUnion_Iic_coe_nat, diff_eq] @[simp] theorem iUnion_Ioo_coe_nat : ⋃ n : ℕ, Ioo a n = Ioi a \ {∞} := by simp only [← Ioi_inter_Iio, ← inter_iUnion, iUnion_Iio_coe_nat, diff_eq] @[simp] theorem iUnion_Icc_coe_nat : ⋃ n : ℕ, Icc a n = Ici a \ {∞} := by simp only [← Ici_inter_Iic, ← inter_iUnion, iUnion_Iic_coe_nat, diff_eq] @[simp] theorem iUnion_Ico_coe_nat : ⋃ n : ℕ, Ico a n = Ici a \ {∞} := by simp only [← Ici_inter_Iio, ← inter_iUnion, iUnion_Iio_coe_nat, diff_eq] @[simp] theorem iInter_Ici_coe_nat : ⋂ n : ℕ, Ici (n : ℝ≥0∞) = {∞} := by simp only [← compl_Iio, ← compl_iUnion, iUnion_Iio_coe_nat, compl_compl] @[simp] theorem iInter_Ioi_coe_nat : ⋂ n : ℕ, Ioi (n : ℝ≥0∞) = {∞} := by simp only [← compl_Iic, ← compl_iUnion, iUnion_Iic_coe_nat, compl_compl] @[simp, norm_cast] theorem coe_min (r p : ℝ≥0) : ((min r p : ℝ≥0) : ℝ≥0∞) = min (r : ℝ≥0∞) p := rfl @[simp, norm_cast] theorem coe_max (r p : ℝ≥0) : ((max r p : ℝ≥0) : ℝ≥0∞) = max (r : ℝ≥0∞) p := rfl theorem le_of_top_imp_top_of_toNNReal_le {a b : ℝ≥0∞} (h : a = ⊤ → b = ⊤) (h_nnreal : a ≠ ⊤ → b ≠ ⊤ → a.toNNReal ≤ b.toNNReal) : a ≤ b := by by_contra! hlt lift b to ℝ≥0 using hlt.ne_top lift a to ℝ≥0 using mt h coe_ne_top refine hlt.not_le ?_ simpa using h_nnreal @[simp] theorem abs_toReal {x : ℝ≥0∞} : |x.toReal| = x.toReal := by cases x <;> simp end Order section CompleteLattice variable {ι : Sort*} {f : ι → ℝ≥0} theorem coe_sSup {s : Set ℝ≥0} : BddAbove s → (↑(sSup s) : ℝ≥0∞) = ⨆ a ∈ s, ↑a := WithTop.coe_sSup theorem coe_sInf {s : Set ℝ≥0} (hs : s.Nonempty) : (↑(sInf s) : ℝ≥0∞) = ⨅ a ∈ s, ↑a := WithTop.coe_sInf hs (OrderBot.bddBelow s) theorem coe_iSup {ι : Sort*} {f : ι → ℝ≥0} (hf : BddAbove (range f)) : (↑(iSup f) : ℝ≥0∞) = ⨆ a, ↑(f a) := WithTop.coe_iSup _ hf @[norm_cast] theorem coe_iInf {ι : Sort*} [Nonempty ι] (f : ι → ℝ≥0) : (↑(iInf f) : ℝ≥0∞) = ⨅ a, ↑(f a) := WithTop.coe_iInf (OrderBot.bddBelow _) theorem coe_mem_upperBounds {s : Set ℝ≥0} : ↑r ∈ upperBounds (ofNNReal '' s) ↔ r ∈ upperBounds s := by simp (config := { contextual := true }) [upperBounds, forall_mem_image, -mem_image, *] lemma iSup_coe_eq_top : ⨆ i, (f i : ℝ≥0∞) = ⊤ ↔ ¬ BddAbove (range f) := WithTop.iSup_coe_eq_top lemma iSup_coe_lt_top : ⨆ i, (f i : ℝ≥0∞) < ⊤ ↔ BddAbove (range f) := WithTop.iSup_coe_lt_top lemma iInf_coe_eq_top : ⨅ i, (f i : ℝ≥0∞) = ⊤ ↔ IsEmpty ι := WithTop.iInf_coe_eq_top lemma iInf_coe_lt_top : ⨅ i, (f i : ℝ≥0∞) < ⊤ ↔ Nonempty ι := WithTop.iInf_coe_lt_top end CompleteLattice section Bit -- Porting note: removed lemmas about `bit0` and `bit1` -- TODO: add lemmas about `OfNat.ofNat` end Bit end ENNReal open ENNReal namespace Set namespace OrdConnected variable {s : Set ℝ} {t : Set ℝ≥0} {u : Set ℝ≥0∞} theorem preimage_coe_nnreal_ennreal (h : u.OrdConnected) : ((↑) ⁻¹' u : Set ℝ≥0).OrdConnected := h.preimage_mono ENNReal.coe_mono -- Porting note (#11215): TODO: generalize to `WithTop` theorem image_coe_nnreal_ennreal (h : t.OrdConnected) : ((↑) '' t : Set ℝ≥0∞).OrdConnected := by refine ⟨forall_mem_image.2 fun x hx => forall_mem_image.2 fun y hy z hz => ?_⟩ rcases ENNReal.le_coe_iff.1 hz.2 with ⟨z, rfl, -⟩ exact mem_image_of_mem _ (h.out hx hy ⟨ENNReal.coe_le_coe.1 hz.1, ENNReal.coe_le_coe.1 hz.2⟩) theorem preimage_ennreal_ofReal (h : u.OrdConnected) : (ENNReal.ofReal ⁻¹' u).OrdConnected := h.preimage_coe_nnreal_ennreal.preimage_real_toNNReal theorem image_ennreal_ofReal (h : s.OrdConnected) : (ENNReal.ofReal '' s).OrdConnected := by simpa only [image_image] using h.image_real_toNNReal.image_coe_nnreal_ennreal end OrdConnected end Set namespace Mathlib.Meta.Positivity open Lean Meta Qq /-- Extension for the `positivity` tactic: `ENNReal.toReal`. -/ @[positivity ENNReal.toReal _] def evalENNRealtoReal : PositivityExt where eval {u α} _zα _pα e := do match u, α, e with | 0, ~q(ℝ), ~q(ENNReal.toReal $a) => assertInstancesCommute pure (.nonnegative q(ENNReal.toReal_nonneg)) | _, _, _ => throwError "not ENNReal.toReal" /-- Extension for the `positivity` tactic: `ENNReal.ofNNReal`. -/ @[positivity ENNReal.ofNNReal _] def evalENNRealOfNNReal : PositivityExt where eval {u α} _zα _pα e := do match u, α, e with | 0, ~q(ℝ≥0∞), ~q(ENNReal.ofNNReal $a) => let ra ← core q(inferInstance) q(inferInstance) a assertInstancesCommute match ra with | .positive pa => pure <| .positive q(ENNReal.coe_pos.mpr $pa) | _ => pure .none | _, _, _ => throwError "not ENNReal.ofNNReal" end Mathlib.Meta.Positivity @[deprecated (since := "2023-12-23")] protected alias ENNReal.le_inv_smul_iff_of_pos := le_inv_smul_iff_of_pos @[deprecated (since := "2023-12-23")] protected alias ENNReal.inv_smul_le_iff_of_pos := inv_smul_le_iff_of_pos
Data\ENNReal\Inv.lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Yury Kudryashov -/ import Mathlib.Data.ENNReal.Operations /-! # Results about division in extended non-negative reals This file establishes basic properties related to the inversion and division operations on `ℝ≥0∞`. For instance, as a consequence of being a `DivInvOneMonoid`, `ℝ≥0∞` inherits a power operation with integer exponent. ## Main results A few order isomorphisms are worthy of mention: - `OrderIso.invENNReal : ℝ≥0∞ ≃o ℝ≥0∞ᵒᵈ`: The map `x ↦ x⁻¹` as an order isomorphism to the dual. - `orderIsoIicOneBirational : ℝ≥0∞ ≃o Iic (1 : ℝ≥0∞)`: The birational order isomorphism between `ℝ≥0∞` and the unit interval `Set.Iic (1 : ℝ≥0∞)` given by `x ↦ (x⁻¹ + 1)⁻¹` with inverse `x ↦ (x⁻¹ - 1)⁻¹` - `orderIsoIicCoe (a : ℝ≥0) : Iic (a : ℝ≥0∞) ≃o Iic a`: Order isomorphism between an initial interval in `ℝ≥0∞` and an initial interval in `ℝ≥0` given by the identity map. - `orderIsoUnitIntervalBirational : ℝ≥0∞ ≃o Icc (0 : ℝ) 1`: An order isomorphism between the extended nonnegative real numbers and the unit interval. This is `orderIsoIicOneBirational` composed with the identity order isomorphism between `Iic (1 : ℝ≥0∞)` and `Icc (0 : ℝ) 1`. -/ open Set NNReal namespace ENNReal noncomputable section Inv variable {a b c d : ℝ≥0∞} {r p q : ℝ≥0} protected theorem div_eq_inv_mul : a / b = b⁻¹ * a := by rw [div_eq_mul_inv, mul_comm] @[simp] theorem inv_zero : (0 : ℝ≥0∞)⁻¹ = ∞ := show sInf { b : ℝ≥0∞ | 1 ≤ 0 * b } = ∞ by simp @[simp] theorem inv_top : ∞⁻¹ = 0 := bot_unique <| le_of_forall_le_of_dense fun a (h : 0 < a) => sInf_le <| by simp [*, h.ne', top_mul] theorem coe_inv_le : (↑r⁻¹ : ℝ≥0∞) ≤ (↑r)⁻¹ := le_sInf fun b (hb : 1 ≤ ↑r * b) => coe_le_iff.2 <| by rintro b rfl apply NNReal.inv_le_of_le_mul rwa [← coe_mul, ← coe_one, coe_le_coe] at hb @[simp, norm_cast] theorem coe_inv (hr : r ≠ 0) : (↑r⁻¹ : ℝ≥0∞) = (↑r)⁻¹ := coe_inv_le.antisymm <| sInf_le <| mem_setOf.2 <| by rw [← coe_mul, mul_inv_cancel hr, coe_one] @[norm_cast] theorem coe_inv_two : ((2⁻¹ : ℝ≥0) : ℝ≥0∞) = 2⁻¹ := by rw [coe_inv _root_.two_ne_zero, coe_two] @[simp, norm_cast] theorem coe_div (hr : r ≠ 0) : (↑(p / r) : ℝ≥0∞) = p / r := by rw [div_eq_mul_inv, div_eq_mul_inv, coe_mul, coe_inv hr] lemma coe_div_le : ↑(p / r) ≤ (p / r : ℝ≥0∞) := by simpa only [div_eq_mul_inv, coe_mul] using mul_le_mul_left' coe_inv_le _ theorem div_zero (h : a ≠ 0) : a / 0 = ∞ := by simp [div_eq_mul_inv, h] instance : DivInvOneMonoid ℝ≥0∞ := { inferInstanceAs (DivInvMonoid ℝ≥0∞) with inv_one := by simpa only [coe_inv one_ne_zero, coe_one] using coe_inj.2 inv_one } protected theorem inv_pow : ∀ {a : ℝ≥0∞} {n : ℕ}, (a ^ n)⁻¹ = a⁻¹ ^ n | _, 0 => by simp only [pow_zero, inv_one] | ⊤, n + 1 => by simp [top_pow] | (a : ℝ≥0), n + 1 => by rcases eq_or_ne a 0 with (rfl | ha) · simp [top_pow] · have := pow_ne_zero (n + 1) ha norm_cast rw [inv_pow] protected theorem mul_inv_cancel (h0 : a ≠ 0) (ht : a ≠ ∞) : a * a⁻¹ = 1 := by lift a to ℝ≥0 using ht norm_cast at h0; norm_cast exact mul_inv_cancel h0 protected theorem inv_mul_cancel (h0 : a ≠ 0) (ht : a ≠ ∞) : a⁻¹ * a = 1 := mul_comm a a⁻¹ ▸ ENNReal.mul_inv_cancel h0 ht protected theorem div_mul_cancel (h0 : a ≠ 0) (hI : a ≠ ∞) : b / a * a = b := by rw [div_eq_mul_inv, mul_assoc, ENNReal.inv_mul_cancel h0 hI, mul_one] protected theorem mul_div_cancel' (h0 : a ≠ 0) (hI : a ≠ ∞) : a * (b / a) = b := by rw [mul_comm, ENNReal.div_mul_cancel h0 hI] -- Porting note: `simp only [div_eq_mul_inv, mul_comm, mul_assoc]` doesn't work in the following two protected theorem mul_comm_div : a / b * c = a * (c / b) := by simp only [div_eq_mul_inv, mul_right_comm, ← mul_assoc] protected theorem mul_div_right_comm : a * b / c = a / c * b := by simp only [div_eq_mul_inv, mul_right_comm] instance : InvolutiveInv ℝ≥0∞ where inv_inv a := by by_cases a = 0 <;> cases a <;> simp_all [none_eq_top, some_eq_coe, -coe_inv, (coe_inv _).symm] @[simp] protected lemma inv_eq_one : a⁻¹ = 1 ↔ a = 1 := by rw [← inv_inj, inv_inv, inv_one] @[simp] theorem inv_eq_top : a⁻¹ = ∞ ↔ a = 0 := inv_zero ▸ inv_inj theorem inv_ne_top : a⁻¹ ≠ ∞ ↔ a ≠ 0 := by simp @[simp] theorem inv_lt_top {x : ℝ≥0∞} : x⁻¹ < ∞ ↔ 0 < x := by simp only [lt_top_iff_ne_top, inv_ne_top, pos_iff_ne_zero] theorem div_lt_top {x y : ℝ≥0∞} (h1 : x ≠ ∞) (h2 : y ≠ 0) : x / y < ∞ := mul_lt_top h1 (inv_ne_top.mpr h2) @[simp] protected theorem inv_eq_zero : a⁻¹ = 0 ↔ a = ∞ := inv_top ▸ inv_inj protected theorem inv_ne_zero : a⁻¹ ≠ 0 ↔ a ≠ ∞ := by simp protected theorem div_pos (ha : a ≠ 0) (hb : b ≠ ∞) : 0 < a / b := ENNReal.mul_pos ha <| ENNReal.inv_ne_zero.2 hb protected theorem inv_mul_le_iff {x y z : ℝ≥0∞} (h1 : x ≠ 0) (h2 : x ≠ ∞) : x⁻¹ * y ≤ z ↔ y ≤ x * z := by rw [← mul_le_mul_left h1 h2, ← mul_assoc, ENNReal.mul_inv_cancel h1 h2, one_mul] protected theorem mul_inv_le_iff {x y z : ℝ≥0∞} (h1 : y ≠ 0) (h2 : y ≠ ∞) : x * y⁻¹ ≤ z ↔ x ≤ z * y := by rw [mul_comm, ENNReal.inv_mul_le_iff h1 h2, mul_comm] protected theorem div_le_iff {x y z : ℝ≥0∞} (h1 : y ≠ 0) (h2 : y ≠ ∞) : x / y ≤ z ↔ x ≤ z * y := by rw [div_eq_mul_inv, ENNReal.mul_inv_le_iff h1 h2] protected theorem div_le_iff' {x y z : ℝ≥0∞} (h1 : y ≠ 0) (h2 : y ≠ ∞) : x / y ≤ z ↔ x ≤ y * z := by rw [mul_comm, ENNReal.div_le_iff h1 h2] protected theorem mul_inv {a b : ℝ≥0∞} (ha : a ≠ 0 ∨ b ≠ ∞) (hb : a ≠ ∞ ∨ b ≠ 0) : (a * b)⁻¹ = a⁻¹ * b⁻¹ := by induction' b with b · replace ha : a ≠ 0 := ha.neg_resolve_right rfl simp [ha] induction' a with a · replace hb : b ≠ 0 := coe_ne_zero.1 (hb.neg_resolve_left rfl) simp [hb] by_cases h'a : a = 0 · simp only [h'a, top_mul, ENNReal.inv_zero, ENNReal.coe_ne_top, zero_mul, Ne, not_false_iff, ENNReal.coe_zero, ENNReal.inv_eq_zero] by_cases h'b : b = 0 · simp only [h'b, ENNReal.inv_zero, ENNReal.coe_ne_top, mul_top, Ne, not_false_iff, mul_zero, ENNReal.coe_zero, ENNReal.inv_eq_zero] rw [← ENNReal.coe_mul, ← ENNReal.coe_inv, ← ENNReal.coe_inv h'a, ← ENNReal.coe_inv h'b, ← ENNReal.coe_mul, mul_inv_rev, mul_comm] simp [h'a, h'b] protected theorem mul_div_mul_left (a b : ℝ≥0∞) (hc : c ≠ 0) (hc' : c ≠ ⊤) : c * a / (c * b) = a / b := by rw [div_eq_mul_inv, div_eq_mul_inv, ENNReal.mul_inv (Or.inl hc) (Or.inl hc'), mul_mul_mul_comm, ENNReal.mul_inv_cancel hc hc', one_mul] protected theorem mul_div_mul_right (a b : ℝ≥0∞) (hc : c ≠ 0) (hc' : c ≠ ⊤) : a * c / (b * c) = a / b := by rw [div_eq_mul_inv, div_eq_mul_inv, ENNReal.mul_inv (Or.inr hc') (Or.inr hc), mul_mul_mul_comm, ENNReal.mul_inv_cancel hc hc', mul_one] protected theorem sub_div (h : 0 < b → b < a → c ≠ 0) : (a - b) / c = a / c - b / c := by simp_rw [div_eq_mul_inv] exact ENNReal.sub_mul (by simpa using h) @[simp] protected theorem inv_pos : 0 < a⁻¹ ↔ a ≠ ∞ := pos_iff_ne_zero.trans ENNReal.inv_ne_zero theorem inv_strictAnti : StrictAnti (Inv.inv : ℝ≥0∞ → ℝ≥0∞) := by intro a b h lift a to ℝ≥0 using h.ne_top induction b; · simp rw [coe_lt_coe] at h rcases eq_or_ne a 0 with (rfl | ha); · simp [h] rw [← coe_inv h.ne_bot, ← coe_inv ha, coe_lt_coe] exact NNReal.inv_lt_inv ha h @[simp] protected theorem inv_lt_inv : a⁻¹ < b⁻¹ ↔ b < a := inv_strictAnti.lt_iff_lt theorem inv_lt_iff_inv_lt : a⁻¹ < b ↔ b⁻¹ < a := by simpa only [inv_inv] using @ENNReal.inv_lt_inv a b⁻¹ theorem lt_inv_iff_lt_inv : a < b⁻¹ ↔ b < a⁻¹ := by simpa only [inv_inv] using @ENNReal.inv_lt_inv a⁻¹ b @[simp] protected theorem inv_le_inv : a⁻¹ ≤ b⁻¹ ↔ b ≤ a := inv_strictAnti.le_iff_le theorem inv_le_iff_inv_le : a⁻¹ ≤ b ↔ b⁻¹ ≤ a := by simpa only [inv_inv] using @ENNReal.inv_le_inv a b⁻¹ theorem le_inv_iff_le_inv : a ≤ b⁻¹ ↔ b ≤ a⁻¹ := by simpa only [inv_inv] using @ENNReal.inv_le_inv a⁻¹ b @[gcongr] protected theorem inv_le_inv' (h : a ≤ b) : b⁻¹ ≤ a⁻¹ := ENNReal.inv_strictAnti.antitone h @[gcongr] protected theorem inv_lt_inv' (h : a < b) : b⁻¹ < a⁻¹ := ENNReal.inv_strictAnti h @[simp] protected theorem inv_le_one : a⁻¹ ≤ 1 ↔ 1 ≤ a := by rw [inv_le_iff_inv_le, inv_one] protected theorem one_le_inv : 1 ≤ a⁻¹ ↔ a ≤ 1 := by rw [le_inv_iff_le_inv, inv_one] @[simp] protected theorem inv_lt_one : a⁻¹ < 1 ↔ 1 < a := by rw [inv_lt_iff_inv_lt, inv_one] @[simp] protected theorem one_lt_inv : 1 < a⁻¹ ↔ a < 1 := by rw [lt_inv_iff_lt_inv, inv_one] /-- The inverse map `fun x ↦ x⁻¹` is an order isomorphism between `ℝ≥0∞` and its `OrderDual` -/ @[simps! apply] def _root_.OrderIso.invENNReal : ℝ≥0∞ ≃o ℝ≥0∞ᵒᵈ where map_rel_iff' := ENNReal.inv_le_inv toEquiv := (Equiv.inv ℝ≥0∞).trans OrderDual.toDual @[simp] theorem _root_.OrderIso.invENNReal_symm_apply (a : ℝ≥0∞ᵒᵈ) : OrderIso.invENNReal.symm a = (OrderDual.ofDual a)⁻¹ := rfl @[simp] theorem div_top : a / ∞ = 0 := by rw [div_eq_mul_inv, inv_top, mul_zero] -- Porting note: reordered 4 lemmas theorem top_div : ∞ / a = if a = ∞ then 0 else ∞ := by simp [div_eq_mul_inv, top_mul'] theorem top_div_of_ne_top (h : a ≠ ∞) : ∞ / a = ∞ := by simp [top_div, h] @[simp] theorem top_div_coe : ∞ / p = ∞ := top_div_of_ne_top coe_ne_top theorem top_div_of_lt_top (h : a < ∞) : ∞ / a = ∞ := top_div_of_ne_top h.ne @[simp] protected theorem zero_div : 0 / a = 0 := zero_mul a⁻¹ theorem div_eq_top : a / b = ∞ ↔ a ≠ 0 ∧ b = 0 ∨ a = ∞ ∧ b ≠ ∞ := by simp [div_eq_mul_inv, ENNReal.mul_eq_top] protected theorem le_div_iff_mul_le (h0 : b ≠ 0 ∨ c ≠ 0) (ht : b ≠ ∞ ∨ c ≠ ∞) : a ≤ c / b ↔ a * b ≤ c := by induction' b with b · lift c to ℝ≥0 using ht.neg_resolve_left rfl rw [div_top, nonpos_iff_eq_zero] rcases eq_or_ne a 0 with (rfl | ha) <;> simp [*] rcases eq_or_ne b 0 with (rfl | hb) · have hc : c ≠ 0 := h0.neg_resolve_left rfl simp [div_zero hc] · rw [← coe_ne_zero] at hb rw [← ENNReal.mul_le_mul_right hb coe_ne_top, ENNReal.div_mul_cancel hb coe_ne_top] protected theorem div_le_iff_le_mul (hb0 : b ≠ 0 ∨ c ≠ ∞) (hbt : b ≠ ∞ ∨ c ≠ 0) : a / b ≤ c ↔ a ≤ c * b := by suffices a * b⁻¹ ≤ c ↔ a ≤ c / b⁻¹ by simpa [div_eq_mul_inv] refine (ENNReal.le_div_iff_mul_le ?_ ?_).symm <;> simpa protected theorem lt_div_iff_mul_lt (hb0 : b ≠ 0 ∨ c ≠ ∞) (hbt : b ≠ ∞ ∨ c ≠ 0) : c < a / b ↔ c * b < a := lt_iff_lt_of_le_iff_le (ENNReal.div_le_iff_le_mul hb0 hbt) theorem div_le_of_le_mul (h : a ≤ b * c) : a / c ≤ b := by by_cases h0 : c = 0 · have : a = 0 := by simpa [h0] using h simp [*] by_cases hinf : c = ∞; · simp [hinf] exact (ENNReal.div_le_iff_le_mul (Or.inl h0) (Or.inl hinf)).2 h theorem div_le_of_le_mul' (h : a ≤ b * c) : a / b ≤ c := div_le_of_le_mul <| mul_comm b c ▸ h @[simp] protected theorem div_self_le_one : a / a ≤ 1 := div_le_of_le_mul <| by rw [one_mul] @[simp] protected lemma mul_inv_le_one (a : ℝ≥0∞) : a * a⁻¹ ≤ 1 := ENNReal.div_self_le_one @[simp] protected lemma inv_mul_le_one (a : ℝ≥0∞) : a⁻¹ * a ≤ 1 := by simp [mul_comm] @[simp] lemma mul_inv_ne_top (a : ℝ≥0∞) : a * a⁻¹ ≠ ⊤ := ne_top_of_le_ne_top one_ne_top a.mul_inv_le_one @[simp] lemma inv_mul_ne_top (a : ℝ≥0∞) : a⁻¹ * a ≠ ⊤ := by simp [mul_comm] theorem mul_le_of_le_div (h : a ≤ b / c) : a * c ≤ b := by rw [← inv_inv c] exact div_le_of_le_mul h theorem mul_le_of_le_div' (h : a ≤ b / c) : c * a ≤ b := mul_comm a c ▸ mul_le_of_le_div h protected theorem div_lt_iff (h0 : b ≠ 0 ∨ c ≠ 0) (ht : b ≠ ∞ ∨ c ≠ ∞) : c / b < a ↔ c < a * b := lt_iff_lt_of_le_iff_le <| ENNReal.le_div_iff_mul_le h0 ht theorem mul_lt_of_lt_div (h : a < b / c) : a * c < b := by contrapose! h exact ENNReal.div_le_of_le_mul h theorem mul_lt_of_lt_div' (h : a < b / c) : c * a < b := mul_comm a c ▸ mul_lt_of_lt_div h theorem div_lt_of_lt_mul (h : a < b * c) : a / c < b := mul_lt_of_lt_div <| by rwa [div_eq_mul_inv, inv_inv] theorem div_lt_of_lt_mul' (h : a < b * c) : a / b < c := div_lt_of_lt_mul <| by rwa [mul_comm] theorem inv_le_iff_le_mul (h₁ : b = ∞ → a ≠ 0) (h₂ : a = ∞ → b ≠ 0) : a⁻¹ ≤ b ↔ 1 ≤ a * b := by rw [← one_div, ENNReal.div_le_iff_le_mul, mul_comm] exacts [or_not_of_imp h₁, not_or_of_imp h₂] @[simp 900] theorem le_inv_iff_mul_le : a ≤ b⁻¹ ↔ a * b ≤ 1 := by rw [← one_div, ENNReal.le_div_iff_mul_le] <;> · right simp @[gcongr] protected theorem div_le_div (hab : a ≤ b) (hdc : d ≤ c) : a / c ≤ b / d := div_eq_mul_inv b d ▸ div_eq_mul_inv a c ▸ mul_le_mul' hab (ENNReal.inv_le_inv.mpr hdc) @[gcongr] protected theorem div_le_div_left (h : a ≤ b) (c : ℝ≥0∞) : c / b ≤ c / a := ENNReal.div_le_div le_rfl h @[gcongr] protected theorem div_le_div_right (h : a ≤ b) (c : ℝ≥0∞) : a / c ≤ b / c := ENNReal.div_le_div h le_rfl protected theorem eq_inv_of_mul_eq_one_left (h : a * b = 1) : a = b⁻¹ := by rw [← mul_one a, ← ENNReal.mul_inv_cancel (right_ne_zero_of_mul_eq_one h), ← mul_assoc, h, one_mul] rintro rfl simp [left_ne_zero_of_mul_eq_one h] at h theorem mul_le_iff_le_inv {a b r : ℝ≥0∞} (hr₀ : r ≠ 0) (hr₁ : r ≠ ∞) : r * a ≤ b ↔ a ≤ r⁻¹ * b := by rw [← @ENNReal.mul_le_mul_left _ a _ hr₀ hr₁, ← mul_assoc, ENNReal.mul_inv_cancel hr₀ hr₁, one_mul] instance : PosSMulStrictMono ℝ≥0 ℝ≥0∞ where elim _r hr _a _b hab := ENNReal.mul_lt_mul_left' (coe_pos.2 hr).ne' coe_ne_top hab instance : SMulPosMono ℝ≥0 ℝ≥0∞ where elim _r _ _a _b hab := mul_le_mul_right' (coe_le_coe.2 hab) _ theorem le_of_forall_nnreal_lt {x y : ℝ≥0∞} (h : ∀ r : ℝ≥0, ↑r < x → ↑r ≤ y) : x ≤ y := by refine le_of_forall_ge_of_dense fun r hr => ?_ lift r to ℝ≥0 using ne_top_of_lt hr exact h r hr theorem le_of_forall_pos_nnreal_lt {x y : ℝ≥0∞} (h : ∀ r : ℝ≥0, 0 < r → ↑r < x → ↑r ≤ y) : x ≤ y := le_of_forall_nnreal_lt fun r hr => (zero_le r).eq_or_lt.elim (fun h => h ▸ zero_le _) fun h0 => h r h0 hr theorem eq_top_of_forall_nnreal_le {x : ℝ≥0∞} (h : ∀ r : ℝ≥0, ↑r ≤ x) : x = ∞ := top_unique <| le_of_forall_nnreal_lt fun r _ => h r protected theorem add_div : (a + b) / c = a / c + b / c := right_distrib a b c⁻¹ protected theorem div_add_div_same {a b c : ℝ≥0∞} : a / c + b / c = (a + b) / c := ENNReal.add_div.symm protected theorem div_self (h0 : a ≠ 0) (hI : a ≠ ∞) : a / a = 1 := ENNReal.mul_inv_cancel h0 hI theorem mul_div_le : a * (b / a) ≤ b := mul_le_of_le_div' le_rfl theorem eq_div_iff (ha : a ≠ 0) (ha' : a ≠ ∞) : b = c / a ↔ a * b = c := ⟨fun h => by rw [h, ENNReal.mul_div_cancel' ha ha'], fun h => by rw [← h, mul_div_assoc, ENNReal.mul_div_cancel' ha ha']⟩ protected theorem div_eq_div_iff (ha : a ≠ 0) (ha' : a ≠ ∞) (hb : b ≠ 0) (hb' : b ≠ ∞) : c / b = d / a ↔ a * c = b * d := by rw [eq_div_iff ha ha'] conv_rhs => rw [eq_comm] rw [← eq_div_iff hb hb', mul_div_assoc, eq_comm] theorem div_eq_one_iff {a b : ℝ≥0∞} (hb₀ : b ≠ 0) (hb₁ : b ≠ ∞) : a / b = 1 ↔ a = b := ⟨fun h => by rw [← (eq_div_iff hb₀ hb₁).mp h.symm, mul_one], fun h => h.symm ▸ ENNReal.div_self hb₀ hb₁⟩ theorem inv_two_add_inv_two : (2 : ℝ≥0∞)⁻¹ + 2⁻¹ = 1 := by rw [← two_mul, ← div_eq_mul_inv, ENNReal.div_self two_ne_zero two_ne_top] theorem inv_three_add_inv_three : (3 : ℝ≥0∞)⁻¹ + 3⁻¹ + 3⁻¹ = 1 := calc (3 : ℝ≥0∞)⁻¹ + 3⁻¹ + 3⁻¹ = 3 * 3⁻¹ := by ring _ = 1 := ENNReal.mul_inv_cancel (Nat.cast_ne_zero.2 <| by decide) coe_ne_top @[simp] protected theorem add_halves (a : ℝ≥0∞) : a / 2 + a / 2 = a := by rw [div_eq_mul_inv, ← mul_add, inv_two_add_inv_two, mul_one] @[simp] theorem add_thirds (a : ℝ≥0∞) : a / 3 + a / 3 + a / 3 = a := by rw [div_eq_mul_inv, ← mul_add, ← mul_add, inv_three_add_inv_three, mul_one] @[simp] theorem div_eq_zero_iff : a / b = 0 ↔ a = 0 ∨ b = ∞ := by simp [div_eq_mul_inv] @[simp] theorem div_pos_iff : 0 < a / b ↔ a ≠ 0 ∧ b ≠ ∞ := by simp [pos_iff_ne_zero, not_or] protected lemma div_ne_zero : a / b ≠ 0 ↔ a ≠ 0 ∧ b ≠ ⊤ := by rw [← pos_iff_ne_zero, div_pos_iff] protected theorem half_pos (h : a ≠ 0) : 0 < a / 2 := by simp only [div_pos_iff, ne_eq, h, not_false_eq_true, two_ne_top, and_self] protected theorem one_half_lt_one : (2⁻¹ : ℝ≥0∞) < 1 := ENNReal.inv_lt_one.2 <| one_lt_two protected theorem half_lt_self (hz : a ≠ 0) (ht : a ≠ ∞) : a / 2 < a := by lift a to ℝ≥0 using ht rw [coe_ne_zero] at hz rw [← coe_two, ← coe_div, coe_lt_coe] exacts [NNReal.half_lt_self hz, two_ne_zero' _] protected theorem half_le_self : a / 2 ≤ a := le_add_self.trans_eq <| ENNReal.add_halves _ theorem sub_half (h : a ≠ ∞) : a - a / 2 = a / 2 := by lift a to ℝ≥0 using h exact sub_eq_of_add_eq (mul_ne_top coe_ne_top <| by simp) (ENNReal.add_halves a) @[simp] theorem one_sub_inv_two : (1 : ℝ≥0∞) - 2⁻¹ = 2⁻¹ := by simpa only [div_eq_mul_inv, one_mul] using sub_half one_ne_top /-- The birational order isomorphism between `ℝ≥0∞` and the unit interval `Set.Iic (1 : ℝ≥0∞)`. -/ @[simps! apply_coe] def orderIsoIicOneBirational : ℝ≥0∞ ≃o Iic (1 : ℝ≥0∞) := by refine StrictMono.orderIsoOfRightInverse (fun x => ⟨(x⁻¹ + 1)⁻¹, ENNReal.inv_le_one.2 <| le_add_self⟩) (fun x y hxy => ?_) (fun x => (x.1⁻¹ - 1)⁻¹) fun x => Subtype.ext ?_ · simpa only [Subtype.mk_lt_mk, ENNReal.inv_lt_inv, ENNReal.add_lt_add_iff_right one_ne_top] · have : (1 : ℝ≥0∞) ≤ x.1⁻¹ := ENNReal.one_le_inv.2 x.2 simp only [inv_inv, Subtype.coe_mk, tsub_add_cancel_of_le this] @[simp] theorem orderIsoIicOneBirational_symm_apply (x : Iic (1 : ℝ≥0∞)) : orderIsoIicOneBirational.symm x = (x.1⁻¹ - 1)⁻¹ := rfl /-- Order isomorphism between an initial interval in `ℝ≥0∞` and an initial interval in `ℝ≥0`. -/ @[simps! apply_coe] def orderIsoIicCoe (a : ℝ≥0) : Iic (a : ℝ≥0∞) ≃o Iic a := OrderIso.symm { toFun := fun x => ⟨x, coe_le_coe.2 x.2⟩ invFun := fun x => ⟨ENNReal.toNNReal x, coe_le_coe.1 <| coe_toNNReal_le_self.trans x.2⟩ left_inv := fun x => Subtype.ext <| toNNReal_coe right_inv := fun x => Subtype.ext <| coe_toNNReal (ne_top_of_le_ne_top coe_ne_top x.2) map_rel_iff' := fun {_ _} => by simp only [Equiv.coe_fn_mk, Subtype.mk_le_mk, coe_le_coe, Subtype.coe_le_coe] } @[simp] theorem orderIsoIicCoe_symm_apply_coe (a : ℝ≥0) (b : Iic a) : ((orderIsoIicCoe a).symm b : ℝ≥0∞) = b := rfl /-- An order isomorphism between the extended nonnegative real numbers and the unit interval. -/ def orderIsoUnitIntervalBirational : ℝ≥0∞ ≃o Icc (0 : ℝ) 1 := orderIsoIicOneBirational.trans <| (orderIsoIicCoe 1).trans <| (NNReal.orderIsoIccZeroCoe 1).symm @[simp] theorem orderIsoUnitIntervalBirational_apply_coe (x : ℝ≥0∞) : (orderIsoUnitIntervalBirational x : ℝ) = (x⁻¹ + 1)⁻¹.toReal := rfl theorem exists_inv_nat_lt {a : ℝ≥0∞} (h : a ≠ 0) : ∃ n : ℕ, (n : ℝ≥0∞)⁻¹ < a := inv_inv a ▸ by simp only [ENNReal.inv_lt_inv, ENNReal.exists_nat_gt (inv_ne_top.2 h)] theorem exists_nat_pos_mul_gt (ha : a ≠ 0) (hb : b ≠ ∞) : ∃ n > 0, b < (n : ℕ) * a := let ⟨n, hn⟩ := ENNReal.exists_nat_gt (div_lt_top hb ha).ne ⟨n, Nat.cast_pos.1 ((zero_le _).trans_lt hn), by rwa [← ENNReal.div_lt_iff (Or.inl ha) (Or.inr hb)]⟩ theorem exists_nat_mul_gt (ha : a ≠ 0) (hb : b ≠ ∞) : ∃ n : ℕ, b < n * a := (exists_nat_pos_mul_gt ha hb).imp fun _ => And.right theorem exists_nat_pos_inv_mul_lt (ha : a ≠ ∞) (hb : b ≠ 0) : ∃ n > 0, ((n : ℕ) : ℝ≥0∞)⁻¹ * a < b := by rcases exists_nat_pos_mul_gt hb ha with ⟨n, npos, hn⟩ use n, npos rw [← ENNReal.div_eq_inv_mul] exact div_lt_of_lt_mul' hn theorem exists_nnreal_pos_mul_lt (ha : a ≠ ∞) (hb : b ≠ 0) : ∃ n > 0, ↑(n : ℝ≥0) * a < b := by rcases exists_nat_pos_inv_mul_lt ha hb with ⟨n, npos : 0 < n, hn⟩ use (n : ℝ≥0)⁻¹ simp [*, npos.ne', zero_lt_one] theorem exists_inv_two_pow_lt (ha : a ≠ 0) : ∃ n : ℕ, 2⁻¹ ^ n < a := by rcases exists_inv_nat_lt ha with ⟨n, hn⟩ refine ⟨n, lt_trans ?_ hn⟩ rw [← ENNReal.inv_pow, ENNReal.inv_lt_inv] norm_cast exact n.lt_two_pow @[simp, norm_cast] theorem coe_zpow (hr : r ≠ 0) (n : ℤ) : (↑(r ^ n) : ℝ≥0∞) = (r : ℝ≥0∞) ^ n := by cases' n with n n · simp only [Int.ofNat_eq_coe, coe_pow, zpow_natCast] · have : r ^ n.succ ≠ 0 := pow_ne_zero (n + 1) hr simp only [zpow_negSucc, coe_inv this, coe_pow] theorem zpow_pos (ha : a ≠ 0) (h'a : a ≠ ∞) (n : ℤ) : 0 < a ^ n := by cases n · simpa using ENNReal.pow_pos ha.bot_lt _ · simp only [h'a, pow_eq_top_iff, zpow_negSucc, Ne, not_false, ENNReal.inv_pos, false_and, not_false_eq_true] theorem zpow_lt_top (ha : a ≠ 0) (h'a : a ≠ ∞) (n : ℤ) : a ^ n < ∞ := by cases n · simpa using ENNReal.pow_lt_top h'a.lt_top _ · simp only [ENNReal.pow_pos ha.bot_lt, zpow_negSucc, inv_lt_top] theorem exists_mem_Ico_zpow {x y : ℝ≥0∞} (hx : x ≠ 0) (h'x : x ≠ ∞) (hy : 1 < y) (h'y : y ≠ ⊤) : ∃ n : ℤ, x ∈ Ico (y ^ n) (y ^ (n + 1)) := by lift x to ℝ≥0 using h'x lift y to ℝ≥0 using h'y have A : y ≠ 0 := by simpa only [Ne, coe_eq_zero] using (zero_lt_one.trans hy).ne' obtain ⟨n, hn, h'n⟩ : ∃ n : ℤ, y ^ n ≤ x ∧ x < y ^ (n + 1) := by refine NNReal.exists_mem_Ico_zpow ?_ (one_lt_coe_iff.1 hy) simpa only [Ne, coe_eq_zero] using hx refine ⟨n, ?_, ?_⟩ · rwa [← ENNReal.coe_zpow A, ENNReal.coe_le_coe] · rwa [← ENNReal.coe_zpow A, ENNReal.coe_lt_coe] theorem exists_mem_Ioc_zpow {x y : ℝ≥0∞} (hx : x ≠ 0) (h'x : x ≠ ∞) (hy : 1 < y) (h'y : y ≠ ⊤) : ∃ n : ℤ, x ∈ Ioc (y ^ n) (y ^ (n + 1)) := by lift x to ℝ≥0 using h'x lift y to ℝ≥0 using h'y have A : y ≠ 0 := by simpa only [Ne, coe_eq_zero] using (zero_lt_one.trans hy).ne' obtain ⟨n, hn, h'n⟩ : ∃ n : ℤ, y ^ n < x ∧ x ≤ y ^ (n + 1) := by refine NNReal.exists_mem_Ioc_zpow ?_ (one_lt_coe_iff.1 hy) simpa only [Ne, coe_eq_zero] using hx refine ⟨n, ?_, ?_⟩ · rwa [← ENNReal.coe_zpow A, ENNReal.coe_lt_coe] · rwa [← ENNReal.coe_zpow A, ENNReal.coe_le_coe] theorem Ioo_zero_top_eq_iUnion_Ico_zpow {y : ℝ≥0∞} (hy : 1 < y) (h'y : y ≠ ⊤) : Ioo (0 : ℝ≥0∞) (∞ : ℝ≥0∞) = ⋃ n : ℤ, Ico (y ^ n) (y ^ (n + 1)) := by ext x simp only [mem_iUnion, mem_Ioo, mem_Ico] constructor · rintro ⟨hx, h'x⟩ exact exists_mem_Ico_zpow hx.ne' h'x.ne hy h'y · rintro ⟨n, hn, h'n⟩ constructor · apply lt_of_lt_of_le _ hn exact ENNReal.zpow_pos (zero_lt_one.trans hy).ne' h'y _ · apply lt_trans h'n _ exact ENNReal.zpow_lt_top (zero_lt_one.trans hy).ne' h'y _ @[gcongr] theorem zpow_le_of_le {x : ℝ≥0∞} (hx : 1 ≤ x) {a b : ℤ} (h : a ≤ b) : x ^ a ≤ x ^ b := by induction' a with a a <;> induction' b with b b · simp only [Int.ofNat_eq_coe, zpow_natCast] exact pow_le_pow_right hx (Int.le_of_ofNat_le_ofNat h) · apply absurd h (not_le_of_gt _) exact lt_of_lt_of_le (Int.negSucc_lt_zero _) (Int.ofNat_nonneg _) · simp only [zpow_negSucc, Int.ofNat_eq_coe, zpow_natCast] refine (ENNReal.inv_le_one.2 ?_).trans ?_ <;> exact one_le_pow_of_one_le' hx _ · simp only [zpow_negSucc, ENNReal.inv_le_inv] apply pow_le_pow_right hx simpa only [← Int.ofNat_le, neg_le_neg_iff, Int.ofNat_add, Int.ofNat_one, Int.negSucc_eq] using h theorem monotone_zpow {x : ℝ≥0∞} (hx : 1 ≤ x) : Monotone ((x ^ ·) : ℤ → ℝ≥0∞) := fun _ _ h => zpow_le_of_le hx h protected theorem zpow_add {x : ℝ≥0∞} (hx : x ≠ 0) (h'x : x ≠ ∞) (m n : ℤ) : x ^ (m + n) = x ^ m * x ^ n := by lift x to ℝ≥0 using h'x replace hx : x ≠ 0 := by simpa only [Ne, coe_eq_zero] using hx simp only [← coe_zpow hx, zpow_add₀ hx, coe_mul] protected theorem zpow_neg {x : ℝ≥0∞} (x_ne_zero : x ≠ 0) (x_ne_top : x ≠ ⊤) (m : ℤ) : x ^ (-m) = (x ^ m)⁻¹ := ENNReal.eq_inv_of_mul_eq_one_left (by simp [← ENNReal.zpow_add x_ne_zero x_ne_top]) protected theorem zpow_sub {x : ℝ≥0∞} (x_ne_zero : x ≠ 0) (x_ne_top : x ≠ ⊤) (m n : ℤ) : x ^ (m - n) = (x ^ m) * (x ^ n)⁻¹ := by rw [sub_eq_add_neg, ENNReal.zpow_add x_ne_zero x_ne_top, ENNReal.zpow_neg x_ne_zero x_ne_top n] end Inv end ENNReal
Data\ENNReal\Operations.lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Yury Kudryashov -/ import Mathlib.Algebra.BigOperators.WithTop import Mathlib.Algebra.GroupWithZero.Divisibility import Mathlib.Data.ENNReal.Basic /-! # Properties of addition, multiplication and subtraction on extended non-negative real numbers In this file we prove elementary properties of algebraic operations on `ℝ≥0∞`, including addition, multiplication, natural powers and truncated subtraction, as well as how these interact with the order structure on `ℝ≥0∞`. Notably excluded from this list are inversion and division, the definitions and properties of which can be found in `Data.ENNReal.Inv`. Note: the definitions of the operations included in this file can be found in `Data.ENNReal.Basic`. -/ open Set NNReal ENNReal namespace ENNReal variable {a b c d : ℝ≥0∞} {r p q : ℝ≥0} section Mul -- Porting note (#11215): TODO: generalize to `WithTop` @[mono, gcongr] theorem mul_lt_mul (ac : a < c) (bd : b < d) : a * b < c * d := by rcases lt_iff_exists_nnreal_btwn.1 ac with ⟨a', aa', a'c⟩ lift a to ℝ≥0 using ne_top_of_lt aa' rcases lt_iff_exists_nnreal_btwn.1 bd with ⟨b', bb', b'd⟩ lift b to ℝ≥0 using ne_top_of_lt bb' norm_cast at * calc ↑(a * b) < ↑(a' * b') := coe_lt_coe.2 (mul_lt_mul₀ aa' bb') _ ≤ c * d := mul_le_mul' a'c.le b'd.le -- TODO: generalize to `CovariantClass α α (· * ·) (· ≤ ·)` theorem mul_left_mono : Monotone (a * ·) := fun _ _ => mul_le_mul' le_rfl -- TODO: generalize to `CovariantClass α α (swap (· * ·)) (· ≤ ·)` theorem mul_right_mono : Monotone (· * a) := fun _ _ h => mul_le_mul' h le_rfl -- Porting note (#11215): TODO: generalize to `WithTop` theorem pow_strictMono : ∀ {n : ℕ}, n ≠ 0 → StrictMono fun x : ℝ≥0∞ => x ^ n | 0, h => absurd rfl h | 1, _ => by simpa only [pow_one] using strictMono_id | n + 2, _ => fun x y h ↦ by simp_rw [pow_succ _ (n + 1)]; exact mul_lt_mul (pow_strictMono n.succ_ne_zero h) h @[gcongr] protected theorem pow_lt_pow_left (h : a < b) {n : ℕ} (hn : n ≠ 0) : a ^ n < b ^ n := ENNReal.pow_strictMono hn h theorem max_mul : max a b * c = max (a * c) (b * c) := mul_right_mono.map_max theorem mul_max : a * max b c = max (a * b) (a * c) := mul_left_mono.map_max -- Porting note (#11215): TODO: generalize to `WithTop` theorem mul_left_strictMono (h0 : a ≠ 0) (hinf : a ≠ ∞) : StrictMono (a * ·) := by lift a to ℝ≥0 using hinf rw [coe_ne_zero] at h0 intro x y h contrapose! h simpa only [← mul_assoc, ← coe_mul, inv_mul_cancel h0, coe_one, one_mul] using mul_le_mul_left' h (↑a⁻¹) @[gcongr] protected theorem mul_lt_mul_left' (h0 : a ≠ 0) (hinf : a ≠ ⊤) (bc : b < c) : a * b < a * c := ENNReal.mul_left_strictMono h0 hinf bc @[gcongr] protected theorem mul_lt_mul_right' (h0 : a ≠ 0) (hinf : a ≠ ⊤) (bc : b < c) : b * a < c * a := mul_comm b a ▸ mul_comm c a ▸ ENNReal.mul_left_strictMono h0 hinf bc -- Porting note (#11215): TODO: generalize to `WithTop` theorem mul_eq_mul_left (h0 : a ≠ 0) (hinf : a ≠ ∞) : a * b = a * c ↔ b = c := (mul_left_strictMono h0 hinf).injective.eq_iff -- Porting note (#11215): TODO: generalize to `WithTop` theorem mul_eq_mul_right : c ≠ 0 → c ≠ ∞ → (a * c = b * c ↔ a = b) := mul_comm c a ▸ mul_comm c b ▸ mul_eq_mul_left -- Porting note (#11215): TODO: generalize to `WithTop` theorem mul_le_mul_left (h0 : a ≠ 0) (hinf : a ≠ ∞) : a * b ≤ a * c ↔ b ≤ c := (mul_left_strictMono h0 hinf).le_iff_le -- Porting note (#11215): TODO: generalize to `WithTop` theorem mul_le_mul_right : c ≠ 0 → c ≠ ∞ → (a * c ≤ b * c ↔ a ≤ b) := mul_comm c a ▸ mul_comm c b ▸ mul_le_mul_left -- Porting note (#11215): TODO: generalize to `WithTop` theorem mul_lt_mul_left (h0 : a ≠ 0) (hinf : a ≠ ∞) : a * b < a * c ↔ b < c := (mul_left_strictMono h0 hinf).lt_iff_lt -- Porting note (#11215): TODO: generalize to `WithTop` theorem mul_lt_mul_right : c ≠ 0 → c ≠ ∞ → (a * c < b * c ↔ a < b) := mul_comm c a ▸ mul_comm c b ▸ mul_lt_mul_left end Mul section OperationsAndOrder protected theorem pow_pos : 0 < a → ∀ n : ℕ, 0 < a ^ n := CanonicallyOrderedCommSemiring.pow_pos protected theorem pow_ne_zero : a ≠ 0 → ∀ n : ℕ, a ^ n ≠ 0 := by simpa only [pos_iff_ne_zero] using ENNReal.pow_pos theorem not_lt_zero : ¬a < 0 := by simp protected theorem le_of_add_le_add_left : a ≠ ∞ → a + b ≤ a + c → b ≤ c := WithTop.le_of_add_le_add_left protected theorem le_of_add_le_add_right : a ≠ ∞ → b + a ≤ c + a → b ≤ c := WithTop.le_of_add_le_add_right @[gcongr] protected theorem add_lt_add_left : a ≠ ∞ → b < c → a + b < a + c := WithTop.add_lt_add_left @[gcongr] protected theorem add_lt_add_right : a ≠ ∞ → b < c → b + a < c + a := WithTop.add_lt_add_right protected theorem add_le_add_iff_left : a ≠ ∞ → (a + b ≤ a + c ↔ b ≤ c) := WithTop.add_le_add_iff_left protected theorem add_le_add_iff_right : a ≠ ∞ → (b + a ≤ c + a ↔ b ≤ c) := WithTop.add_le_add_iff_right protected theorem add_lt_add_iff_left : a ≠ ∞ → (a + b < a + c ↔ b < c) := WithTop.add_lt_add_iff_left protected theorem add_lt_add_iff_right : a ≠ ∞ → (b + a < c + a ↔ b < c) := WithTop.add_lt_add_iff_right protected theorem add_lt_add_of_le_of_lt : a ≠ ∞ → a ≤ b → c < d → a + c < b + d := WithTop.add_lt_add_of_le_of_lt protected theorem add_lt_add_of_lt_of_le : c ≠ ∞ → a < b → c ≤ d → a + c < b + d := WithTop.add_lt_add_of_lt_of_le instance contravariantClass_add_lt : ContravariantClass ℝ≥0∞ ℝ≥0∞ (· + ·) (· < ·) := WithTop.contravariantClass_add_lt theorem lt_add_right (ha : a ≠ ∞) (hb : b ≠ 0) : a < a + b := by rwa [← pos_iff_ne_zero, ← ENNReal.add_lt_add_iff_left ha, add_zero] at hb end OperationsAndOrder section OperationsAndInfty variable {α : Type*} @[simp] theorem add_eq_top : a + b = ∞ ↔ a = ∞ ∨ b = ∞ := WithTop.add_eq_top @[simp] theorem add_lt_top : a + b < ∞ ↔ a < ∞ ∧ b < ∞ := WithTop.add_lt_top theorem toNNReal_add {r₁ r₂ : ℝ≥0∞} (h₁ : r₁ ≠ ∞) (h₂ : r₂ ≠ ∞) : (r₁ + r₂).toNNReal = r₁.toNNReal + r₂.toNNReal := by lift r₁ to ℝ≥0 using h₁ lift r₂ to ℝ≥0 using h₂ rfl theorem not_lt_top {x : ℝ≥0∞} : ¬x < ∞ ↔ x = ∞ := by rw [lt_top_iff_ne_top, Classical.not_not] theorem add_ne_top : a + b ≠ ∞ ↔ a ≠ ∞ ∧ b ≠ ∞ := by simpa only [lt_top_iff_ne_top] using add_lt_top theorem mul_top' : a * ∞ = if a = 0 then 0 else ∞ := by convert WithTop.mul_top' a -- Porting note: added because `simp` no longer uses `WithTop` lemmas for `ℝ≥0∞` @[simp] theorem mul_top (h : a ≠ 0) : a * ∞ = ∞ := WithTop.mul_top h theorem top_mul' : ∞ * a = if a = 0 then 0 else ∞ := by convert WithTop.top_mul' a -- Porting note: added because `simp` no longer uses `WithTop` lemmas for `ℝ≥0∞` @[simp] theorem top_mul (h : a ≠ 0) : ∞ * a = ∞ := WithTop.top_mul h theorem top_mul_top : ∞ * ∞ = ∞ := WithTop.top_mul_top -- Porting note (#11215): TODO: assume `n ≠ 0` instead of `0 < n` theorem top_pow {n : ℕ} (n_pos : 0 < n) : (∞ : ℝ≥0∞) ^ n = ∞ := WithTop.top_pow n_pos theorem mul_eq_top : a * b = ∞ ↔ a ≠ 0 ∧ b = ∞ ∨ a = ∞ ∧ b ≠ 0 := WithTop.mul_eq_top_iff theorem mul_lt_top : a ≠ ∞ → b ≠ ∞ → a * b < ∞ := WithTop.mul_lt_top theorem mul_ne_top : a ≠ ∞ → b ≠ ∞ → a * b ≠ ∞ := by simpa only [lt_top_iff_ne_top] using mul_lt_top theorem lt_top_of_mul_ne_top_left (h : a * b ≠ ∞) (hb : b ≠ 0) : a < ∞ := lt_top_iff_ne_top.2 fun ha => h <| mul_eq_top.2 (Or.inr ⟨ha, hb⟩) theorem lt_top_of_mul_ne_top_right (h : a * b ≠ ∞) (ha : a ≠ 0) : b < ∞ := lt_top_of_mul_ne_top_left (by rwa [mul_comm]) ha theorem mul_lt_top_iff {a b : ℝ≥0∞} : a * b < ∞ ↔ a < ∞ ∧ b < ∞ ∨ a = 0 ∨ b = 0 := by constructor · intro h rw [← or_assoc, or_iff_not_imp_right, or_iff_not_imp_right] intro hb ha exact ⟨lt_top_of_mul_ne_top_left h.ne hb, lt_top_of_mul_ne_top_right h.ne ha⟩ · rintro (⟨ha, hb⟩ | rfl | rfl) <;> [exact mul_lt_top ha.ne hb.ne; simp; simp] theorem mul_self_lt_top_iff {a : ℝ≥0∞} : a * a < ⊤ ↔ a < ⊤ := by rw [ENNReal.mul_lt_top_iff, and_self, or_self, or_iff_left_iff_imp] rintro rfl exact zero_lt_top theorem mul_pos_iff : 0 < a * b ↔ 0 < a ∧ 0 < b := CanonicallyOrderedCommSemiring.mul_pos theorem mul_pos (ha : a ≠ 0) (hb : b ≠ 0) : 0 < a * b := mul_pos_iff.2 ⟨pos_iff_ne_zero.2 ha, pos_iff_ne_zero.2 hb⟩ -- Porting note (#11215): TODO: generalize to `WithTop` @[simp] theorem pow_eq_top_iff {n : ℕ} : a ^ n = ∞ ↔ a = ∞ ∧ n ≠ 0 := by rcases n.eq_zero_or_pos with rfl | (hn : 0 < n) · simp · induction a · simp only [Ne, hn.ne', top_pow hn, not_false_eq_true, and_self] · simp only [← coe_pow, coe_ne_top, false_and] theorem pow_eq_top (n : ℕ) (h : a ^ n = ∞) : a = ∞ := (pow_eq_top_iff.1 h).1 theorem pow_ne_top (h : a ≠ ∞) {n : ℕ} : a ^ n ≠ ∞ := mt (pow_eq_top n) h theorem pow_lt_top : a < ∞ → ∀ n : ℕ, a ^ n < ∞ := by simpa only [lt_top_iff_ne_top] using pow_ne_top @[simp, norm_cast] theorem coe_finset_sum {s : Finset α} {f : α → ℝ≥0} : ↑(∑ a ∈ s, f a) = ∑ a ∈ s, (f a : ℝ≥0∞) := map_sum ofNNRealHom f s @[simp, norm_cast] theorem coe_finset_prod {s : Finset α} {f : α → ℝ≥0} : ↑(∏ a ∈ s, f a) = ∏ a ∈ s, (f a : ℝ≥0∞) := map_prod ofNNRealHom f s end OperationsAndInfty -- Porting note (#11215): TODO: generalize to `WithTop` @[gcongr] theorem add_lt_add (ac : a < c) (bd : b < d) : a + b < c + d := by lift a to ℝ≥0 using ac.ne_top lift b to ℝ≥0 using bd.ne_top cases c; · simp cases d; · simp simp only [← coe_add, some_eq_coe, coe_lt_coe] at * exact add_lt_add ac bd section Cancel -- Porting note (#11215): TODO: generalize to `WithTop` /-- An element `a` is `AddLECancellable` if `a + b ≤ a + c` implies `b ≤ c` for all `b` and `c`. This is true in `ℝ≥0∞` for all elements except `∞`. -/ theorem addLECancellable_iff_ne {a : ℝ≥0∞} : AddLECancellable a ↔ a ≠ ∞ := by constructor · rintro h rfl refine zero_lt_one.not_le (h ?_) simp · rintro h b c hbc apply ENNReal.le_of_add_le_add_left h hbc /-- This lemma has an abbreviated name because it is used frequently. -/ theorem cancel_of_ne {a : ℝ≥0∞} (h : a ≠ ∞) : AddLECancellable a := addLECancellable_iff_ne.mpr h /-- This lemma has an abbreviated name because it is used frequently. -/ theorem cancel_of_lt {a : ℝ≥0∞} (h : a < ∞) : AddLECancellable a := cancel_of_ne h.ne /-- This lemma has an abbreviated name because it is used frequently. -/ theorem cancel_of_lt' {a b : ℝ≥0∞} (h : a < b) : AddLECancellable a := cancel_of_ne h.ne_top /-- This lemma has an abbreviated name because it is used frequently. -/ theorem cancel_coe {a : ℝ≥0} : AddLECancellable (a : ℝ≥0∞) := cancel_of_ne coe_ne_top theorem add_right_inj (h : a ≠ ∞) : a + b = a + c ↔ b = c := (cancel_of_ne h).inj theorem add_left_inj (h : a ≠ ∞) : b + a = c + a ↔ b = c := (cancel_of_ne h).inj_left end Cancel section Sub theorem sub_eq_sInf {a b : ℝ≥0∞} : a - b = sInf { d | a ≤ d + b } := le_antisymm (le_sInf fun _ h => tsub_le_iff_right.mpr h) <| sInf_le <| mem_setOf.2 le_tsub_add /-- This is a special case of `WithTop.coe_sub` in the `ENNReal` namespace -/ @[simp] theorem coe_sub : (↑(r - p) : ℝ≥0∞) = ↑r - ↑p := WithTop.coe_sub /-- This is a special case of `WithTop.top_sub_coe` in the `ENNReal` namespace -/ @[simp] theorem top_sub_coe : ∞ - ↑r = ∞ := WithTop.top_sub_coe /-- This is a special case of `WithTop.sub_top` in the `ENNReal` namespace -/ theorem sub_top : a - ∞ = 0 := WithTop.sub_top -- Porting note: added `@[simp]` @[simp] theorem sub_eq_top_iff : a - b = ∞ ↔ a = ∞ ∧ b ≠ ∞ := WithTop.sub_eq_top_iff theorem sub_ne_top (ha : a ≠ ∞) : a - b ≠ ∞ := mt sub_eq_top_iff.mp <| mt And.left ha @[simp, norm_cast] theorem natCast_sub (m n : ℕ) : ↑(m - n) = (m - n : ℝ≥0∞) := by rw [← coe_natCast, Nat.cast_tsub, coe_sub, coe_natCast, coe_natCast] @[deprecated (since := "2024-04-17")] alias nat_cast_sub := natCast_sub protected theorem sub_eq_of_eq_add (hb : b ≠ ∞) : a = c + b → a - b = c := (cancel_of_ne hb).tsub_eq_of_eq_add protected theorem eq_sub_of_add_eq (hc : c ≠ ∞) : a + c = b → a = b - c := (cancel_of_ne hc).eq_tsub_of_add_eq protected theorem sub_eq_of_eq_add_rev (hb : b ≠ ∞) : a = b + c → a - b = c := (cancel_of_ne hb).tsub_eq_of_eq_add_rev theorem sub_eq_of_add_eq (hb : b ≠ ∞) (hc : a + b = c) : c - b = a := ENNReal.sub_eq_of_eq_add hb hc.symm @[simp] protected theorem add_sub_cancel_left (ha : a ≠ ∞) : a + b - a = b := (cancel_of_ne ha).add_tsub_cancel_left @[simp] protected theorem add_sub_cancel_right (hb : b ≠ ∞) : a + b - b = a := (cancel_of_ne hb).add_tsub_cancel_right protected theorem sub_add_eq_add_sub (hab : b ≤ a) (b_ne_top : b ≠ ∞) : a - b + c = a + c - b := by by_cases c_top : c = ∞ · simpa [c_top] using ENNReal.eq_sub_of_add_eq b_ne_top rfl refine (sub_eq_of_add_eq b_ne_top ?_).symm simp only [add_assoc, add_comm c b] simpa only [← add_assoc] using (add_left_inj c_top).mpr <| tsub_add_cancel_of_le hab protected theorem lt_add_of_sub_lt_left (h : a ≠ ∞ ∨ b ≠ ∞) : a - b < c → a < b + c := by obtain rfl | hb := eq_or_ne b ∞ · rw [top_add, lt_top_iff_ne_top] exact fun _ => h.resolve_right (Classical.not_not.2 rfl) · exact (cancel_of_ne hb).lt_add_of_tsub_lt_left protected theorem lt_add_of_sub_lt_right (h : a ≠ ∞ ∨ c ≠ ∞) : a - c < b → a < b + c := add_comm c b ▸ ENNReal.lt_add_of_sub_lt_left h theorem le_sub_of_add_le_left (ha : a ≠ ∞) : a + b ≤ c → b ≤ c - a := (cancel_of_ne ha).le_tsub_of_add_le_left theorem le_sub_of_add_le_right (hb : b ≠ ∞) : a + b ≤ c → a ≤ c - b := (cancel_of_ne hb).le_tsub_of_add_le_right protected theorem sub_lt_of_lt_add (hac : c ≤ a) (h : a < b + c) : a - c < b := ((cancel_of_lt' <| hac.trans_lt h).tsub_lt_iff_right hac).mpr h protected theorem sub_lt_iff_lt_right (hb : b ≠ ∞) (hab : b ≤ a) : a - b < c ↔ a < c + b := (cancel_of_ne hb).tsub_lt_iff_right hab protected theorem sub_lt_self (ha : a ≠ ∞) (ha₀ : a ≠ 0) (hb : b ≠ 0) : a - b < a := (cancel_of_ne ha).tsub_lt_self (pos_iff_ne_zero.2 ha₀) (pos_iff_ne_zero.2 hb) protected theorem sub_lt_self_iff (ha : a ≠ ∞) : a - b < a ↔ 0 < a ∧ 0 < b := (cancel_of_ne ha).tsub_lt_self_iff theorem sub_lt_of_sub_lt (h₂ : c ≤ a) (h₃ : a ≠ ∞ ∨ b ≠ ∞) (h₁ : a - b < c) : a - c < b := ENNReal.sub_lt_of_lt_add h₂ (add_comm c b ▸ ENNReal.lt_add_of_sub_lt_right h₃ h₁) theorem sub_sub_cancel (h : a ≠ ∞) (h2 : b ≤ a) : a - (a - b) = b := (cancel_of_ne <| sub_ne_top h).tsub_tsub_cancel_of_le h2 theorem sub_right_inj {a b c : ℝ≥0∞} (ha : a ≠ ∞) (hb : b ≤ a) (hc : c ≤ a) : a - b = a - c ↔ b = c := (cancel_of_ne ha).tsub_right_inj (cancel_of_ne <| ne_top_of_le_ne_top ha hb) (cancel_of_ne <| ne_top_of_le_ne_top ha hc) hb hc theorem sub_mul (h : 0 < b → b < a → c ≠ ∞) : (a - b) * c = a * c - b * c := by rcases le_or_lt a b with hab | hab; · simp [hab, mul_right_mono hab] rcases eq_or_lt_of_le (zero_le b) with (rfl | hb); · simp exact (cancel_of_ne <| mul_ne_top hab.ne_top (h hb hab)).tsub_mul theorem mul_sub (h : 0 < c → c < b → a ≠ ∞) : a * (b - c) = a * b - a * c := by simp only [mul_comm a] exact sub_mul h theorem sub_le_sub_iff_left (h : c ≤ a) (h' : a ≠ ∞) : (a - b ≤ a - c) ↔ c ≤ b := (cancel_of_ne h').tsub_le_tsub_iff_left (cancel_of_ne (ne_top_of_le_ne_top h' h)) h end Sub section Sum open Finset variable {α : Type*} /-- A product of finite numbers is still finite -/ theorem prod_lt_top {s : Finset α} {f : α → ℝ≥0∞} (h : ∀ a ∈ s, f a ≠ ∞) : ∏ a ∈ s, f a < ∞ := WithTop.prod_lt_top h /-- A sum of finite numbers is still finite -/ theorem sum_lt_top {s : Finset α} {f : α → ℝ≥0∞} (h : ∀ a ∈ s, f a ≠ ∞) : ∑ a ∈ s, f a < ∞ := WithTop.sum_lt_top h /-- A sum of finite numbers is still finite -/ theorem sum_lt_top_iff {s : Finset α} {f : α → ℝ≥0∞} : ∑ a ∈ s, f a < ∞ ↔ ∀ a ∈ s, f a < ∞ := WithTop.sum_lt_top_iff /-- A sum of numbers is infinite iff one of them is infinite -/ theorem sum_eq_top_iff {s : Finset α} {f : α → ℝ≥0∞} : ∑ x ∈ s, f x = ∞ ↔ ∃ a ∈ s, f a = ∞ := WithTop.sum_eq_top_iff theorem lt_top_of_sum_ne_top {s : Finset α} {f : α → ℝ≥0∞} (h : ∑ x ∈ s, f x ≠ ∞) {a : α} (ha : a ∈ s) : f a < ∞ := sum_lt_top_iff.1 h.lt_top a ha /-- Seeing `ℝ≥0∞` as `ℝ≥0` does not change their sum, unless one of the `ℝ≥0∞` is infinity -/ theorem toNNReal_sum {s : Finset α} {f : α → ℝ≥0∞} (hf : ∀ a ∈ s, f a ≠ ∞) : ENNReal.toNNReal (∑ a ∈ s, f a) = ∑ a ∈ s, ENNReal.toNNReal (f a) := by rw [← coe_inj, coe_toNNReal, coe_finset_sum, sum_congr rfl] · intro x hx exact (coe_toNNReal (hf x hx)).symm · exact (sum_lt_top hf).ne /-- seeing `ℝ≥0∞` as `Real` does not change their sum, unless one of the `ℝ≥0∞` is infinity -/ theorem toReal_sum {s : Finset α} {f : α → ℝ≥0∞} (hf : ∀ a ∈ s, f a ≠ ∞) : ENNReal.toReal (∑ a ∈ s, f a) = ∑ a ∈ s, ENNReal.toReal (f a) := by rw [ENNReal.toReal, toNNReal_sum hf, NNReal.coe_sum] rfl theorem ofReal_sum_of_nonneg {s : Finset α} {f : α → ℝ} (hf : ∀ i, i ∈ s → 0 ≤ f i) : ENNReal.ofReal (∑ i ∈ s, f i) = ∑ i ∈ s, ENNReal.ofReal (f i) := by simp_rw [ENNReal.ofReal, ← coe_finset_sum, coe_inj] exact Real.toNNReal_sum_of_nonneg hf theorem sum_lt_sum_of_nonempty {s : Finset α} (hs : s.Nonempty) {f g : α → ℝ≥0∞} (Hlt : ∀ i ∈ s, f i < g i) : ∑ i ∈ s, f i < ∑ i ∈ s, g i := by induction hs using Finset.Nonempty.cons_induction with | singleton => simp [Hlt _ (Finset.mem_singleton_self _)] | cons _ _ _ _ ih => simp only [Finset.sum_cons, forall_mem_cons] at Hlt ⊢ exact ENNReal.add_lt_add Hlt.1 (ih Hlt.2) theorem exists_le_of_sum_le {s : Finset α} (hs : s.Nonempty) {f g : α → ℝ≥0∞} (Hle : ∑ i ∈ s, f i ≤ ∑ i ∈ s, g i) : ∃ i ∈ s, f i ≤ g i := by contrapose! Hle apply ENNReal.sum_lt_sum_of_nonempty hs Hle end Sum section Interval variable {x y z : ℝ≥0∞} {ε ε₁ ε₂ : ℝ≥0∞} {s : Set ℝ≥0∞} protected theorem Ico_eq_Iio : Ico 0 y = Iio y := Ico_bot theorem mem_Iio_self_add : x ≠ ∞ → ε ≠ 0 → x ∈ Iio (x + ε) := fun xt ε0 => lt_add_right xt ε0 theorem mem_Ioo_self_sub_add : x ≠ ∞ → x ≠ 0 → ε₁ ≠ 0 → ε₂ ≠ 0 → x ∈ Ioo (x - ε₁) (x + ε₂) := fun xt x0 ε0 ε0' => ⟨ENNReal.sub_lt_self xt x0 ε0, lt_add_right xt ε0'⟩ end Interval -- TODO: generalize some of these to `WithTop α` section Actions /-- A `MulAction` over `ℝ≥0∞` restricts to a `MulAction` over `ℝ≥0`. -/ noncomputable instance {M : Type*} [MulAction ℝ≥0∞ M] : MulAction ℝ≥0 M := MulAction.compHom M ofNNRealHom.toMonoidHom theorem smul_def {M : Type*} [MulAction ℝ≥0∞ M] (c : ℝ≥0) (x : M) : c • x = (c : ℝ≥0∞) • x := rfl instance {M N : Type*} [MulAction ℝ≥0∞ M] [MulAction ℝ≥0∞ N] [SMul M N] [IsScalarTower ℝ≥0∞ M N] : IsScalarTower ℝ≥0 M N where smul_assoc r := (smul_assoc (r : ℝ≥0∞) : _) instance smulCommClass_left {M N : Type*} [MulAction ℝ≥0∞ N] [SMul M N] [SMulCommClass ℝ≥0∞ M N] : SMulCommClass ℝ≥0 M N where smul_comm r := (smul_comm (r : ℝ≥0∞) : _) instance smulCommClass_right {M N : Type*} [MulAction ℝ≥0∞ N] [SMul M N] [SMulCommClass M ℝ≥0∞ N] : SMulCommClass M ℝ≥0 N where smul_comm m r := (smul_comm m (r : ℝ≥0∞) : _) /-- A `DistribMulAction` over `ℝ≥0∞` restricts to a `DistribMulAction` over `ℝ≥0`. -/ noncomputable instance {M : Type*} [AddMonoid M] [DistribMulAction ℝ≥0∞ M] : DistribMulAction ℝ≥0 M := DistribMulAction.compHom M ofNNRealHom.toMonoidHom /-- A `Module` over `ℝ≥0∞` restricts to a `Module` over `ℝ≥0`. -/ noncomputable instance {M : Type*} [AddCommMonoid M] [Module ℝ≥0∞ M] : Module ℝ≥0 M := Module.compHom M ofNNRealHom /-- An `Algebra` over `ℝ≥0∞` restricts to an `Algebra` over `ℝ≥0`. -/ noncomputable instance {A : Type*} [Semiring A] [Algebra ℝ≥0∞ A] : Algebra ℝ≥0 A where smul := (· • ·) commutes' r x := by simp [Algebra.commutes] smul_def' r x := by simp [← Algebra.smul_def (r : ℝ≥0∞) x, smul_def] toRingHom := (algebraMap ℝ≥0∞ A).comp (ofNNRealHom : ℝ≥0 →+* ℝ≥0∞) -- verify that the above produces instances we might care about noncomputable example : Algebra ℝ≥0 ℝ≥0∞ := inferInstance noncomputable example : DistribMulAction ℝ≥0ˣ ℝ≥0∞ := inferInstance theorem coe_smul {R} (r : R) (s : ℝ≥0) [SMul R ℝ≥0] [SMul R ℝ≥0∞] [IsScalarTower R ℝ≥0 ℝ≥0] [IsScalarTower R ℝ≥0 ℝ≥0∞] : (↑(r • s) : ℝ≥0∞) = (r : R) • (s : ℝ≥0∞) := by rw [← smul_one_smul ℝ≥0 r (s : ℝ≥0∞), smul_def, smul_eq_mul, ← ENNReal.coe_mul, smul_mul_assoc, one_mul] -- Porting note: added missing `DecidableEq R` theorem smul_top {R} [Zero R] [SMulWithZero R ℝ≥0∞] [IsScalarTower R ℝ≥0∞ ℝ≥0∞] [NoZeroSMulDivisors R ℝ≥0∞] [DecidableEq R] (c : R) : c • ∞ = if c = 0 then 0 else ∞ := by rw [← smul_one_mul, mul_top'] -- Porting note: need the primed version of `one_ne_zero` now simp_rw [smul_eq_zero, or_iff_left (one_ne_zero' ℝ≥0∞)] end Actions end ENNReal
Data\ENNReal\Real.lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Yury Kudryashov -/ import Mathlib.Data.ENNReal.Inv import Mathlib.Tactic.Bound.Attribute /-! # Maps between real and extended non-negative real numbers This file focuses on the functions `ENNReal.toReal : ℝ≥0∞ → ℝ` and `ENNReal.ofReal : ℝ → ℝ≥0∞` which were defined in `Data.ENNReal.Basic`. It collects all the basic results of the interactions between these functions and the algebraic and lattice operations, although a few may appear in earlier files. This file provides a `positivity` extension for `ENNReal.ofReal`. # Main theorems - `trichotomy (p : ℝ≥0∞) : p = 0 ∨ p = ∞ ∨ 0 < p.toReal`: often used for `WithLp` and `lp` - `dichotomy (p : ℝ≥0∞) [Fact (1 ≤ p)] : p = ∞ ∨ 1 ≤ p.toReal`: often used for `WithLp` and `lp` - `toNNReal_iInf` through `toReal_sSup`: these declarations allow for easy conversions between indexed or set infima and suprema in `ℝ`, `ℝ≥0` and `ℝ≥0∞`. This is especially useful because `ℝ≥0∞` is a complete lattice. -/ open Set NNReal ENNReal namespace ENNReal section Real variable {a b c d : ℝ≥0∞} {r p q : ℝ≥0} theorem toReal_add (ha : a ≠ ∞) (hb : b ≠ ∞) : (a + b).toReal = a.toReal + b.toReal := by lift a to ℝ≥0 using ha lift b to ℝ≥0 using hb rfl theorem toReal_sub_of_le {a b : ℝ≥0∞} (h : b ≤ a) (ha : a ≠ ∞) : (a - b).toReal = a.toReal - b.toReal := by lift b to ℝ≥0 using ne_top_of_le_ne_top ha h lift a to ℝ≥0 using ha simp only [← ENNReal.coe_sub, ENNReal.coe_toReal, NNReal.coe_sub (ENNReal.coe_le_coe.mp h)] theorem le_toReal_sub {a b : ℝ≥0∞} (hb : b ≠ ∞) : a.toReal - b.toReal ≤ (a - b).toReal := by lift b to ℝ≥0 using hb induction a · simp · simp only [← coe_sub, NNReal.sub_def, Real.coe_toNNReal', coe_toReal] exact le_max_left _ _ theorem toReal_add_le : (a + b).toReal ≤ a.toReal + b.toReal := if ha : a = ∞ then by simp only [ha, top_add, top_toReal, zero_add, toReal_nonneg] else if hb : b = ∞ then by simp only [hb, add_top, top_toReal, add_zero, toReal_nonneg] else le_of_eq (toReal_add ha hb) theorem ofReal_add {p q : ℝ} (hp : 0 ≤ p) (hq : 0 ≤ q) : ENNReal.ofReal (p + q) = ENNReal.ofReal p + ENNReal.ofReal q := by rw [ENNReal.ofReal, ENNReal.ofReal, ENNReal.ofReal, ← coe_add, coe_inj, Real.toNNReal_add hp hq] theorem ofReal_add_le {p q : ℝ} : ENNReal.ofReal (p + q) ≤ ENNReal.ofReal p + ENNReal.ofReal q := coe_le_coe.2 Real.toNNReal_add_le @[simp] theorem toReal_le_toReal (ha : a ≠ ∞) (hb : b ≠ ∞) : a.toReal ≤ b.toReal ↔ a ≤ b := by lift a to ℝ≥0 using ha lift b to ℝ≥0 using hb norm_cast @[gcongr] theorem toReal_mono (hb : b ≠ ∞) (h : a ≤ b) : a.toReal ≤ b.toReal := (toReal_le_toReal (ne_top_of_le_ne_top hb h) hb).2 h theorem toReal_mono' (h : a ≤ b) (ht : b = ∞ → a = ∞) : a.toReal ≤ b.toReal := by rcases eq_or_ne a ∞ with rfl | ha · exact toReal_nonneg · exact toReal_mono (mt ht ha) h @[simp] theorem toReal_lt_toReal (ha : a ≠ ∞) (hb : b ≠ ∞) : a.toReal < b.toReal ↔ a < b := by lift a to ℝ≥0 using ha lift b to ℝ≥0 using hb norm_cast @[gcongr] theorem toReal_strict_mono (hb : b ≠ ∞) (h : a < b) : a.toReal < b.toReal := (toReal_lt_toReal h.ne_top hb).2 h @[gcongr] theorem toNNReal_mono (hb : b ≠ ∞) (h : a ≤ b) : a.toNNReal ≤ b.toNNReal := toReal_mono hb h theorem le_toNNReal_of_coe_le (h : p ≤ a) (ha : a ≠ ∞) : p ≤ a.toNNReal := @toNNReal_coe p ▸ toNNReal_mono ha h /-- If `a ≤ b + c` and `a = ∞` whenever `b = ∞` or `c = ∞`, then `ENNReal.toReal a ≤ ENNReal.toReal b + ENNReal.toReal c`. This lemma is useful to transfer triangle-like inequalities from `ENNReal`s to `Real`s. -/ theorem toReal_le_add' (hle : a ≤ b + c) (hb : b = ∞ → a = ∞) (hc : c = ∞ → a = ∞) : a.toReal ≤ b.toReal + c.toReal := by refine le_trans (toReal_mono' hle ?_) toReal_add_le simpa only [add_eq_top, or_imp] using And.intro hb hc /-- If `a ≤ b + c`, `b ≠ ∞`, and `c ≠ ∞`, then `ENNReal.toReal a ≤ ENNReal.toReal b + ENNReal.toReal c`. This lemma is useful to transfer triangle-like inequalities from `ENNReal`s to `Real`s. -/ theorem toReal_le_add (hle : a ≤ b + c) (hb : b ≠ ∞) (hc : c ≠ ∞) : a.toReal ≤ b.toReal + c.toReal := toReal_le_add' hle (flip absurd hb) (flip absurd hc) @[simp] theorem toNNReal_le_toNNReal (ha : a ≠ ∞) (hb : b ≠ ∞) : a.toNNReal ≤ b.toNNReal ↔ a ≤ b := ⟨fun h => by rwa [← coe_toNNReal ha, ← coe_toNNReal hb, coe_le_coe], toNNReal_mono hb⟩ @[gcongr] theorem toNNReal_strict_mono (hb : b ≠ ∞) (h : a < b) : a.toNNReal < b.toNNReal := by simpa [← ENNReal.coe_lt_coe, hb, h.ne_top] @[simp] theorem toNNReal_lt_toNNReal (ha : a ≠ ∞) (hb : b ≠ ∞) : a.toNNReal < b.toNNReal ↔ a < b := ⟨fun h => by rwa [← coe_toNNReal ha, ← coe_toNNReal hb, coe_lt_coe], toNNReal_strict_mono hb⟩ theorem toNNReal_lt_of_lt_coe (h : a < p) : a.toNNReal < p := @toNNReal_coe p ▸ toNNReal_strict_mono coe_ne_top h theorem toReal_max (hr : a ≠ ∞) (hp : b ≠ ∞) : ENNReal.toReal (max a b) = max (ENNReal.toReal a) (ENNReal.toReal b) := (le_total a b).elim (fun h => by simp only [h, (ENNReal.toReal_le_toReal hr hp).2 h, max_eq_right]) fun h => by simp only [h, (ENNReal.toReal_le_toReal hp hr).2 h, max_eq_left] theorem toReal_min {a b : ℝ≥0∞} (hr : a ≠ ∞) (hp : b ≠ ∞) : ENNReal.toReal (min a b) = min (ENNReal.toReal a) (ENNReal.toReal b) := (le_total a b).elim (fun h => by simp only [h, (ENNReal.toReal_le_toReal hr hp).2 h, min_eq_left]) fun h => by simp only [h, (ENNReal.toReal_le_toReal hp hr).2 h, min_eq_right] theorem toReal_sup {a b : ℝ≥0∞} : a ≠ ∞ → b ≠ ∞ → (a ⊔ b).toReal = a.toReal ⊔ b.toReal := toReal_max theorem toReal_inf {a b : ℝ≥0∞} : a ≠ ∞ → b ≠ ∞ → (a ⊓ b).toReal = a.toReal ⊓ b.toReal := toReal_min theorem toNNReal_pos_iff : 0 < a.toNNReal ↔ 0 < a ∧ a < ∞ := by induction a <;> simp theorem toNNReal_pos {a : ℝ≥0∞} (ha₀ : a ≠ 0) (ha_top : a ≠ ∞) : 0 < a.toNNReal := toNNReal_pos_iff.mpr ⟨bot_lt_iff_ne_bot.mpr ha₀, lt_top_iff_ne_top.mpr ha_top⟩ theorem toReal_pos_iff : 0 < a.toReal ↔ 0 < a ∧ a < ∞ := NNReal.coe_pos.trans toNNReal_pos_iff theorem toReal_pos {a : ℝ≥0∞} (ha₀ : a ≠ 0) (ha_top : a ≠ ∞) : 0 < a.toReal := toReal_pos_iff.mpr ⟨bot_lt_iff_ne_bot.mpr ha₀, lt_top_iff_ne_top.mpr ha_top⟩ @[gcongr, bound] theorem ofReal_le_ofReal {p q : ℝ} (h : p ≤ q) : ENNReal.ofReal p ≤ ENNReal.ofReal q := by simp [ENNReal.ofReal, Real.toNNReal_le_toNNReal h] theorem ofReal_le_of_le_toReal {a : ℝ} {b : ℝ≥0∞} (h : a ≤ ENNReal.toReal b) : ENNReal.ofReal a ≤ b := (ofReal_le_ofReal h).trans ofReal_toReal_le @[simp] theorem ofReal_le_ofReal_iff {p q : ℝ} (h : 0 ≤ q) : ENNReal.ofReal p ≤ ENNReal.ofReal q ↔ p ≤ q := by rw [ENNReal.ofReal, ENNReal.ofReal, coe_le_coe, Real.toNNReal_le_toNNReal_iff h] lemma ofReal_le_ofReal_iff' {p q : ℝ} : ENNReal.ofReal p ≤ .ofReal q ↔ p ≤ q ∨ p ≤ 0 := coe_le_coe.trans Real.toNNReal_le_toNNReal_iff' lemma ofReal_lt_ofReal_iff' {p q : ℝ} : ENNReal.ofReal p < .ofReal q ↔ p < q ∧ 0 < q := coe_lt_coe.trans Real.toNNReal_lt_toNNReal_iff' @[simp] theorem ofReal_eq_ofReal_iff {p q : ℝ} (hp : 0 ≤ p) (hq : 0 ≤ q) : ENNReal.ofReal p = ENNReal.ofReal q ↔ p = q := by rw [ENNReal.ofReal, ENNReal.ofReal, coe_inj, Real.toNNReal_eq_toNNReal_iff hp hq] @[simp] theorem ofReal_lt_ofReal_iff {p q : ℝ} (h : 0 < q) : ENNReal.ofReal p < ENNReal.ofReal q ↔ p < q := by rw [ENNReal.ofReal, ENNReal.ofReal, coe_lt_coe, Real.toNNReal_lt_toNNReal_iff h] theorem ofReal_lt_ofReal_iff_of_nonneg {p q : ℝ} (hp : 0 ≤ p) : ENNReal.ofReal p < ENNReal.ofReal q ↔ p < q := by rw [ENNReal.ofReal, ENNReal.ofReal, coe_lt_coe, Real.toNNReal_lt_toNNReal_iff_of_nonneg hp] @[simp] theorem ofReal_pos {p : ℝ} : 0 < ENNReal.ofReal p ↔ 0 < p := by simp [ENNReal.ofReal] @[bound] private alias ⟨_, Bound.ofReal_pos_of_pos⟩ := ofReal_pos @[simp] theorem ofReal_eq_zero {p : ℝ} : ENNReal.ofReal p = 0 ↔ p ≤ 0 := by simp [ENNReal.ofReal] @[simp] theorem zero_eq_ofReal {p : ℝ} : 0 = ENNReal.ofReal p ↔ p ≤ 0 := eq_comm.trans ofReal_eq_zero alias ⟨_, ofReal_of_nonpos⟩ := ofReal_eq_zero @[simp] lemma ofReal_lt_natCast {p : ℝ} {n : ℕ} (hn : n ≠ 0) : ENNReal.ofReal p < n ↔ p < n := by exact mod_cast ofReal_lt_ofReal_iff (Nat.cast_pos.2 hn.bot_lt) @[deprecated (since := "2024-04-17")] alias ofReal_lt_nat_cast := ofReal_lt_natCast @[simp] lemma ofReal_lt_one {p : ℝ} : ENNReal.ofReal p < 1 ↔ p < 1 := by exact mod_cast ofReal_lt_natCast one_ne_zero @[simp] lemma ofReal_lt_ofNat {p : ℝ} {n : ℕ} [n.AtLeastTwo] : ENNReal.ofReal p < no_index (OfNat.ofNat n) ↔ p < OfNat.ofNat n := ofReal_lt_natCast (NeZero.ne n) @[simp] lemma natCast_le_ofReal {n : ℕ} {p : ℝ} (hn : n ≠ 0) : n ≤ ENNReal.ofReal p ↔ n ≤ p := by simp only [← not_lt, ofReal_lt_natCast hn] @[deprecated (since := "2024-04-17")] alias nat_cast_le_ofReal := natCast_le_ofReal @[simp] lemma one_le_ofReal {p : ℝ} : 1 ≤ ENNReal.ofReal p ↔ 1 ≤ p := by exact mod_cast natCast_le_ofReal one_ne_zero @[simp] lemma ofNat_le_ofReal {n : ℕ} [n.AtLeastTwo] {p : ℝ} : no_index (OfNat.ofNat n) ≤ ENNReal.ofReal p ↔ OfNat.ofNat n ≤ p := natCast_le_ofReal (NeZero.ne n) @[simp] lemma ofReal_le_natCast {r : ℝ} {n : ℕ} : ENNReal.ofReal r ≤ n ↔ r ≤ n := coe_le_coe.trans Real.toNNReal_le_natCast @[deprecated (since := "2024-04-17")] alias ofReal_le_nat_cast := ofReal_le_natCast @[simp] lemma ofReal_le_one {r : ℝ} : ENNReal.ofReal r ≤ 1 ↔ r ≤ 1 := coe_le_coe.trans Real.toNNReal_le_one @[simp] lemma ofReal_le_ofNat {r : ℝ} {n : ℕ} [n.AtLeastTwo] : ENNReal.ofReal r ≤ no_index (OfNat.ofNat n) ↔ r ≤ OfNat.ofNat n := ofReal_le_natCast @[simp] lemma natCast_lt_ofReal {n : ℕ} {r : ℝ} : n < ENNReal.ofReal r ↔ n < r := coe_lt_coe.trans Real.natCast_lt_toNNReal @[deprecated (since := "2024-04-17")] alias nat_cast_lt_ofReal := natCast_lt_ofReal @[simp] lemma one_lt_ofReal {r : ℝ} : 1 < ENNReal.ofReal r ↔ 1 < r := coe_lt_coe.trans Real.one_lt_toNNReal @[simp] lemma ofNat_lt_ofReal {n : ℕ} [n.AtLeastTwo] {r : ℝ} : no_index (OfNat.ofNat n) < ENNReal.ofReal r ↔ OfNat.ofNat n < r := natCast_lt_ofReal @[simp] lemma ofReal_eq_natCast {r : ℝ} {n : ℕ} (h : n ≠ 0) : ENNReal.ofReal r = n ↔ r = n := ENNReal.coe_inj.trans <| Real.toNNReal_eq_natCast h @[deprecated (since := "2024-04-17")] alias ofReal_eq_nat_cast := ofReal_eq_natCast @[simp] lemma ofReal_eq_one {r : ℝ} : ENNReal.ofReal r = 1 ↔ r = 1 := ENNReal.coe_inj.trans Real.toNNReal_eq_one @[simp] lemma ofReal_eq_ofNat {r : ℝ} {n : ℕ} [n.AtLeastTwo] : ENNReal.ofReal r = no_index (OfNat.ofNat n) ↔ r = OfNat.ofNat n := ofReal_eq_natCast (NeZero.ne n) theorem ofReal_sub (p : ℝ) {q : ℝ} (hq : 0 ≤ q) : ENNReal.ofReal (p - q) = ENNReal.ofReal p - ENNReal.ofReal q := by obtain h | h := le_total p q · rw [ofReal_of_nonpos (sub_nonpos_of_le h), tsub_eq_zero_of_le (ofReal_le_ofReal h)] refine ENNReal.eq_sub_of_add_eq ofReal_ne_top ?_ rw [← ofReal_add (sub_nonneg_of_le h) hq, sub_add_cancel] theorem ofReal_le_iff_le_toReal {a : ℝ} {b : ℝ≥0∞} (hb : b ≠ ∞) : ENNReal.ofReal a ≤ b ↔ a ≤ ENNReal.toReal b := by lift b to ℝ≥0 using hb simpa [ENNReal.ofReal, ENNReal.toReal] using Real.toNNReal_le_iff_le_coe theorem ofReal_lt_iff_lt_toReal {a : ℝ} {b : ℝ≥0∞} (ha : 0 ≤ a) (hb : b ≠ ∞) : ENNReal.ofReal a < b ↔ a < ENNReal.toReal b := by lift b to ℝ≥0 using hb simpa [ENNReal.ofReal, ENNReal.toReal] using Real.toNNReal_lt_iff_lt_coe ha theorem ofReal_lt_coe_iff {a : ℝ} {b : ℝ≥0} (ha : 0 ≤ a) : ENNReal.ofReal a < b ↔ a < b := (ofReal_lt_iff_lt_toReal ha coe_ne_top).trans <| by rw [coe_toReal] theorem le_ofReal_iff_toReal_le {a : ℝ≥0∞} {b : ℝ} (ha : a ≠ ∞) (hb : 0 ≤ b) : a ≤ ENNReal.ofReal b ↔ ENNReal.toReal a ≤ b := by lift a to ℝ≥0 using ha simpa [ENNReal.ofReal, ENNReal.toReal] using Real.le_toNNReal_iff_coe_le hb theorem toReal_le_of_le_ofReal {a : ℝ≥0∞} {b : ℝ} (hb : 0 ≤ b) (h : a ≤ ENNReal.ofReal b) : ENNReal.toReal a ≤ b := have ha : a ≠ ∞ := ne_top_of_le_ne_top ofReal_ne_top h (le_ofReal_iff_toReal_le ha hb).1 h theorem lt_ofReal_iff_toReal_lt {a : ℝ≥0∞} {b : ℝ} (ha : a ≠ ∞) : a < ENNReal.ofReal b ↔ ENNReal.toReal a < b := by lift a to ℝ≥0 using ha simpa [ENNReal.ofReal, ENNReal.toReal] using Real.lt_toNNReal_iff_coe_lt theorem toReal_lt_of_lt_ofReal {b : ℝ} (h : a < ENNReal.ofReal b) : ENNReal.toReal a < b := (lt_ofReal_iff_toReal_lt h.ne_top).1 h theorem ofReal_mul {p q : ℝ} (hp : 0 ≤ p) : ENNReal.ofReal (p * q) = ENNReal.ofReal p * ENNReal.ofReal q := by simp only [ENNReal.ofReal, ← coe_mul, Real.toNNReal_mul hp] theorem ofReal_mul' {p q : ℝ} (hq : 0 ≤ q) : ENNReal.ofReal (p * q) = ENNReal.ofReal p * ENNReal.ofReal q := by rw [mul_comm, ofReal_mul hq, mul_comm] theorem ofReal_pow {p : ℝ} (hp : 0 ≤ p) (n : ℕ) : ENNReal.ofReal (p ^ n) = ENNReal.ofReal p ^ n := by rw [ofReal_eq_coe_nnreal hp, ← coe_pow, ← ofReal_coe_nnreal, NNReal.coe_pow, NNReal.coe_mk] theorem ofReal_nsmul {x : ℝ} {n : ℕ} : ENNReal.ofReal (n • x) = n • ENNReal.ofReal x := by simp only [nsmul_eq_mul, ← ofReal_natCast n, ← ofReal_mul n.cast_nonneg] theorem ofReal_inv_of_pos {x : ℝ} (hx : 0 < x) : ENNReal.ofReal x⁻¹ = (ENNReal.ofReal x)⁻¹ := by rw [ENNReal.ofReal, ENNReal.ofReal, ← @coe_inv (Real.toNNReal x) (by simp [hx]), coe_inj, ← Real.toNNReal_inv] theorem ofReal_div_of_pos {x y : ℝ} (hy : 0 < y) : ENNReal.ofReal (x / y) = ENNReal.ofReal x / ENNReal.ofReal y := by rw [div_eq_mul_inv, div_eq_mul_inv, ofReal_mul' (inv_nonneg.2 hy.le), ofReal_inv_of_pos hy] @[simp] theorem toNNReal_mul {a b : ℝ≥0∞} : (a * b).toNNReal = a.toNNReal * b.toNNReal := WithTop.untop'_zero_mul a b theorem toNNReal_mul_top (a : ℝ≥0∞) : ENNReal.toNNReal (a * ∞) = 0 := by simp theorem toNNReal_top_mul (a : ℝ≥0∞) : ENNReal.toNNReal (∞ * a) = 0 := by simp @[simp] theorem smul_toNNReal (a : ℝ≥0) (b : ℝ≥0∞) : (a • b).toNNReal = a * b.toNNReal := by change ((a : ℝ≥0∞) * b).toNNReal = a * b.toNNReal simp only [ENNReal.toNNReal_mul, ENNReal.toNNReal_coe] -- Porting note (#11215): TODO: upgrade to `→*₀` /-- `ENNReal.toNNReal` as a `MonoidHom`. -/ def toNNRealHom : ℝ≥0∞ →* ℝ≥0 where toFun := ENNReal.toNNReal map_one' := toNNReal_coe map_mul' _ _ := toNNReal_mul @[simp] theorem toNNReal_pow (a : ℝ≥0∞) (n : ℕ) : (a ^ n).toNNReal = a.toNNReal ^ n := toNNRealHom.map_pow a n @[simp] theorem toNNReal_prod {ι : Type*} {s : Finset ι} {f : ι → ℝ≥0∞} : (∏ i ∈ s, f i).toNNReal = ∏ i ∈ s, (f i).toNNReal := map_prod toNNRealHom _ _ -- Porting note (#11215): TODO: upgrade to `→*₀` /-- `ENNReal.toReal` as a `MonoidHom`. -/ def toRealHom : ℝ≥0∞ →* ℝ := (NNReal.toRealHom : ℝ≥0 →* ℝ).comp toNNRealHom @[simp] theorem toReal_mul : (a * b).toReal = a.toReal * b.toReal := toRealHom.map_mul a b theorem toReal_nsmul (a : ℝ≥0∞) (n : ℕ) : (n • a).toReal = n • a.toReal := by simp @[simp] theorem toReal_pow (a : ℝ≥0∞) (n : ℕ) : (a ^ n).toReal = a.toReal ^ n := toRealHom.map_pow a n @[simp] theorem toReal_prod {ι : Type*} {s : Finset ι} {f : ι → ℝ≥0∞} : (∏ i ∈ s, f i).toReal = ∏ i ∈ s, (f i).toReal := map_prod toRealHom _ _ theorem toReal_ofReal_mul (c : ℝ) (a : ℝ≥0∞) (h : 0 ≤ c) : ENNReal.toReal (ENNReal.ofReal c * a) = c * ENNReal.toReal a := by rw [ENNReal.toReal_mul, ENNReal.toReal_ofReal h] theorem toReal_mul_top (a : ℝ≥0∞) : ENNReal.toReal (a * ∞) = 0 := by rw [toReal_mul, top_toReal, mul_zero] theorem toReal_top_mul (a : ℝ≥0∞) : ENNReal.toReal (∞ * a) = 0 := by rw [mul_comm] exact toReal_mul_top _ theorem toReal_eq_toReal (ha : a ≠ ∞) (hb : b ≠ ∞) : a.toReal = b.toReal ↔ a = b := by lift a to ℝ≥0 using ha lift b to ℝ≥0 using hb simp only [coe_inj, NNReal.coe_inj, coe_toReal] theorem toReal_smul (r : ℝ≥0) (s : ℝ≥0∞) : (r • s).toReal = r • s.toReal := by rw [ENNReal.smul_def, smul_eq_mul, toReal_mul, coe_toReal] rfl protected theorem trichotomy (p : ℝ≥0∞) : p = 0 ∨ p = ∞ ∨ 0 < p.toReal := by simpa only [or_iff_not_imp_left] using toReal_pos protected theorem trichotomy₂ {p q : ℝ≥0∞} (hpq : p ≤ q) : p = 0 ∧ q = 0 ∨ p = 0 ∧ q = ∞ ∨ p = 0 ∧ 0 < q.toReal ∨ p = ∞ ∧ q = ∞ ∨ 0 < p.toReal ∧ q = ∞ ∨ 0 < p.toReal ∧ 0 < q.toReal ∧ p.toReal ≤ q.toReal := by rcases eq_or_lt_of_le (bot_le : 0 ≤ p) with ((rfl : 0 = p) | (hp : 0 < p)) · simpa using q.trichotomy rcases eq_or_lt_of_le (le_top : q ≤ ∞) with (rfl | hq) · simpa using p.trichotomy repeat' right have hq' : 0 < q := lt_of_lt_of_le hp hpq have hp' : p < ∞ := lt_of_le_of_lt hpq hq simp [ENNReal.toReal_le_toReal hp'.ne hq.ne, ENNReal.toReal_pos_iff, hpq, hp, hp', hq', hq] protected theorem dichotomy (p : ℝ≥0∞) [Fact (1 ≤ p)] : p = ∞ ∨ 1 ≤ p.toReal := haveI : p = ⊤ ∨ 0 < p.toReal ∧ 1 ≤ p.toReal := by simpa using ENNReal.trichotomy₂ (Fact.out : 1 ≤ p) this.imp_right fun h => h.2 theorem toReal_pos_iff_ne_top (p : ℝ≥0∞) [Fact (1 ≤ p)] : 0 < p.toReal ↔ p ≠ ∞ := ⟨fun h hp => have : (0 : ℝ) ≠ 0 := top_toReal ▸ (hp ▸ h.ne : 0 ≠ ∞.toReal) this rfl, fun h => zero_lt_one.trans_le (p.dichotomy.resolve_left h)⟩ theorem toNNReal_inv (a : ℝ≥0∞) : a⁻¹.toNNReal = a.toNNReal⁻¹ := by induction' a with a; · simp rcases eq_or_ne a 0 with (rfl | ha); · simp rw [← coe_inv ha, toNNReal_coe, toNNReal_coe] theorem toNNReal_div (a b : ℝ≥0∞) : (a / b).toNNReal = a.toNNReal / b.toNNReal := by rw [div_eq_mul_inv, toNNReal_mul, toNNReal_inv, div_eq_mul_inv] theorem toReal_inv (a : ℝ≥0∞) : a⁻¹.toReal = a.toReal⁻¹ := by simp only [ENNReal.toReal, toNNReal_inv, NNReal.coe_inv] theorem toReal_div (a b : ℝ≥0∞) : (a / b).toReal = a.toReal / b.toReal := by rw [div_eq_mul_inv, toReal_mul, toReal_inv, div_eq_mul_inv] theorem ofReal_prod_of_nonneg {α : Type*} {s : Finset α} {f : α → ℝ} (hf : ∀ i, i ∈ s → 0 ≤ f i) : ENNReal.ofReal (∏ i ∈ s, f i) = ∏ i ∈ s, ENNReal.ofReal (f i) := by simp_rw [ENNReal.ofReal, ← coe_finset_prod, coe_inj] exact Real.toNNReal_prod_of_nonneg hf end Real section iInf variable {ι : Sort*} {f g : ι → ℝ≥0∞} variable {a b c d : ℝ≥0∞} {r p q : ℝ≥0} theorem toNNReal_iInf (hf : ∀ i, f i ≠ ∞) : (iInf f).toNNReal = ⨅ i, (f i).toNNReal := by cases isEmpty_or_nonempty ι · rw [iInf_of_empty, top_toNNReal, NNReal.iInf_empty] · lift f to ι → ℝ≥0 using hf simp_rw [← coe_iInf, toNNReal_coe] theorem toNNReal_sInf (s : Set ℝ≥0∞) (hs : ∀ r ∈ s, r ≠ ∞) : (sInf s).toNNReal = sInf (ENNReal.toNNReal '' s) := by have hf : ∀ i, ((↑) : s → ℝ≥0∞) i ≠ ∞ := fun ⟨r, rs⟩ => hs r rs -- Porting note: `← sInf_image'` had to be replaced by `← image_eq_range` as the lemmas are used -- in a different order. simpa only [← sInf_range, ← image_eq_range, Subtype.range_coe_subtype] using (toNNReal_iInf hf) theorem toNNReal_iSup (hf : ∀ i, f i ≠ ∞) : (iSup f).toNNReal = ⨆ i, (f i).toNNReal := by lift f to ι → ℝ≥0 using hf simp_rw [toNNReal_coe] by_cases h : BddAbove (range f) · rw [← coe_iSup h, toNNReal_coe] · rw [NNReal.iSup_of_not_bddAbove h, iSup_coe_eq_top.2 h, top_toNNReal] theorem toNNReal_sSup (s : Set ℝ≥0∞) (hs : ∀ r ∈ s, r ≠ ∞) : (sSup s).toNNReal = sSup (ENNReal.toNNReal '' s) := by have hf : ∀ i, ((↑) : s → ℝ≥0∞) i ≠ ∞ := fun ⟨r, rs⟩ => hs r rs -- Porting note: `← sSup_image'` had to be replaced by `← image_eq_range` as the lemmas are used -- in a different order. simpa only [← sSup_range, ← image_eq_range, Subtype.range_coe_subtype] using (toNNReal_iSup hf) theorem toReal_iInf (hf : ∀ i, f i ≠ ∞) : (iInf f).toReal = ⨅ i, (f i).toReal := by simp only [ENNReal.toReal, toNNReal_iInf hf, NNReal.coe_iInf] theorem toReal_sInf (s : Set ℝ≥0∞) (hf : ∀ r ∈ s, r ≠ ∞) : (sInf s).toReal = sInf (ENNReal.toReal '' s) := by simp only [ENNReal.toReal, toNNReal_sInf s hf, NNReal.coe_sInf, Set.image_image] theorem toReal_iSup (hf : ∀ i, f i ≠ ∞) : (iSup f).toReal = ⨆ i, (f i).toReal := by simp only [ENNReal.toReal, toNNReal_iSup hf, NNReal.coe_iSup] theorem toReal_sSup (s : Set ℝ≥0∞) (hf : ∀ r ∈ s, r ≠ ∞) : (sSup s).toReal = sSup (ENNReal.toReal '' s) := by simp only [ENNReal.toReal, toNNReal_sSup s hf, NNReal.coe_sSup, Set.image_image] theorem iInf_add : iInf f + a = ⨅ i, f i + a := le_antisymm (le_iInf fun _ => add_le_add (iInf_le _ _) <| le_rfl) (tsub_le_iff_right.1 <| le_iInf fun _ => tsub_le_iff_right.2 <| iInf_le _ _) theorem iSup_sub : (⨆ i, f i) - a = ⨆ i, f i - a := le_antisymm (tsub_le_iff_right.2 <| iSup_le fun i => tsub_le_iff_right.1 <| le_iSup (f · - a) i) (iSup_le fun _ => tsub_le_tsub (le_iSup _ _) (le_refl a)) theorem sub_iInf : (a - ⨅ i, f i) = ⨆ i, a - f i := by refine eq_of_forall_ge_iff fun c => ?_ rw [tsub_le_iff_right, add_comm, iInf_add] simp [tsub_le_iff_right, sub_eq_add_neg, add_comm] theorem sInf_add {s : Set ℝ≥0∞} : sInf s + a = ⨅ b ∈ s, b + a := by simp [sInf_eq_iInf, iInf_add] theorem add_iInf {a : ℝ≥0∞} : a + iInf f = ⨅ b, a + f b := by rw [add_comm, iInf_add]; simp [add_comm] theorem iInf_add_iInf (h : ∀ i j, ∃ k, f k + g k ≤ f i + g j) : iInf f + iInf g = ⨅ a, f a + g a := suffices ⨅ a, f a + g a ≤ iInf f + iInf g from le_antisymm (le_iInf fun a => add_le_add (iInf_le _ _) (iInf_le _ _)) this calc ⨅ a, f a + g a ≤ ⨅ (a) (a'), f a + g a' := le_iInf₂ fun a a' => let ⟨k, h⟩ := h a a'; iInf_le_of_le k h _ = iInf f + iInf g := by simp_rw [iInf_add, add_iInf] theorem iInf_sum {α : Type*} {f : ι → α → ℝ≥0∞} {s : Finset α} [Nonempty ι] (h : ∀ (t : Finset α) (i j : ι), ∃ k, ∀ a ∈ t, f k a ≤ f i a ∧ f k a ≤ f j a) : ⨅ i, ∑ a ∈ s, f i a = ∑ a ∈ s, ⨅ i, f i a := by induction' s using Finset.cons_induction_on with a s ha ih · simp only [Finset.sum_empty, ciInf_const] · simp only [Finset.sum_cons, ← ih] refine (iInf_add_iInf fun i j => ?_).symm refine (h (Finset.cons a s ha) i j).imp fun k hk => ?_ rw [Finset.forall_mem_cons] at hk exact add_le_add hk.1.1 (Finset.sum_le_sum fun a ha => (hk.2 a ha).2) /-- If `x ≠ 0` and `x ≠ ∞`, then right multiplication by `x` maps infimum to infimum. See also `ENNReal.iInf_mul` that assumes `[Nonempty ι]` but does not require `x ≠ 0`. -/ theorem iInf_mul_of_ne {ι} {f : ι → ℝ≥0∞} {x : ℝ≥0∞} (h0 : x ≠ 0) (h : x ≠ ∞) : iInf f * x = ⨅ i, f i * x := le_antisymm mul_right_mono.map_iInf_le ((ENNReal.div_le_iff_le_mul (Or.inl h0) <| Or.inl h).mp <| le_iInf fun _ => (ENNReal.div_le_iff_le_mul (Or.inl h0) <| Or.inl h).mpr <| iInf_le _ _) /-- If `x ≠ ∞`, then right multiplication by `x` maps infimum over a nonempty type to infimum. See also `ENNReal.iInf_mul_of_ne` that assumes `x ≠ 0` but does not require `[Nonempty ι]`. -/ theorem iInf_mul {ι} [Nonempty ι] {f : ι → ℝ≥0∞} {x : ℝ≥0∞} (h : x ≠ ∞) : iInf f * x = ⨅ i, f i * x := by by_cases h0 : x = 0 · simp only [h0, mul_zero, iInf_const] · exact iInf_mul_of_ne h0 h /-- If `x ≠ ∞`, then left multiplication by `x` maps infimum over a nonempty type to infimum. See also `ENNReal.mul_iInf_of_ne` that assumes `x ≠ 0` but does not require `[Nonempty ι]`. -/ theorem mul_iInf {ι} [Nonempty ι] {f : ι → ℝ≥0∞} {x : ℝ≥0∞} (h : x ≠ ∞) : x * iInf f = ⨅ i, x * f i := by simpa only [mul_comm] using iInf_mul h /-- If `x ≠ 0` and `x ≠ ∞`, then left multiplication by `x` maps infimum to infimum. See also `ENNReal.mul_iInf` that assumes `[Nonempty ι]` but does not require `x ≠ 0`. -/ theorem mul_iInf_of_ne {ι} {f : ι → ℝ≥0∞} {x : ℝ≥0∞} (h0 : x ≠ 0) (h : x ≠ ∞) : x * iInf f = ⨅ i, x * f i := by simpa only [mul_comm] using iInf_mul_of_ne h0 h /-! `supr_mul`, `mul_supr` and variants are in `Topology.Instances.ENNReal`. -/ end iInf section iSup @[simp] theorem iSup_eq_zero {ι : Sort*} {f : ι → ℝ≥0∞} : ⨆ i, f i = 0 ↔ ∀ i, f i = 0 := iSup_eq_bot @[simp] theorem iSup_zero_eq_zero {ι : Sort*} : ⨆ _ : ι, (0 : ℝ≥0∞) = 0 := by simp theorem sup_eq_zero {a b : ℝ≥0∞} : a ⊔ b = 0 ↔ a = 0 ∧ b = 0 := sup_eq_bot_iff theorem iSup_natCast : ⨆ n : ℕ, (n : ℝ≥0∞) = ∞ := (iSup_eq_top _).2 fun _b hb => ENNReal.exists_nat_gt (lt_top_iff_ne_top.1 hb) @[deprecated (since := "2024-04-05")] alias iSup_coe_nat := iSup_natCast end iSup end ENNReal namespace Mathlib.Meta.Positivity open Lean Meta Qq /-- Extension for the `positivity` tactic: `ENNReal.ofReal`. -/ @[positivity ENNReal.ofReal _] def evalENNRealOfReal : PositivityExt where eval {u α} _zα _pα e := do match u, α, e with | 0, ~q(ℝ≥0∞), ~q(ENNReal.ofReal $a) => let ra ← core q(inferInstance) q(inferInstance) a assertInstancesCommute match ra with | .positive pa => pure (.positive q(Iff.mpr (@ENNReal.ofReal_pos $a) $pa)) | _ => pure .none | _, _, _ => throwError "not ENNReal.ofReal" end Mathlib.Meta.Positivity
Data\Fin\Basic.lean
/- Copyright (c) 2017 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis, Keeley Hoek -/ import Mathlib.Algebra.NeZero import Mathlib.Data.Nat.Defs import Mathlib.Init.Data.Nat.Lemmas import Mathlib.Logic.Embedding.Basic import Mathlib.Logic.Equiv.Set import Mathlib.Tactic.Common /-! # The finite type with `n` elements `Fin n` is the type whose elements are natural numbers smaller than `n`. This file expands on the development in the core library. ## Main definitions ### Induction principles * `finZeroElim` : Elimination principle for the empty set `Fin 0`, generalizes `Fin.elim0`. * `Fin.succRec` : Define `C n i` by induction on `i : Fin n` interpreted as `(0 : Fin (n - i)).succ.succ…`. This function has two arguments: `H0 n` defines `0`-th element `C (n+1) 0` of an `(n+1)`-tuple, and `Hs n i` defines `(i+1)`-st element of `(n+1)`-tuple based on `n`, `i`, and `i`-th element of `n`-tuple. * `Fin.succRecOn` : same as `Fin.succRec` but `i : Fin n` is the first argument; * `Fin.induction` : Define `C i` by induction on `i : Fin (n + 1)`, separating into the `Nat`-like base cases of `C 0` and `C (i.succ)`. * `Fin.inductionOn` : same as `Fin.induction` but with `i : Fin (n + 1)` as the first argument. * `Fin.cases` : define `f : Π i : Fin n.succ, C i` by separately handling the cases `i = 0` and `i = Fin.succ j`, `j : Fin n`, defined using `Fin.induction`. * `Fin.reverseInduction`: reverse induction on `i : Fin (n + 1)`; given `C (Fin.last n)` and `∀ i : Fin n, C (Fin.succ i) → C (Fin.castSucc i)`, constructs all values `C i` by going down; * `Fin.lastCases`: define `f : Π i, Fin (n + 1), C i` by separately handling the cases `i = Fin.last n` and `i = Fin.castSucc j`, a special case of `Fin.reverseInduction`; * `Fin.addCases`: define a function on `Fin (m + n)` by separately handling the cases `Fin.castAdd n i` and `Fin.natAdd m i`; * `Fin.succAboveCases`: given `i : Fin (n + 1)`, define a function on `Fin (n + 1)` by separately handling the cases `j = i` and `j = Fin.succAbove i k`, same as `Fin.insertNth` but marked as eliminator and works for `Sort*`. -- Porting note: this is in another file ### Embeddings and isomorphisms * `Fin.valEmbedding` : coercion to natural numbers as an `Embedding`; * `Fin.succEmb` : `Fin.succ` as an `Embedding`; * `Fin.castLEEmb h` : `Fin.castLE` as an `Embedding`, embed `Fin n` into `Fin m`, `h : n ≤ m`; * `finCongr` : `Fin.cast` as an `Equiv`, equivalence between `Fin n` and `Fin m` when `n = m`; * `Fin.castAddEmb m` : `Fin.castAdd` as an `Embedding`, embed `Fin n` into `Fin (n+m)`; * `Fin.castSuccEmb` : `Fin.castSucc` as an `Embedding`, embed `Fin n` into `Fin (n+1)`; * `Fin.addNatEmb m i` : `Fin.addNat` as an `Embedding`, add `m` on `i` on the right, generalizes `Fin.succ`; * `Fin.natAddEmb n i` : `Fin.natAdd` as an `Embedding`, adds `n` on `i` on the left; ### Other casts * `Fin.ofNat'`: given a positive number `n` (deduced from `[NeZero n]`), `Fin.ofNat' i` is `i % n` interpreted as an element of `Fin n`; * `Fin.divNat i` : divides `i : Fin (m * n)` by `n`; * `Fin.modNat i` : takes the mod of `i : Fin (m * n)` by `n`; ### Misc definitions * `Fin.revPerm : Equiv.Perm (Fin n)` : `Fin.rev` as an `Equiv.Perm`, the antitone involution given by `i ↦ n-(i+1)` -/ assert_not_exists Monoid universe u v open Fin Nat Function /-- Elimination principle for the empty set `Fin 0`, dependent version. -/ def finZeroElim {α : Fin 0 → Sort*} (x : Fin 0) : α x := x.elim0 namespace Fin instance {n : ℕ} : CanLift ℕ (Fin n) Fin.val (· < n) where prf k hk := ⟨⟨k, hk⟩, rfl⟩ /-- A dependent variant of `Fin.elim0`. -/ def rec0 {α : Fin 0 → Sort*} (i : Fin 0) : α i := absurd i.2 (Nat.not_lt_zero _) variable {n m : ℕ} --variable {a b : Fin n} -- this *really* breaks stuff theorem val_injective : Function.Injective (@Fin.val n) := @Fin.eq_of_val_eq n /-- If you actually have an element of `Fin n`, then the `n` is always positive -/ lemma size_positive : Fin n → 0 < n := Fin.pos lemma size_positive' [Nonempty (Fin n)] : 0 < n := ‹Nonempty (Fin n)›.elim Fin.pos protected theorem prop (a : Fin n) : a.val < n := a.2 section Order variable {a b c : Fin n} protected lemma lt_of_le_of_lt : a ≤ b → b < c → a < c := Nat.lt_of_le_of_lt protected lemma lt_of_lt_of_le : a < b → b ≤ c → a < c := Nat.lt_of_lt_of_le protected lemma le_rfl : a ≤ a := Nat.le_refl _ protected lemma lt_iff_le_and_ne : a < b ↔ a ≤ b ∧ a ≠ b := by rw [← val_ne_iff]; exact Nat.lt_iff_le_and_ne protected lemma lt_or_lt_of_ne (h : a ≠ b) : a < b ∨ b < a := Nat.lt_or_lt_of_ne $ val_ne_iff.2 h protected lemma lt_or_le (a b : Fin n) : a < b ∨ b ≤ a := Nat.lt_or_ge _ _ protected lemma le_or_lt (a b : Fin n) : a ≤ b ∨ b < a := (b.lt_or_le a).symm protected lemma le_of_eq (hab : a = b) : a ≤ b := Nat.le_of_eq $ congr_arg val hab protected lemma ge_of_eq (hab : a = b) : b ≤ a := Fin.le_of_eq hab.symm protected lemma eq_or_lt_of_le : a ≤ b → a = b ∨ a < b := by rw [Fin.ext_iff]; exact Nat.eq_or_lt_of_le protected lemma lt_or_eq_of_le : a ≤ b → a < b ∨ a = b := by rw [Fin.ext_iff]; exact Nat.lt_or_eq_of_le end Order lemma lt_last_iff_ne_last {a : Fin (n + 1)} : a < last n ↔ a ≠ last n := by simp [Fin.lt_iff_le_and_ne, le_last] lemma ne_zero_of_lt {a b : Fin (n + 1)} (hab : a < b) : b ≠ 0 := Fin.ne_of_gt $ Fin.lt_of_le_of_lt a.zero_le hab lemma ne_last_of_lt {a b : Fin (n + 1)} (hab : a < b) : a ≠ last n := Fin.ne_of_lt $ Fin.lt_of_lt_of_le hab b.le_last /-- Equivalence between `Fin n` and `{ i // i < n }`. -/ @[simps apply symm_apply] def equivSubtype : Fin n ≃ { i // i < n } where toFun a := ⟨a.1, a.2⟩ invFun a := ⟨a.1, a.2⟩ left_inv := fun ⟨_, _⟩ => rfl right_inv := fun ⟨_, _⟩ => rfl section coe /-! ### coercions and constructions -/ theorem val_eq_val (a b : Fin n) : (a : ℕ) = b ↔ a = b := Fin.ext_iff.symm @[deprecated Fin.ext_iff (since := "2024-02-20")] theorem eq_iff_veq (a b : Fin n) : a = b ↔ a.1 = b.1 := Fin.ext_iff theorem ne_iff_vne (a b : Fin n) : a ≠ b ↔ a.1 ≠ b.1 := Fin.ext_iff.not -- Porting note: I'm not sure if this comment still applies. -- built-in reduction doesn't always work @[simp, nolint simpNF] theorem mk_eq_mk {a h a' h'} : @mk n a h = @mk n a' h' ↔ a = a' := Fin.ext_iff -- syntactic tautologies now /-- Assume `k = l`. If two functions defined on `Fin k` and `Fin l` are equal on each element, then they coincide (in the heq sense). -/ protected theorem heq_fun_iff {α : Sort*} {k l : ℕ} (h : k = l) {f : Fin k → α} {g : Fin l → α} : HEq f g ↔ ∀ i : Fin k, f i = g ⟨(i : ℕ), h ▸ i.2⟩ := by subst h simp [Function.funext_iff] /-- Assume `k = l` and `k' = l'`. If two functions `Fin k → Fin k' → α` and `Fin l → Fin l' → α` are equal on each pair, then they coincide (in the heq sense). -/ protected theorem heq_fun₂_iff {α : Sort*} {k l k' l' : ℕ} (h : k = l) (h' : k' = l') {f : Fin k → Fin k' → α} {g : Fin l → Fin l' → α} : HEq f g ↔ ∀ (i : Fin k) (j : Fin k'), f i j = g ⟨(i : ℕ), h ▸ i.2⟩ ⟨(j : ℕ), h' ▸ j.2⟩ := by subst h subst h' simp [Function.funext_iff] protected theorem heq_ext_iff {k l : ℕ} (h : k = l) {i : Fin k} {j : Fin l} : HEq i j ↔ (i : ℕ) = (j : ℕ) := by subst h simp [val_eq_val] end coe section Order /-! ### order -/ theorem le_iff_val_le_val {a b : Fin n} : a ≤ b ↔ (a : ℕ) ≤ b := Iff.rfl /-- `a < b` as natural numbers if and only if `a < b` in `Fin n`. -/ @[norm_cast, simp] theorem val_fin_lt {n : ℕ} {a b : Fin n} : (a : ℕ) < (b : ℕ) ↔ a < b := Iff.rfl /-- `a ≤ b` as natural numbers if and only if `a ≤ b` in `Fin n`. -/ @[norm_cast, simp] theorem val_fin_le {n : ℕ} {a b : Fin n} : (a : ℕ) ≤ (b : ℕ) ↔ a ≤ b := Iff.rfl -- @[simp] -- Porting note (#10618): simp can prove this theorem min_val {a : Fin n} : min (a : ℕ) n = a := by simp -- @[simp] -- Porting note (#10618): simp can prove this theorem max_val {a : Fin n} : max (a : ℕ) n = n := by simp /-- The inclusion map `Fin n → ℕ` is an embedding. -/ @[simps apply] def valEmbedding : Fin n ↪ ℕ := ⟨val, val_injective⟩ @[simp] theorem equivSubtype_symm_trans_valEmbedding : equivSubtype.symm.toEmbedding.trans valEmbedding = Embedding.subtype (· < n) := rfl /-- Use the ordering on `Fin n` for checking recursive definitions. For example, the following definition is not accepted by the termination checker, unless we declare the `WellFoundedRelation` instance: ```lean def factorial {n : ℕ} : Fin n → ℕ | ⟨0, _⟩ := 1 | ⟨i + 1, hi⟩ := (i + 1) * factorial ⟨i, i.lt_succ_self.trans hi⟩ ``` -/ instance {n : ℕ} : WellFoundedRelation (Fin n) := measure (val : Fin n → ℕ) /-- Given a positive `n`, `Fin.ofNat' i` is `i % n` as an element of `Fin n`. -/ def ofNat'' [NeZero n] (i : ℕ) : Fin n := ⟨i % n, mod_lt _ n.pos_of_neZero⟩ -- Porting note: `Fin.ofNat'` conflicts with something in core (there the hypothesis is `n > 0`), -- so for now we make this double-prime `''`. This is also the reason for the dubious translation. instance {n : ℕ} [NeZero n] : Zero (Fin n) := ⟨ofNat'' 0⟩ instance {n : ℕ} [NeZero n] : One (Fin n) := ⟨ofNat'' 1⟩ /-- The `Fin.val_zero` in `Lean` only applies in `Fin (n+1)`. This one instead uses a `NeZero n` typeclass hypothesis. -/ @[simp] theorem val_zero' (n : ℕ) [NeZero n] : ((0 : Fin n) : ℕ) = 0 := rfl /-- The `Fin.zero_le` in `Lean` only applies in `Fin (n+1)`. This one instead uses a `NeZero n` typeclass hypothesis. -/ @[simp] protected theorem zero_le' [NeZero n] (a : Fin n) : 0 ≤ a := Nat.zero_le a.val /-- The `Fin.pos_iff_ne_zero` in `Lean` only applies in `Fin (n+1)`. This one instead uses a `NeZero n` typeclass hypothesis. -/ theorem pos_iff_ne_zero' [NeZero n] (a : Fin n) : 0 < a ↔ a ≠ 0 := by rw [← val_fin_lt, val_zero', Nat.pos_iff_ne_zero, Ne, Ne, Fin.ext_iff, val_zero'] @[simp] lemma cast_eq_self (a : Fin n) : cast rfl a = a := rfl theorem rev_involutive : Involutive (rev : Fin n → Fin n) := rev_rev /-- `Fin.rev` as an `Equiv.Perm`, the antitone involution `Fin n → Fin n` given by `i ↦ n-(i+1)`. -/ @[simps! apply symm_apply] def revPerm : Equiv.Perm (Fin n) := Involutive.toPerm rev rev_involutive theorem rev_injective : Injective (@rev n) := rev_involutive.injective theorem rev_surjective : Surjective (@rev n) := rev_involutive.surjective theorem rev_bijective : Bijective (@rev n) := rev_involutive.bijective @[simp] theorem revPerm_symm : (@revPerm n).symm = revPerm := rfl theorem cast_rev (i : Fin n) (h : n = m) : cast h i.rev = (i.cast h).rev := by subst h; simp theorem rev_eq_iff {i j : Fin n} : rev i = j ↔ i = rev j := by rw [← rev_inj, rev_rev] theorem rev_ne_iff {i j : Fin n} : rev i ≠ j ↔ i ≠ rev j := rev_eq_iff.not theorem rev_lt_iff {i j : Fin n} : rev i < j ↔ rev j < i := by rw [← rev_lt_rev, rev_rev] theorem rev_le_iff {i j : Fin n} : rev i ≤ j ↔ rev j ≤ i := by rw [← rev_le_rev, rev_rev] theorem lt_rev_iff {i j : Fin n} : i < rev j ↔ j < rev i := by rw [← rev_lt_rev, rev_rev] theorem le_rev_iff {i j : Fin n} : i ≤ rev j ↔ j ≤ rev i := by rw [← rev_le_rev, rev_rev] -- Porting note: this is now syntactically equal to `val_last` @[simp] theorem val_rev_zero [NeZero n] : ((rev 0 : Fin n) : ℕ) = n.pred := rfl theorem last_pos' [NeZero n] : 0 < last n := n.pos_of_neZero theorem one_lt_last [NeZero n] : 1 < last (n + 1) := by rw [lt_iff_val_lt_val, val_one, val_last, Nat.lt_add_left_iff_pos, Nat.pos_iff_ne_zero] exact NeZero.ne n end Order section Add /-! ### addition, numerals, and coercion from Nat -/ @[simp] theorem val_one' (n : ℕ) [NeZero n] : ((1 : Fin n) : ℕ) = 1 % n := rfl -- Porting note: Delete this lemma after porting theorem val_one'' {n : ℕ} : ((1 : Fin (n + 1)) : ℕ) = 1 % (n + 1) := rfl instance nontrivial {n : ℕ} : Nontrivial (Fin (n + 2)) where exists_pair_ne := ⟨0, 1, (ne_iff_vne 0 1).mpr (by simp [val_one, val_zero])⟩ theorem nontrivial_iff_two_le : Nontrivial (Fin n) ↔ 2 ≤ n := by rcases n with (_ | _ | n) <;> simp [← Nat.one_eq_succ_zero, Fin.nontrivial, not_nontrivial, Nat.succ_le_iff] -- Porting note: here and in the next lemma, had to use `← Nat.one_eq_succ_zero`. section Monoid -- Porting note (#10618): removing `simp`, `simp` can prove it with AddCommMonoid instance protected theorem add_zero [NeZero n] (k : Fin n) : k + 0 = k := by simp only [add_def, val_zero', Nat.add_zero, mod_eq_of_lt (is_lt k)] -- Porting note (#10618): removing `simp`, `simp` can prove it with AddCommMonoid instance protected theorem zero_add [NeZero n] (k : Fin n) : 0 + k = k := by simp [Fin.ext_iff, add_def, mod_eq_of_lt (is_lt k)] instance {a : ℕ} [NeZero n] : OfNat (Fin n) a where ofNat := Fin.ofNat' a n.pos_of_neZero instance inhabited (n : ℕ) [NeZero n] : Inhabited (Fin n) := ⟨0⟩ instance inhabitedFinOneAdd (n : ℕ) : Inhabited (Fin (1 + n)) := haveI : NeZero (1 + n) := by rw [Nat.add_comm]; infer_instance inferInstance @[simp] theorem default_eq_zero (n : ℕ) [NeZero n] : (default : Fin n) = 0 := rfl section from_ad_hoc @[simp] lemma ofNat'_zero {h : 0 < n} [NeZero n] : (Fin.ofNat' 0 h : Fin n) = 0 := rfl @[simp] lemma ofNat'_one {h : 0 < n} [NeZero n] : (Fin.ofNat' 1 h : Fin n) = 1 := rfl end from_ad_hoc instance instNatCast [NeZero n] : NatCast (Fin n) where natCast n := Fin.ofNat'' n lemma natCast_def [NeZero n] (a : ℕ) : (a : Fin n) = ⟨a % n, mod_lt _ n.pos_of_neZero⟩ := rfl end Monoid theorem val_add_eq_ite {n : ℕ} (a b : Fin n) : (↑(a + b) : ℕ) = if n ≤ a + b then a + b - n else a + b := by rw [Fin.val_add, Nat.add_mod_eq_ite, Nat.mod_eq_of_lt (show ↑a < n from a.2), Nat.mod_eq_of_lt (show ↑b < n from b.2)] --- Porting note: syntactically the same as the above section OfNatCoe @[simp] theorem ofNat''_eq_cast (n : ℕ) [NeZero n] (a : ℕ) : (Fin.ofNat'' a : Fin n) = a := rfl @[simp] lemma val_natCast (a n : ℕ) [NeZero n] : (a : Fin n).val = a % n := rfl @[deprecated (since := "2024-04-17")] alias val_nat_cast := val_natCast -- Porting note: is this the right name for things involving `Nat.cast`? /-- Converting an in-range number to `Fin (n + 1)` produces a result whose value is the original number. -/ theorem val_cast_of_lt {n : ℕ} [NeZero n] {a : ℕ} (h : a < n) : (a : Fin n).val = a := Nat.mod_eq_of_lt h /-- If `n` is non-zero, converting the value of a `Fin n` to `Fin n` results in the same value. -/ @[simp] theorem cast_val_eq_self {n : ℕ} [NeZero n] (a : Fin n) : (a.val : Fin n) = a := Fin.ext <| val_cast_of_lt a.isLt -- Porting note: this is syntactically the same as `val_cast_of_lt` -- Porting note: this is syntactically the same as `cast_val_of_lt` @[simp] lemma natCast_self (n : ℕ) [NeZero n] : (n : Fin n) = 0 := by ext; simp @[deprecated (since := "2024-04-17")] alias nat_cast_self := natCast_self @[simp] lemma natCast_eq_zero {a n : ℕ} [NeZero n] : (a : Fin n) = 0 ↔ n ∣ a := by simp [Fin.ext_iff, Nat.dvd_iff_mod_eq_zero] @[deprecated (since := "2024-04-17")] alias nat_cast_eq_zero := natCast_eq_zero @[simp] theorem natCast_eq_last (n) : (n : Fin (n + 1)) = Fin.last n := by ext; simp @[deprecated (since := "2024-05-04")] alias cast_nat_eq_last := natCast_eq_last theorem le_val_last (i : Fin (n + 1)) : i ≤ n := by rw [Fin.natCast_eq_last] exact Fin.le_last i variable {a b : ℕ} lemma natCast_le_natCast (han : a ≤ n) (hbn : b ≤ n) : (a : Fin (n + 1)) ≤ b ↔ a ≤ b := by rw [← Nat.lt_succ_iff] at han hbn simp [le_iff_val_le_val, -val_fin_le, Nat.mod_eq_of_lt, han, hbn] lemma natCast_lt_natCast (han : a ≤ n) (hbn : b ≤ n) : (a : Fin (n + 1)) < b ↔ a < b := by rw [← Nat.lt_succ_iff] at han hbn; simp [lt_iff_val_lt_val, Nat.mod_eq_of_lt, han, hbn] lemma natCast_mono (hbn : b ≤ n) (hab : a ≤ b) : (a : Fin (n + 1)) ≤ b := (natCast_le_natCast (hab.trans hbn) hbn).2 hab lemma natCast_strictMono (hbn : b ≤ n) (hab : a < b) : (a : Fin (n + 1)) < b := (natCast_lt_natCast (hab.le.trans hbn) hbn).2 hab end OfNatCoe @[simp] theorem one_eq_zero_iff [NeZero n] : (1 : Fin n) = 0 ↔ n = 1 := by obtain _ | _ | n := n <;> simp [Fin.ext_iff] @[simp] theorem zero_eq_one_iff [NeZero n] : (0 : Fin n) = 1 ↔ n = 1 := by rw [eq_comm, one_eq_zero_iff] end Add section Succ /-! ### succ and casts into larger Fin types -/ lemma succ_injective (n : ℕ) : Injective (@Fin.succ n) := fun a b ↦ by simp [Fin.ext_iff] /-- `Fin.succ` as an `Embedding` -/ def succEmb (n : ℕ) : Fin n ↪ Fin (n + 1) where toFun := succ inj' := succ_injective _ @[simp] theorem val_succEmb : ⇑(succEmb n) = Fin.succ := rfl @[simp] theorem exists_succ_eq {x : Fin (n + 1)} : (∃ y, Fin.succ y = x) ↔ x ≠ 0 := ⟨fun ⟨_, hy⟩ => hy ▸ succ_ne_zero _, x.cases (fun h => h.irrefl.elim) (fun _ _ => ⟨_, rfl⟩)⟩ theorem exists_succ_eq_of_ne_zero {x : Fin (n + 1)} (h : x ≠ 0) : ∃ y, Fin.succ y = x := exists_succ_eq.mpr h @[simp] theorem succ_zero_eq_one' [NeZero n] : Fin.succ (0 : Fin n) = 1 := by cases n · exact (NeZero.ne 0 rfl).elim · rfl theorem one_pos' [NeZero n] : (0 : Fin (n + 1)) < 1 := succ_zero_eq_one' (n := n) ▸ succ_pos _ theorem zero_ne_one' [NeZero n] : (0 : Fin (n + 1)) ≠ 1 := Fin.ne_of_lt one_pos' /-- The `Fin.succ_one_eq_two` in `Lean` only applies in `Fin (n+2)`. This one instead uses a `NeZero n` typeclass hypothesis. -/ @[simp] theorem succ_one_eq_two' [NeZero n] : Fin.succ (1 : Fin (n + 1)) = 2 := by cases n · exact (NeZero.ne 0 rfl).elim · rfl -- Version of `succ_one_eq_two` to be used by `dsimp`. -- Note the `'` swapped around due to a move to std4. /-- The `Fin.le_zero_iff` in `Lean` only applies in `Fin (n+1)`. This one instead uses a `NeZero n` typeclass hypothesis. -/ @[simp] theorem le_zero_iff' {n : ℕ} [NeZero n] {k : Fin n} : k ≤ 0 ↔ k = 0 := ⟨fun h => Fin.ext <| by rw [Nat.eq_zero_of_le_zero h]; rfl, by rintro rfl; exact Nat.le_refl _⟩ -- Move to Batteries? @[simp] theorem cast_refl {n : Nat} (h : n = n) : Fin.cast h = id := rfl -- TODO: Move to Batteries @[simp] lemma castLE_inj {hmn : m ≤ n} {a b : Fin m} : castLE hmn a = castLE hmn b ↔ a = b := by simp [Fin.ext_iff] @[simp] lemma castAdd_inj {a b : Fin m} : castAdd n a = castAdd n b ↔ a = b := by simp [Fin.ext_iff] attribute [simp] castSucc_inj lemma castLE_injective (hmn : m ≤ n) : Injective (castLE hmn) := fun _ _ hab ↦ Fin.ext (congr_arg val hab :) lemma castAdd_injective (m n : ℕ) : Injective (@Fin.castAdd m n) := castLE_injective _ lemma castSucc_injective (n : ℕ) : Injective (@Fin.castSucc n) := castAdd_injective _ _ /-- `Fin.castLE` as an `Embedding`, `castLEEmb h i` embeds `i` into a larger `Fin` type. -/ @[simps! apply] def castLEEmb (h : n ≤ m) : Fin n ↪ Fin m where toFun := castLE h inj' := castLE_injective _ @[simp, norm_cast] lemma coe_castLEEmb {m n} (hmn : m ≤ n) : castLEEmb hmn = castLE hmn := rfl /- The next proof can be golfed a lot using `Fintype.card`. It is written this way to define `ENat.card` and `Nat.card` without a `Fintype` dependency (not done yet). -/ assert_not_exists Fintype lemma nonempty_embedding_iff : Nonempty (Fin n ↪ Fin m) ↔ n ≤ m := by refine ⟨fun h ↦ ?_, fun h ↦ ⟨castLEEmb h⟩⟩ induction n generalizing m with | zero => exact m.zero_le | succ n ihn => cases' h with e rcases exists_eq_succ_of_ne_zero (pos_iff_nonempty.2 (Nonempty.map e inferInstance)).ne' with ⟨m, rfl⟩ refine Nat.succ_le_succ <| ihn ⟨?_⟩ refine ⟨fun i ↦ (e.setValue 0 0 i.succ).pred (mt e.setValue_eq_iff.1 i.succ_ne_zero), fun i j h ↦ ?_⟩ simpa only [pred_inj, EmbeddingLike.apply_eq_iff_eq, succ_inj] using h lemma equiv_iff_eq : Nonempty (Fin m ≃ Fin n) ↔ m = n := ⟨fun ⟨e⟩ ↦ le_antisymm (nonempty_embedding_iff.1 ⟨e⟩) (nonempty_embedding_iff.1 ⟨e.symm⟩), fun h ↦ h ▸ ⟨.refl _⟩⟩ @[simp] lemma castLE_castSucc {n m} (i : Fin n) (h : n + 1 ≤ m) : i.castSucc.castLE h = i.castLE (Nat.le_of_succ_le h) := rfl @[simp] lemma castLE_comp_castSucc {n m} (h : n + 1 ≤ m) : Fin.castLE h ∘ Fin.castSucc = Fin.castLE (Nat.le_of_succ_le h) := rfl @[simp] lemma castLE_rfl (n : ℕ) : Fin.castLE (le_refl n) = id := rfl @[simp] theorem range_castLE {n k : ℕ} (h : n ≤ k) : Set.range (castLE h) = { i : Fin k | (i : ℕ) < n } := Set.ext fun x => ⟨fun ⟨y, hy⟩ => hy ▸ y.2, fun hx => ⟨⟨x, hx⟩, rfl⟩⟩ @[simp] theorem coe_of_injective_castLE_symm {n k : ℕ} (h : n ≤ k) (i : Fin k) (hi) : ((Equiv.ofInjective _ (castLE_injective h)).symm ⟨i, hi⟩ : ℕ) = i := by rw [← coe_castLE h] exact congr_arg Fin.val (Equiv.apply_ofInjective_symm _ _) theorem leftInverse_cast (eq : n = m) : LeftInverse (cast eq.symm) (cast eq) := fun _ => rfl theorem rightInverse_cast (eq : n = m) : RightInverse (cast eq.symm) (cast eq) := fun _ => rfl theorem cast_le_cast (eq : n = m) {a b : Fin n} : cast eq a ≤ cast eq b ↔ a ≤ b := Iff.rfl /-- The 'identity' equivalence between `Fin m` and `Fin n` when `m = n`. -/ @[simps] def _root_.finCongr (eq : n = m) : Fin n ≃ Fin m where toFun := cast eq invFun := cast eq.symm left_inv := leftInverse_cast eq right_inv := rightInverse_cast eq @[simp] lemma _root_.finCongr_apply_mk (h : m = n) (k : ℕ) (hk : k < m) : finCongr h ⟨k, hk⟩ = ⟨k, h ▸ hk⟩ := rfl @[simp] lemma _root_.finCongr_refl (h : n = n := rfl) : finCongr h = Equiv.refl (Fin n) := by ext; simp @[simp] lemma _root_.finCongr_symm (h : m = n) : (finCongr h).symm = finCongr h.symm := rfl @[simp] lemma _root_.finCongr_apply_coe (h : m = n) (k : Fin m) : (finCongr h k : ℕ) = k := rfl lemma _root_.finCongr_symm_apply_coe (h : m = n) (k : Fin n) : ((finCongr h).symm k : ℕ) = k := rfl /-- While in many cases `finCongr` is better than `Equiv.cast`/`cast`, sometimes we want to apply a generic theorem about `cast`. -/ lemma _root_.finCongr_eq_equivCast (h : n = m) : finCongr h = .cast (h ▸ rfl) := by subst h; simp @[simp] theorem cast_zero {n' : ℕ} [NeZero n] {h : n = n'} : cast h (0 : Fin n) = by { haveI : NeZero n' := by {rw [← h]; infer_instance}; exact 0} := rfl /-- While in many cases `Fin.cast` is better than `Equiv.cast`/`cast`, sometimes we want to apply a generic theorem about `cast`. -/ theorem cast_eq_cast (h : n = m) : (cast h : Fin n → Fin m) = _root_.cast (h ▸ rfl) := by subst h ext rfl /-- `Fin.castAdd` as an `Embedding`, `castAddEmb m i` embeds `i : Fin n` in `Fin (n+m)`. See also `Fin.natAddEmb` and `Fin.addNatEmb`. -/ @[simps! apply] def castAddEmb (m) : Fin n ↪ Fin (n + m) := castLEEmb (le_add_right n m) /-- `Fin.castSucc` as an `Embedding`, `castSuccEmb i` embeds `i : Fin n` in `Fin (n+1)`. -/ @[simps! apply] def castSuccEmb : Fin n ↪ Fin (n + 1) := castAddEmb _ @[simp, norm_cast] lemma coe_castSuccEmb : (castSuccEmb : Fin n → Fin (n + 1)) = Fin.castSucc := rfl @[simp] theorem castSucc_le_castSucc_iff {a b : Fin n} : castSucc a ≤ castSucc b ↔ a ≤ b := Iff.rfl @[simp] theorem succ_le_castSucc_iff {a b : Fin n} : succ a ≤ castSucc b ↔ a < b := by rw [le_castSucc_iff, succ_lt_succ_iff] @[simp] theorem castSucc_lt_succ_iff {a b : Fin n} : castSucc a < succ b ↔ a ≤ b := by rw [castSucc_lt_iff_succ_le, succ_le_succ_iff] theorem le_of_castSucc_lt_of_succ_lt {a b : Fin (n + 1)} {i : Fin n} (hl : castSucc i < a) (hu : b < succ i) : b < a := by simp [Fin.lt_def, -val_fin_lt] at *; omega theorem castSucc_lt_or_lt_succ (p : Fin (n + 1)) (i : Fin n) : castSucc i < p ∨ p < i.succ := by simp [Fin.lt_def, -val_fin_lt]; omega @[deprecated (since := "2024-05-30")] alias succAbove_lt_gt := castSucc_lt_or_lt_succ theorem succ_le_or_le_castSucc (p : Fin (n + 1)) (i : Fin n) : succ i ≤ p ∨ p ≤ i.castSucc := by rw [le_castSucc_iff, ← castSucc_lt_iff_succ_le] exact p.castSucc_lt_or_lt_succ i theorem exists_castSucc_eq_of_ne_last {x : Fin (n + 1)} (h : x ≠ (last _)) : ∃ y, Fin.castSucc y = x := exists_castSucc_eq.mpr h theorem forall_fin_succ' {P : Fin (n + 1) → Prop} : (∀ i, P i) ↔ (∀ i : Fin n, P i.castSucc) ∧ P (.last _) := ⟨fun H => ⟨fun _ => H _, H _⟩, fun ⟨H0, H1⟩ i => Fin.lastCases H1 H0 i⟩ -- to match `Fin.eq_zero_or_eq_succ` theorem eq_castSucc_or_eq_last {n : Nat} (i : Fin (n + 1)) : (∃ j : Fin n, i = j.castSucc) ∨ i = last n := i.lastCases (Or.inr rfl) (Or.inl ⟨·, rfl⟩) theorem exists_fin_succ' {P : Fin (n + 1) → Prop} : (∃ i, P i) ↔ (∃ i : Fin n, P i.castSucc) ∨ P (.last _) := ⟨fun ⟨i, h⟩ => Fin.lastCases Or.inr (fun i hi => Or.inl ⟨i, hi⟩) i h, fun h => h.elim (fun ⟨i, hi⟩ => ⟨i.castSucc, hi⟩) (fun h => ⟨.last _, h⟩)⟩ /-- The `Fin.castSucc_zero` in `Lean` only applies in `Fin (n+1)`. This one instead uses a `NeZero n` typeclass hypothesis. -/ @[simp] theorem castSucc_zero' [NeZero n] : castSucc (0 : Fin n) = 0 := rfl /-- `castSucc i` is positive when `i` is positive. The `Fin.castSucc_pos` in `Lean` only applies in `Fin (n+1)`. This one instead uses a `NeZero n` typeclass hypothesis. -/ theorem castSucc_pos' [NeZero n] {i : Fin n} (h : 0 < i) : 0 < castSucc i := by simpa [lt_iff_val_lt_val] using h /-- The `Fin.castSucc_eq_zero_iff` in `Lean` only applies in `Fin (n+1)`. This one instead uses a `NeZero n` typeclass hypothesis. -/ @[simp] theorem castSucc_eq_zero_iff' [NeZero n] (a : Fin n) : castSucc a = 0 ↔ a = 0 := Fin.ext_iff.trans <| (Fin.ext_iff.trans <| by simp).symm /-- The `Fin.castSucc_ne_zero_iff` in `Lean` only applies in `Fin (n+1)`. This one instead uses a `NeZero n` typeclass hypothesis. -/ theorem castSucc_ne_zero_iff' [NeZero n] (a : Fin n) : castSucc a ≠ 0 ↔ a ≠ 0 := not_iff_not.mpr <| castSucc_eq_zero_iff' a theorem castSucc_ne_zero_of_lt {p i : Fin n} (h : p < i) : castSucc i ≠ 0 := by cases n · exact i.elim0 · rw [castSucc_ne_zero_iff', Ne, Fin.ext_iff] exact ((zero_le _).trans_lt h).ne' theorem succ_ne_last_iff (a : Fin (n + 1)) : succ a ≠ last (n + 1) ↔ a ≠ last n := not_iff_not.mpr <| succ_eq_last_succ a theorem succ_ne_last_of_lt {p i : Fin n} (h : i < p) : succ i ≠ last n := by cases n · exact i.elim0 · rw [succ_ne_last_iff, Ne, Fin.ext_iff] exact ((le_last _).trans_lt' h).ne @[norm_cast, simp] theorem coe_eq_castSucc {a : Fin n} : (a : Fin (n + 1)) = castSucc a := by ext exact val_cast_of_lt (Nat.lt.step a.is_lt) theorem coe_succ_lt_iff_lt {n : ℕ} {j k : Fin n} : (j : Fin <| n + 1) < k ↔ j < k := by simp only [coe_eq_castSucc, castSucc_lt_castSucc_iff] @[simp] theorem range_castSucc {n : ℕ} : Set.range (castSucc : Fin n → Fin n.succ) = ({ i | (i : ℕ) < n } : Set (Fin n.succ)) := range_castLE (by omega) @[simp] theorem coe_of_injective_castSucc_symm {n : ℕ} (i : Fin n.succ) (hi) : ((Equiv.ofInjective castSucc (castSucc_injective _)).symm ⟨i, hi⟩ : ℕ) = i := by rw [← coe_castSucc] exact congr_arg val (Equiv.apply_ofInjective_symm _ _) /-- `Fin.addNat` as an `Embedding`, `addNatEmb m i` adds `m` to `i`, generalizes `Fin.succ`. -/ @[simps! apply] def addNatEmb (m) : Fin n ↪ Fin (n + m) where toFun := (addNat · m) inj' a b := by simp [Fin.ext_iff] /-- `Fin.natAdd` as an `Embedding`, `natAddEmb n i` adds `n` to `i` "on the left". -/ @[simps! apply] def natAddEmb (n) {m} : Fin m ↪ Fin (n + m) where toFun := natAdd n inj' a b := by simp [Fin.ext_iff] end Succ section Pred /-! ### pred -/ theorem pred_one' [NeZero n] (h := (zero_ne_one' (n := n)).symm) : Fin.pred (1 : Fin (n + 1)) h = 0 := by simp_rw [Fin.ext_iff, coe_pred, val_one', val_zero', Nat.sub_eq_zero_iff_le, Nat.mod_le] theorem pred_last (h := Fin.ext_iff.not.2 last_pos'.ne') : pred (last (n + 1)) h = last n := by simp_rw [← succ_last, pred_succ] theorem pred_lt_iff {j : Fin n} {i : Fin (n + 1)} (hi : i ≠ 0) : pred i hi < j ↔ i < succ j := by rw [← succ_lt_succ_iff, succ_pred] theorem lt_pred_iff {j : Fin n} {i : Fin (n + 1)} (hi : i ≠ 0) : j < pred i hi ↔ succ j < i := by rw [← succ_lt_succ_iff, succ_pred] theorem pred_le_iff {j : Fin n} {i : Fin (n + 1)} (hi : i ≠ 0) : pred i hi ≤ j ↔ i ≤ succ j := by rw [← succ_le_succ_iff, succ_pred] theorem le_pred_iff {j : Fin n} {i : Fin (n + 1)} (hi : i ≠ 0) : j ≤ pred i hi ↔ succ j ≤ i := by rw [← succ_le_succ_iff, succ_pred] theorem castSucc_pred_eq_pred_castSucc {a : Fin (n + 1)} (ha : a ≠ 0) (ha' := a.castSucc_ne_zero_iff.mpr ha) : (a.pred ha).castSucc = (castSucc a).pred ha' := rfl theorem castSucc_pred_add_one_eq {a : Fin (n + 1)} (ha : a ≠ 0) : (a.pred ha).castSucc + 1 = a := by cases' a using cases with a · exact (ha rfl).elim · rw [pred_succ, coeSucc_eq_succ] theorem le_pred_castSucc_iff {a b : Fin (n + 1)} (ha : castSucc a ≠ 0) : b ≤ (castSucc a).pred ha ↔ b < a := by rw [le_pred_iff, succ_le_castSucc_iff] theorem pred_castSucc_lt_iff {a b : Fin (n + 1)} (ha : castSucc a ≠ 0) : (castSucc a).pred ha < b ↔ a ≤ b := by rw [pred_lt_iff, castSucc_lt_succ_iff] theorem pred_castSucc_lt {a : Fin (n + 1)} (ha : castSucc a ≠ 0) : (castSucc a).pred ha < a := by rw [pred_castSucc_lt_iff, le_def] theorem le_castSucc_pred_iff {a b : Fin (n + 1)} (ha : a ≠ 0) : b ≤ castSucc (a.pred ha) ↔ b < a := by rw [castSucc_pred_eq_pred_castSucc, le_pred_castSucc_iff] theorem castSucc_pred_lt_iff {a b : Fin (n + 1)} (ha : a ≠ 0) : castSucc (a.pred ha) < b ↔ a ≤ b := by rw [castSucc_pred_eq_pred_castSucc, pred_castSucc_lt_iff] theorem castSucc_pred_lt {a : Fin (n + 1)} (ha : a ≠ 0) : castSucc (a.pred ha) < a := by rw [castSucc_pred_lt_iff, le_def] end Pred section CastPred /-- `castPred i` sends `i : Fin (n + 1)` to `Fin n` as long as i ≠ last n. -/ @[inline] def castPred (i : Fin (n + 1)) (h : i ≠ last n) : Fin n := castLT i (val_lt_last h) @[simp] lemma castLT_eq_castPred (i : Fin (n + 1)) (h : i < last _) (h' := Fin.ext_iff.not.2 h.ne) : castLT i h = castPred i h' := rfl @[simp] lemma coe_castPred (i : Fin (n + 1)) (h : i ≠ last _) : (castPred i h : ℕ) = i := rfl @[simp] theorem castPred_castSucc {i : Fin n} (h' := Fin.ext_iff.not.2 (castSucc_lt_last i).ne) : castPred (castSucc i) h' = i := rfl @[simp] theorem castSucc_castPred (i : Fin (n + 1)) (h : i ≠ last n) : castSucc (i.castPred h) = i := by rcases exists_castSucc_eq.mpr h with ⟨y, rfl⟩ rw [castPred_castSucc] theorem castPred_eq_iff_eq_castSucc (i : Fin (n + 1)) (hi : i ≠ last _) (j : Fin n) : castPred i hi = j ↔ i = castSucc j := ⟨fun h => by rw [← h, castSucc_castPred], fun h => by simp_rw [h, castPred_castSucc]⟩ @[simp] theorem castPred_mk (i : ℕ) (h₁ : i < n) (h₂ := h₁.trans (Nat.lt_succ_self _)) (h₃ : ⟨i, h₂⟩ ≠ last _ := (ne_iff_vne _ _).mpr (val_last _ ▸ h₁.ne)) : castPred ⟨i, h₂⟩ h₃ = ⟨i, h₁⟩ := rfl theorem castPred_le_castPred_iff {i j : Fin (n + 1)} {hi : i ≠ last n} {hj : j ≠ last n} : castPred i hi ≤ castPred j hj ↔ i ≤ j := Iff.rfl theorem castPred_lt_castPred_iff {i j : Fin (n + 1)} {hi : i ≠ last n} {hj : j ≠ last n} : castPred i hi < castPred j hj ↔ i < j := Iff.rfl theorem castPred_lt_iff {j : Fin n} {i : Fin (n + 1)} (hi : i ≠ last n) : castPred i hi < j ↔ i < castSucc j := by rw [← castSucc_lt_castSucc_iff, castSucc_castPred] theorem lt_castPred_iff {j : Fin n} {i : Fin (n + 1)} (hi : i ≠ last n) : j < castPred i hi ↔ castSucc j < i := by rw [← castSucc_lt_castSucc_iff, castSucc_castPred] theorem castPred_le_iff {j : Fin n} {i : Fin (n + 1)} (hi : i ≠ last n) : castPred i hi ≤ j ↔ i ≤ castSucc j := by rw [← castSucc_le_castSucc_iff, castSucc_castPred] theorem le_castPred_iff {j : Fin n} {i : Fin (n + 1)} (hi : i ≠ last n) : j ≤ castPred i hi ↔ castSucc j ≤ i := by rw [← castSucc_le_castSucc_iff, castSucc_castPred] theorem castPred_inj {i j : Fin (n + 1)} {hi : i ≠ last n} {hj : j ≠ last n} : castPred i hi = castPred j hj ↔ i = j := by simp_rw [Fin.ext_iff, le_antisymm_iff, ← le_def, castPred_le_castPred_iff] theorem castPred_zero' [NeZero n] (h := Fin.ext_iff.not.2 last_pos'.ne) : castPred (0 : Fin (n + 1)) h = 0 := rfl theorem castPred_zero (h := Fin.ext_iff.not.2 last_pos.ne) : castPred (0 : Fin (n + 2)) h = 0 := rfl @[simp] theorem castPred_one [NeZero n] (h := Fin.ext_iff.not.2 one_lt_last.ne) : castPred (1 : Fin (n + 2)) h = 1 := by cases n · exact subsingleton_one.elim _ 1 · rfl theorem rev_pred {i : Fin (n + 1)} (h : i ≠ 0) (h' := rev_ne_iff.mpr ((rev_last _).symm ▸ h)) : rev (pred i h) = castPred (rev i) h' := by rw [← castSucc_inj, castSucc_castPred, ← rev_succ, succ_pred] theorem rev_castPred {i : Fin (n + 1)} (h : i ≠ last n) (h' := rev_ne_iff.mpr ((rev_zero _).symm ▸ h)) : rev (castPred i h) = pred (rev i) h' := by rw [← succ_inj, succ_pred, ← rev_castSucc, castSucc_castPred] theorem succ_castPred_eq_castPred_succ {a : Fin (n + 1)} (ha : a ≠ last n) (ha' := a.succ_ne_last_iff.mpr ha) : (a.castPred ha).succ = (succ a).castPred ha' := rfl theorem succ_castPred_eq_add_one {a : Fin (n + 1)} (ha : a ≠ last n) : (a.castPred ha).succ = a + 1 := by cases' a using lastCases with a · exact (ha rfl).elim · rw [castPred_castSucc, coeSucc_eq_succ] theorem castpred_succ_le_iff {a b : Fin (n + 1)} (ha : succ a ≠ last (n + 1)) : (succ a).castPred ha ≤ b ↔ a < b := by rw [castPred_le_iff, succ_le_castSucc_iff] theorem lt_castPred_succ_iff {a b : Fin (n + 1)} (ha : succ a ≠ last (n + 1)) : b < (succ a).castPred ha ↔ b ≤ a := by rw [lt_castPred_iff, castSucc_lt_succ_iff] theorem lt_castPred_succ {a : Fin (n + 1)} (ha : succ a ≠ last (n + 1)) : a < (succ a).castPred ha := by rw [lt_castPred_succ_iff, le_def] theorem succ_castPred_le_iff {a b : Fin (n + 1)} (ha : a ≠ last n) : succ (a.castPred ha) ≤ b ↔ a < b := by rw [succ_castPred_eq_castPred_succ ha, castpred_succ_le_iff] theorem lt_succ_castPred_iff {a b : Fin (n + 1)} (ha : a ≠ last n) : b < succ (a.castPred ha) ↔ b ≤ a := by rw [succ_castPred_eq_castPred_succ ha, lt_castPred_succ_iff] theorem lt_succ_castPred {a : Fin (n + 1)} (ha : a ≠ last n) : a < succ (a.castPred ha) := by rw [lt_succ_castPred_iff, le_def] theorem castPred_le_pred_iff {a b : Fin (n + 1)} (ha : a ≠ last n) (hb : b ≠ 0) : castPred a ha ≤ pred b hb ↔ a < b := by rw [le_pred_iff, succ_castPred_le_iff] theorem pred_lt_castPred_iff {a b : Fin (n + 1)} (ha : a ≠ 0) (hb : b ≠ last n) : pred a ha < castPred b hb ↔ a ≤ b := by rw [lt_castPred_iff, castSucc_pred_lt_iff ha] theorem pred_lt_castPred {a : Fin (n + 1)} (h₁ : a ≠ 0) (h₂ : a ≠ last n) : pred a h₁ < castPred a h₂ := by rw [pred_lt_castPred_iff, le_def] end CastPred section SuccAbove variable {p : Fin (n + 1)} {i j : Fin n} /-- `succAbove p i` embeds `Fin n` into `Fin (n + 1)` with a hole around `p`. -/ def succAbove (p : Fin (n + 1)) (i : Fin n) : Fin (n + 1) := if castSucc i < p then i.castSucc else i.succ /-- Embedding `i : Fin n` into `Fin (n + 1)` with a hole around `p : Fin (n + 1)` embeds `i` by `castSucc` when the resulting `i.castSucc < p`. -/ lemma succAbove_of_castSucc_lt (p : Fin (n + 1)) (i : Fin n) (h : castSucc i < p) : p.succAbove i = castSucc i := if_pos h lemma succAbove_of_succ_le (p : Fin (n + 1)) (i : Fin n) (h : succ i ≤ p) : p.succAbove i = castSucc i := succAbove_of_castSucc_lt _ _ (castSucc_lt_iff_succ_le.mpr h) /-- Embedding `i : Fin n` into `Fin (n + 1)` with a hole around `p : Fin (n + 1)` embeds `i` by `succ` when the resulting `p < i.succ`. -/ lemma succAbove_of_le_castSucc (p : Fin (n + 1)) (i : Fin n) (h : p ≤ castSucc i) : p.succAbove i = i.succ := if_neg (Fin.not_lt.2 h) lemma succAbove_of_lt_succ (p : Fin (n + 1)) (i : Fin n) (h : p < succ i) : p.succAbove i = succ i := succAbove_of_le_castSucc _ _ (le_castSucc_iff.mpr h) lemma succAbove_succ_of_lt (p i : Fin n) (h : p < i) : succAbove p.succ i = i.succ := succAbove_of_lt_succ _ _ (succ_lt_succ_iff.mpr h) lemma succAbove_succ_of_le (p i : Fin n) (h : i ≤ p) : succAbove p.succ i = i.castSucc := succAbove_of_succ_le _ _ (succ_le_succ_iff.mpr h) @[simp] lemma succAbove_succ_self (j : Fin n) : j.succ.succAbove j = j.castSucc := succAbove_succ_of_le _ _ Fin.le_rfl lemma succAbove_castSucc_of_lt (p i : Fin n) (h : i < p) : succAbove p.castSucc i = i.castSucc := succAbove_of_castSucc_lt _ _ (castSucc_lt_castSucc_iff.2 h) lemma succAbove_castSucc_of_le (p i : Fin n) (h : p ≤ i) : succAbove p.castSucc i = i.succ := succAbove_of_le_castSucc _ _ (castSucc_le_castSucc_iff.2 h) @[simp] lemma succAbove_castSucc_self (j : Fin n) : succAbove j.castSucc j = j.succ := succAbove_castSucc_of_le _ _ Fin.le_rfl lemma succAbove_pred_of_lt (p i : Fin (n + 1)) (h : p < i) (hi := Fin.ne_of_gt $ Fin.lt_of_le_of_lt p.zero_le h) : succAbove p (i.pred hi) = i := by rw [succAbove_of_lt_succ _ _ (succ_pred _ _ ▸ h), succ_pred] lemma succAbove_pred_of_le (p i : Fin (n + 1)) (h : i ≤ p) (hi : i ≠ 0) : succAbove p (i.pred hi) = (i.pred hi).castSucc := succAbove_of_succ_le _ _ (succ_pred _ _ ▸ h) @[simp] lemma succAbove_pred_self (p : Fin (n + 1)) (h : p ≠ 0) : succAbove p (p.pred h) = (p.pred h).castSucc := succAbove_pred_of_le _ _ Fin.le_rfl h lemma succAbove_castPred_of_lt (p i : Fin (n + 1)) (h : i < p) (hi := Fin.ne_of_lt $ Nat.lt_of_lt_of_le h p.le_last) : succAbove p (i.castPred hi) = i := by rw [succAbove_of_castSucc_lt _ _ (castSucc_castPred _ _ ▸ h), castSucc_castPred] lemma succAbove_castPred_of_le (p i : Fin (n + 1)) (h : p ≤ i) (hi : i ≠ last n) : succAbove p (i.castPred hi) = (i.castPred hi).succ := succAbove_of_le_castSucc _ _ (castSucc_castPred _ _ ▸ h) lemma succAbove_castPred_self (p : Fin (n + 1)) (h : p ≠ last n) : succAbove p (p.castPred h) = (p.castPred h).succ := succAbove_castPred_of_le _ _ Fin.le_rfl h lemma succAbove_rev_left (p : Fin (n + 1)) (i : Fin n) : p.rev.succAbove i = (p.succAbove i.rev).rev := by obtain h | h := (rev p).succ_le_or_le_castSucc i · rw [succAbove_of_succ_le _ _ h, succAbove_of_le_castSucc _ _ (rev_succ _ ▸ (le_rev_iff.mpr h)), rev_succ, rev_rev] · rw [succAbove_of_le_castSucc _ _ h, succAbove_of_succ_le _ _ (rev_castSucc _ ▸ (rev_le_iff.mpr h)), rev_castSucc, rev_rev] lemma succAbove_rev_right (p : Fin (n + 1)) (i : Fin n) : p.succAbove i.rev = (p.rev.succAbove i).rev := by rw [succAbove_rev_left, rev_rev] /-- Embedding `i : Fin n` into `Fin (n + 1)` with a hole around `p : Fin (n + 1)` never results in `p` itself -/ lemma succAbove_ne (p : Fin (n + 1)) (i : Fin n) : p.succAbove i ≠ p := by rcases p.castSucc_lt_or_lt_succ i with (h | h) · rw [succAbove_of_castSucc_lt _ _ h] exact Fin.ne_of_lt h · rw [succAbove_of_lt_succ _ _ h] exact Fin.ne_of_gt h lemma ne_succAbove (p : Fin (n + 1)) (i : Fin n) : p ≠ p.succAbove i := (succAbove_ne _ _).symm /-- Given a fixed pivot `p : Fin (n + 1)`, `p.succAbove` is injective. -/ lemma succAbove_right_injective : Injective p.succAbove := by rintro i j hij unfold succAbove at hij split_ifs at hij with hi hj hj · exact castSucc_injective _ hij · rw [hij] at hi cases hj $ Nat.lt_trans j.castSucc_lt_succ hi · rw [← hij] at hj cases hi $ Nat.lt_trans i.castSucc_lt_succ hj · exact succ_injective _ hij /-- Given a fixed pivot `p : Fin (n + 1)`, `p.succAbove` is injective. -/ lemma succAbove_right_inj : p.succAbove i = p.succAbove j ↔ i = j := succAbove_right_injective.eq_iff /-- `Fin.succAbove p` as an `Embedding`. -/ @[simps!] def succAboveEmb (p : Fin (n + 1)) : Fin n ↪ Fin (n + 1) := ⟨p.succAbove, succAbove_right_injective⟩ @[simp, norm_cast] lemma coe_succAboveEmb (p : Fin (n + 1)) : p.succAboveEmb = p.succAbove := rfl @[simp] lemma succAbove_ne_zero_zero [NeZero n] {a : Fin (n + 1)} (ha : a ≠ 0) : a.succAbove 0 = 0 := by rw [Fin.succAbove_of_castSucc_lt] · exact castSucc_zero' · exact Fin.pos_iff_ne_zero.2 ha lemma succAbove_eq_zero_iff [NeZero n] {a : Fin (n + 1)} {b : Fin n} (ha : a ≠ 0) : a.succAbove b = 0 ↔ b = 0 := by rw [← succAbove_ne_zero_zero ha, succAbove_right_inj] lemma succAbove_ne_zero [NeZero n] {a : Fin (n + 1)} {b : Fin n} (ha : a ≠ 0) (hb : b ≠ 0) : a.succAbove b ≠ 0 := mt (succAbove_eq_zero_iff ha).mp hb /-- Embedding `Fin n` into `Fin (n + 1)` with a hole around zero embeds by `succ`. -/ @[simp] lemma succAbove_zero : succAbove (0 : Fin (n + 1)) = Fin.succ := rfl lemma succAbove_zero_apply (i : Fin n) : succAbove 0 i = succ i := by rw [succAbove_zero] @[simp] lemma succAbove_ne_last_last {a : Fin (n + 2)} (h : a ≠ last (n + 1)) : a.succAbove (last n) = last (n + 1) := by rw [succAbove_of_lt_succ _ _ (succ_last _ ▸ lt_last_iff_ne_last.2 h), succ_last] lemma succAbove_eq_last_iff {a : Fin (n + 2)} {b : Fin (n + 1)} (ha : a ≠ last _) : a.succAbove b = last _ ↔ b = last _ := by simp [← succAbove_ne_last_last ha, succAbove_right_inj] lemma succAbove_ne_last {a : Fin (n + 2)} {b : Fin (n + 1)} (ha : a ≠ last _) (hb : b ≠ last _) : a.succAbove b ≠ last _ := mt (succAbove_eq_last_iff ha).mp hb /-- Embedding `Fin n` into `Fin (n + 1)` with a hole around `last n` embeds by `castSucc`. -/ @[simp] lemma succAbove_last : succAbove (last n) = castSucc := by ext; simp only [succAbove_of_castSucc_lt, castSucc_lt_last] lemma succAbove_last_apply (i : Fin n) : succAbove (last n) i = castSucc i := by rw [succAbove_last] @[deprecated (since := "2024-05-30")] lemma succAbove_lt_ge (p : Fin (n + 1)) (i : Fin n) : castSucc i < p ∨ p ≤ castSucc i := Nat.lt_or_ge (castSucc i) p /-- Embedding `i : Fin n` into `Fin (n + 1)` using a pivot `p` that is greater results in a value that is less than `p`. -/ lemma succAbove_lt_iff_castSucc_lt (p : Fin (n + 1)) (i : Fin n) : p.succAbove i < p ↔ castSucc i < p := by cases' castSucc_lt_or_lt_succ p i with H H · rwa [iff_true_right H, succAbove_of_castSucc_lt _ _ H] · rw [castSucc_lt_iff_succ_le, iff_false_right (Fin.not_le.2 H), succAbove_of_lt_succ _ _ H] exact Fin.not_lt.2 $ Fin.le_of_lt H lemma succAbove_lt_iff_succ_le (p : Fin (n + 1)) (i : Fin n) : p.succAbove i < p ↔ succ i ≤ p := by rw [succAbove_lt_iff_castSucc_lt, castSucc_lt_iff_succ_le] /-- Embedding `i : Fin n` into `Fin (n + 1)` using a pivot `p` that is lesser results in a value that is greater than `p`. -/ lemma lt_succAbove_iff_le_castSucc (p : Fin (n + 1)) (i : Fin n) : p < p.succAbove i ↔ p ≤ castSucc i := by cases' castSucc_lt_or_lt_succ p i with H H · rw [iff_false_right (Fin.not_le.2 H), succAbove_of_castSucc_lt _ _ H] exact Fin.not_lt.2 $ Fin.le_of_lt H · rwa [succAbove_of_lt_succ _ _ H, iff_true_left H, le_castSucc_iff] lemma lt_succAbove_iff_lt_castSucc (p : Fin (n + 1)) (i : Fin n) : p < p.succAbove i ↔ p < succ i := by rw [lt_succAbove_iff_le_castSucc, le_castSucc_iff] /-- Embedding a positive `Fin n` results in a positive `Fin (n + 1)` -/ lemma succAbove_pos [NeZero n] (p : Fin (n + 1)) (i : Fin n) (h : 0 < i) : 0 < p.succAbove i := by by_cases H : castSucc i < p · simpa [succAbove_of_castSucc_lt _ _ H] using castSucc_pos' h · simp [succAbove_of_le_castSucc _ _ (Fin.not_lt.1 H)] lemma castPred_succAbove (x : Fin n) (y : Fin (n + 1)) (h : castSucc x < y) (h' := Fin.ne_last_of_lt $ (succAbove_lt_iff_castSucc_lt ..).2 h) : (y.succAbove x).castPred h' = x := by rw [castPred_eq_iff_eq_castSucc, succAbove_of_castSucc_lt _ _ h] lemma pred_succAbove (x : Fin n) (y : Fin (n + 1)) (h : y ≤ castSucc x) (h' := Fin.ne_zero_of_lt $ (lt_succAbove_iff_le_castSucc ..).2 h) : (y.succAbove x).pred h' = x := by simp only [succAbove_of_le_castSucc _ _ h, pred_succ] lemma exists_succAbove_eq {x y : Fin (n + 1)} (h : x ≠ y) : ∃ z, y.succAbove z = x := by obtain hxy | hyx := Fin.lt_or_lt_of_ne h exacts [⟨_, succAbove_castPred_of_lt _ _ hxy⟩, ⟨_, succAbove_pred_of_lt _ _ hyx⟩] @[simp] lemma exists_succAbove_eq_iff {x y : Fin (n + 1)} : (∃ z, x.succAbove z = y) ↔ y ≠ x := ⟨by rintro ⟨y, rfl⟩; exact succAbove_ne _ _, exists_succAbove_eq⟩ /-- The range of `p.succAbove` is everything except `p`. -/ @[simp] lemma range_succAbove (p : Fin (n + 1)) : Set.range p.succAbove = {p}ᶜ := Set.ext fun _ => exists_succAbove_eq_iff @[simp] lemma range_succ (n : ℕ) : Set.range (Fin.succ : Fin n → Fin (n + 1)) = {0}ᶜ := by rw [← succAbove_zero]; exact range_succAbove (0 : Fin (n + 1)) /-- `succAbove` is injective at the pivot -/ lemma succAbove_left_injective : Injective (@succAbove n) := fun _ _ h => by simpa [range_succAbove] using congr_arg (fun f : Fin n → Fin (n + 1) => (Set.range f)ᶜ) h /-- `succAbove` is injective at the pivot -/ @[simp] lemma succAbove_left_inj {x y : Fin (n + 1)} : x.succAbove = y.succAbove ↔ x = y := succAbove_left_injective.eq_iff @[simp] lemma zero_succAbove {n : ℕ} (i : Fin n) : (0 : Fin (n + 1)).succAbove i = i.succ := rfl @[simp] lemma succ_succAbove_zero {n : ℕ} [NeZero n] (i : Fin n) : succAbove i.succ 0 = 0 := succAbove_of_castSucc_lt i.succ 0 (by simp only [castSucc_zero', succ_pos]) /-- `succ` commutes with `succAbove`. -/ @[simp] lemma succ_succAbove_succ {n : ℕ} (i : Fin (n + 1)) (j : Fin n) : i.succ.succAbove j.succ = (i.succAbove j).succ := by obtain h | h := i.lt_or_le (succ j) · rw [succAbove_of_lt_succ _ _ h, succAbove_succ_of_lt _ _ h] · rwa [succAbove_of_castSucc_lt _ _ h, succAbove_succ_of_le, succ_castSucc] /-- `castSucc` commutes with `succAbove`. -/ @[simp] lemma castSucc_succAbove_castSucc {n : ℕ} {i : Fin (n + 1)} {j : Fin n} : i.castSucc.succAbove j.castSucc = (i.succAbove j).castSucc := by rcases i.le_or_lt (castSucc j) with (h | h) · rw [succAbove_of_le_castSucc _ _ h, succAbove_castSucc_of_le _ _ h, succ_castSucc] · rw [succAbove_of_castSucc_lt _ _ h, succAbove_castSucc_of_lt _ _ h] /-- `pred` commutes with `succAbove`. -/ lemma pred_succAbove_pred {a : Fin (n + 2)} {b : Fin (n + 1)} (ha : a ≠ 0) (hb : b ≠ 0) (hk := succAbove_ne_zero ha hb) : (a.pred ha).succAbove (b.pred hb) = (a.succAbove b).pred hk := by simp_rw [← succ_inj (b := pred (succAbove a b) hk), ← succ_succAbove_succ, succ_pred] /-- `castPred` commutes with `succAbove`. -/ lemma castPred_succAbove_castPred {a : Fin (n + 2)} {b : Fin (n + 1)} (ha : a ≠ last (n + 1)) (hb : b ≠ last n) (hk := succAbove_ne_last ha hb) : (a.castPred ha).succAbove (b.castPred hb) = (a.succAbove b).castPred hk := by simp_rw [← castSucc_inj (b := (a.succAbove b).castPred hk), ← castSucc_succAbove_castSucc, castSucc_castPred] /-- `rev` commutes with `succAbove`. -/ lemma rev_succAbove (p : Fin (n + 1)) (i : Fin n) : rev (succAbove p i) = succAbove (rev p) (rev i) := by rw [succAbove_rev_left, rev_rev] --@[simp] -- Porting note: can be proved by `simp` lemma one_succAbove_zero {n : ℕ} : (1 : Fin (n + 2)).succAbove 0 = 0 := by rfl /-- By moving `succ` to the outside of this expression, we create opportunities for further simplification using `succAbove_zero` or `succ_succAbove_zero`. -/ @[simp] lemma succ_succAbove_one {n : ℕ} [NeZero n] (i : Fin (n + 1)) : i.succ.succAbove 1 = (i.succAbove 0).succ := by rw [← succ_zero_eq_one']; convert succ_succAbove_succ i 0 @[simp] lemma one_succAbove_succ {n : ℕ} (j : Fin n) : (1 : Fin (n + 2)).succAbove j.succ = j.succ.succ := by have := succ_succAbove_succ 0 j; rwa [succ_zero_eq_one, zero_succAbove] at this @[simp] lemma one_succAbove_one {n : ℕ} : (1 : Fin (n + 3)).succAbove 1 = 2 := by simpa only [succ_zero_eq_one, val_zero, zero_succAbove, succ_one_eq_two] using succ_succAbove_succ (0 : Fin (n + 2)) (0 : Fin (n + 2)) end SuccAbove section PredAbove /-- `predAbove p i` surjects `i : Fin (n+1)` into `Fin n` by subtracting one if `p < i`. -/ def predAbove (p : Fin n) (i : Fin (n + 1)) : Fin n := if h : castSucc p < i then pred i (Fin.ne_zero_of_lt h) else castPred i (Fin.ne_of_lt $ Fin.lt_of_le_of_lt (Fin.not_lt.1 h) (castSucc_lt_last _)) lemma predAbove_of_le_castSucc (p : Fin n) (i : Fin (n + 1)) (h : i ≤ castSucc p) (hi := Fin.ne_of_lt $ Fin.lt_of_le_of_lt h $ castSucc_lt_last _) : p.predAbove i = i.castPred hi := dif_neg $ Fin.not_lt.2 h lemma predAbove_of_lt_succ (p : Fin n) (i : Fin (n + 1)) (h : i < succ p) (hi := Fin.ne_last_of_lt h) : p.predAbove i = i.castPred hi := predAbove_of_le_castSucc _ _ (le_castSucc_iff.mpr h) lemma predAbove_of_castSucc_lt (p : Fin n) (i : Fin (n + 1)) (h : castSucc p < i) (hi := Fin.ne_zero_of_lt h) : p.predAbove i = i.pred hi := dif_pos h lemma predAbove_of_succ_le (p : Fin n) (i : Fin (n + 1)) (h : succ p ≤ i) (hi := Fin.ne_of_gt $ Fin.lt_of_lt_of_le (succ_pos _) h) : p.predAbove i = i.pred hi := predAbove_of_castSucc_lt _ _ (castSucc_lt_iff_succ_le.mpr h) lemma predAbove_succ_of_lt (p i : Fin n) (h : i < p) (hi := succ_ne_last_of_lt h) : p.predAbove (succ i) = (i.succ).castPred hi := by rw [predAbove_of_lt_succ _ _ (succ_lt_succ_iff.mpr h)] lemma predAbove_succ_of_le (p i : Fin n) (h : p ≤ i) : p.predAbove (succ i) = i := by rw [predAbove_of_succ_le _ _ (succ_le_succ_iff.mpr h), pred_succ] @[simp] lemma predAbove_succ_self (p : Fin n) : p.predAbove (succ p) = p := predAbove_succ_of_le _ _ Fin.le_rfl lemma predAbove_castSucc_of_lt (p i : Fin n) (h : p < i) (hi := castSucc_ne_zero_of_lt h) : p.predAbove (castSucc i) = i.castSucc.pred hi := by rw [predAbove_of_castSucc_lt _ _ (castSucc_lt_castSucc_iff.2 h)] lemma predAbove_castSucc_of_le (p i : Fin n) (h : i ≤ p) : p.predAbove (castSucc i) = i := by rw [predAbove_of_le_castSucc _ _ (castSucc_le_castSucc_iff.mpr h), castPred_castSucc] @[simp] lemma predAbove_castSucc_self (p : Fin n) : p.predAbove (castSucc p) = p := predAbove_castSucc_of_le _ _ Fin.le_rfl lemma predAbove_pred_of_lt (p i : Fin (n + 1)) (h : i < p) (hp := Fin.ne_zero_of_lt h) (hi := Fin.ne_last_of_lt h) : (pred p hp).predAbove i = castPred i hi := by rw [predAbove_of_lt_succ _ _ (succ_pred _ _ ▸ h)] lemma predAbove_pred_of_le (p i : Fin (n + 1)) (h : p ≤ i) (hp : p ≠ 0) (hi := Fin.ne_of_gt $ Fin.lt_of_lt_of_le (Fin.pos_iff_ne_zero.2 hp) h) : (pred p hp).predAbove i = pred i hi := by rw [predAbove_of_succ_le _ _ (succ_pred _ _ ▸ h)] lemma predAbove_pred_self (p : Fin (n + 1)) (hp : p ≠ 0) : (pred p hp).predAbove p = pred p hp := predAbove_pred_of_le _ _ Fin.le_rfl hp lemma predAbove_castPred_of_lt (p i : Fin (n + 1)) (h : p < i) (hp := Fin.ne_last_of_lt h) (hi := Fin.ne_zero_of_lt h) : (castPred p hp).predAbove i = pred i hi := by rw [predAbove_of_castSucc_lt _ _ (castSucc_castPred _ _ ▸ h)] lemma predAbove_castPred_of_le (p i : Fin (n + 1)) (h : i ≤ p) (hp : p ≠ last n) (hi := Fin.ne_of_lt $ Fin.lt_of_le_of_lt h $ Fin.lt_last_iff_ne_last.2 hp) : (castPred p hp).predAbove i = castPred i hi := by rw [predAbove_of_le_castSucc _ _ (castSucc_castPred _ _ ▸ h)] lemma predAbove_castPred_self (p : Fin (n + 1)) (hp : p ≠ last n) : (castPred p hp).predAbove p = castPred p hp := predAbove_castPred_of_le _ _ Fin.le_rfl hp lemma predAbove_rev_left (p : Fin n) (i : Fin (n + 1)) : p.rev.predAbove i = (p.predAbove i.rev).rev := by obtain h | h := (rev i).succ_le_or_le_castSucc p · rw [predAbove_of_succ_le _ _ h, rev_pred, predAbove_of_le_castSucc _ _ (rev_succ _ ▸ (le_rev_iff.mpr h)), castPred_inj, rev_rev] · rw [predAbove_of_le_castSucc _ _ h, rev_castPred, predAbove_of_succ_le _ _ (rev_castSucc _ ▸ (rev_le_iff.mpr h)), pred_inj, rev_rev] lemma predAbove_rev_right (p : Fin n) (i : Fin (n + 1)) : p.predAbove i.rev = (p.rev.predAbove i).rev := by rw [predAbove_rev_left, rev_rev] @[simp] lemma predAbove_right_zero [NeZero n] {i : Fin n} : predAbove (i : Fin n) 0 = 0 := by cases n · exact i.elim0 · rw [predAbove_of_le_castSucc _ _ (zero_le _), castPred_zero] @[simp] lemma predAbove_zero_succ [NeZero n] {i : Fin n} : predAbove 0 i.succ = i := by rw [predAbove_succ_of_le _ _ (Fin.zero_le' _)] @[simp] lemma succ_predAbove_zero [NeZero n] {j : Fin (n + 1)} (h : j ≠ 0) : succ (predAbove 0 j) = j := by rcases exists_succ_eq_of_ne_zero h with ⟨k, rfl⟩ rw [predAbove_zero_succ] @[simp] lemma predAbove_zero_of_ne_zero [NeZero n] {i : Fin (n + 1)} (hi : i ≠ 0) : predAbove 0 i = i.pred hi := by obtain ⟨y, rfl⟩ := exists_succ_eq.2 hi; exact predAbove_zero_succ lemma predAbove_zero [NeZero n] {i : Fin (n + 1)} : predAbove (0 : Fin n) i = if hi : i = 0 then 0 else i.pred hi := by split_ifs with hi · rw [hi, predAbove_right_zero] · rw [predAbove_zero_of_ne_zero hi] @[simp] lemma predAbove_right_last {i : Fin (n + 1)} : predAbove i (last (n + 1)) = last n := by rw [predAbove_of_castSucc_lt _ _ (castSucc_lt_last _), pred_last] @[simp] lemma predAbove_last_castSucc {i : Fin (n + 1)} : predAbove (last n) (i.castSucc) = i := by rw [predAbove_of_le_castSucc _ _ (castSucc_le_castSucc_iff.mpr (le_last _)), castPred_castSucc] @[simp] lemma predAbove_last_of_ne_last {i : Fin (n + 2)} (hi : i ≠ last (n + 1)) : predAbove (last n) i = castPred i hi := by rw [← exists_castSucc_eq] at hi rcases hi with ⟨y, rfl⟩ exact predAbove_last_castSucc lemma predAbove_last_apply {i : Fin (n + 2)} : predAbove (last n) i = if hi : i = last _ then last _ else i.castPred hi := by split_ifs with hi · rw [hi, predAbove_right_last] · rw [predAbove_last_of_ne_last hi] /-- Sending `Fin (n+1)` to `Fin n` by subtracting one from anything above `p` then back to `Fin (n+1)` with a gap around `p` is the identity away from `p`. -/ @[simp] lemma succAbove_predAbove {p : Fin n} {i : Fin (n + 1)} (h : i ≠ castSucc p) : p.castSucc.succAbove (p.predAbove i) = i := by obtain h | h := Fin.lt_or_lt_of_ne h · rw [predAbove_of_le_castSucc _ _ (Fin.le_of_lt h), succAbove_castPred_of_lt _ _ h] · rw [predAbove_of_castSucc_lt _ _ h, succAbove_pred_of_lt _ _ h] /-- Sending `Fin n` into `Fin (n + 1)` with a gap at `p` then back to `Fin n` by subtracting one from anything above `p` is the identity. -/ @[simp] lemma predAbove_succAbove (p : Fin n) (i : Fin n) : p.predAbove ((castSucc p).succAbove i) = i := by obtain h | h := p.le_or_lt i · rw [succAbove_castSucc_of_le _ _ h, predAbove_succ_of_le _ _ h] · rw [succAbove_castSucc_of_lt _ _ h, predAbove_castSucc_of_le _ _ $ Fin.le_of_lt h] /-- `succ` commutes with `predAbove`. -/ @[simp] lemma succ_predAbove_succ (a : Fin n) (b : Fin (n + 1)) : a.succ.predAbove b.succ = (a.predAbove b).succ := by obtain h | h := Fin.le_or_lt (succ a) b · rw [predAbove_of_castSucc_lt _ _ h, predAbove_succ_of_le _ _ h, succ_pred] · rw [predAbove_of_lt_succ _ _ h, predAbove_succ_of_lt _ _ h, succ_castPred_eq_castPred_succ] /-- `castSucc` commutes with `predAbove`. -/ @[simp] lemma castSucc_predAbove_castSucc {n : ℕ} (a : Fin n) (b : Fin (n + 1)) : a.castSucc.predAbove b.castSucc = (a.predAbove b).castSucc := by obtain h | h := a.castSucc.lt_or_le b · rw [predAbove_of_castSucc_lt _ _ h, predAbove_castSucc_of_lt _ _ h, castSucc_pred_eq_pred_castSucc] · rw [predAbove_of_le_castSucc _ _ h, predAbove_castSucc_of_le _ _ h, castSucc_castPred] /-- `rev` commutes with `predAbove`. -/ lemma rev_predAbove {n : ℕ} (p : Fin n) (i : Fin (n + 1)) : (predAbove p i).rev = predAbove p.rev i.rev := by rw [predAbove_rev_left, rev_rev] end PredAbove section DivMod /-- Compute `i / n`, where `n` is a `Nat` and inferred the type of `i`. -/ def divNat (i : Fin (m * n)) : Fin m := ⟨i / n, Nat.div_lt_of_lt_mul <| Nat.mul_comm m n ▸ i.prop⟩ @[simp] theorem coe_divNat (i : Fin (m * n)) : (i.divNat : ℕ) = i / n := rfl /-- Compute `i % n`, where `n` is a `Nat` and inferred the type of `i`. -/ def modNat (i : Fin (m * n)) : Fin n := ⟨i % n, Nat.mod_lt _ <| Nat.pos_of_mul_pos_left i.pos⟩ @[simp] theorem coe_modNat (i : Fin (m * n)) : (i.modNat : ℕ) = i % n := rfl theorem modNat_rev (i : Fin (m * n)) : i.rev.modNat = i.modNat.rev := by ext have H₁ : i % n + 1 ≤ n := i.modNat.is_lt have H₂ : i / n < m := i.divNat.is_lt simp only [coe_modNat, val_rev] calc (m * n - (i + 1)) % n = (m * n - ((i / n) * n + i % n + 1)) % n := by rw [Nat.div_add_mod'] _ = ((m - i / n - 1) * n + (n - (i % n + 1))) % n := by rw [Nat.mul_sub_right_distrib, Nat.one_mul, Nat.sub_add_sub_cancel _ H₁, Nat.mul_sub_right_distrib, Nat.sub_sub, Nat.add_assoc] exact Nat.le_mul_of_pos_left _ <| Nat.le_sub_of_add_le' H₂ _ = n - (i % n + 1) := by rw [Nat.mul_comm, Nat.mul_add_mod, Nat.mod_eq_of_lt]; exact i.modNat.rev.is_lt end DivMod section Rec /-! ### recursion and induction principles -/ end Rec theorem liftFun_iff_succ {α : Type*} (r : α → α → Prop) [IsTrans α r] {f : Fin (n + 1) → α} : ((· < ·) ⇒ r) f f ↔ ∀ i : Fin n, r (f (castSucc i)) (f i.succ) := by constructor · intro H i exact H i.castSucc_lt_succ · refine fun H i => Fin.induction (fun h ↦ ?_) ?_ · simp [le_def] at h · intro j ihj hij rw [← le_castSucc_iff] at hij obtain hij | hij := (le_def.1 hij).eq_or_lt · obtain rfl := Fin.ext hij exact H _ · exact _root_.trans (ihj hij) (H j) section AddGroup open Nat Int /-- Negation on `Fin n` -/ instance neg (n : ℕ) : Neg (Fin n) := ⟨fun a => ⟨(n - a) % n, Nat.mod_lt _ a.pos⟩⟩ theorem neg_def (a : Fin n) : -a = ⟨(n - a) % n, Nat.mod_lt _ a.pos⟩ := rfl protected theorem coe_neg (a : Fin n) : ((-a : Fin n) : ℕ) = (n - a) % n := rfl theorem eq_zero (n : Fin 1) : n = 0 := Subsingleton.elim _ _ instance uniqueFinOne : Unique (Fin 1) where uniq _ := Subsingleton.elim _ _ @[simp] theorem coe_fin_one (a : Fin 1) : (a : ℕ) = 0 := by simp [Subsingleton.elim a 0] lemma eq_one_of_neq_zero (i : Fin 2) (hi : i ≠ 0) : i = 1 := fin_two_eq_of_eq_zero_iff (by simpa only [one_eq_zero_iff, succ.injEq, iff_false] using hi) @[simp] theorem coe_neg_one : ↑(-1 : Fin (n + 1)) = n := by cases n · simp rw [Fin.coe_neg, Fin.val_one, Nat.add_one_sub_one, Nat.mod_eq_of_lt] constructor theorem last_sub (i : Fin (n + 1)) : last n - i = Fin.rev i := Fin.ext <| by rw [coe_sub_iff_le.2 i.le_last, val_last, val_rev, Nat.succ_sub_succ_eq_sub] theorem add_one_le_of_lt {n : ℕ} {a b : Fin (n + 1)} (h : a < b) : a + 1 ≤ b := by cases' a with a ha cases' b with b hb cases n · simp only [Nat.zero_eq, Nat.zero_add, Nat.lt_one_iff] at ha hb simp [ha, hb] simp only [le_iff_val_le_val, val_add, lt_iff_val_lt_val, val_mk, val_one] at h ⊢ rwa [Nat.mod_eq_of_lt, Nat.succ_le_iff] rw [Nat.succ_lt_succ_iff] exact h.trans_le (Nat.le_of_lt_succ hb) theorem exists_eq_add_of_le {n : ℕ} {a b : Fin n} (h : a ≤ b) : ∃ k ≤ b, b = a + k := by obtain ⟨k, hk⟩ : ∃ k : ℕ, (b : ℕ) = a + k := Nat.exists_eq_add_of_le h have hkb : k ≤ b := by omega refine ⟨⟨k, hkb.trans_lt b.is_lt⟩, hkb, ?_⟩ simp [Fin.ext_iff, Fin.val_add, ← hk, Nat.mod_eq_of_lt b.is_lt] theorem exists_eq_add_of_lt {n : ℕ} {a b : Fin (n + 1)} (h : a < b) : ∃ k < b, k + 1 ≤ b ∧ b = a + k + 1 := by cases n · cases' a with a ha cases' b with b hb simp only [Nat.zero_eq, Nat.zero_add, Nat.lt_one_iff] at ha hb simp [ha, hb] at h obtain ⟨k, hk⟩ : ∃ k : ℕ, (b : ℕ) = a + k + 1 := Nat.exists_eq_add_of_lt h have hkb : k < b := by omega refine ⟨⟨k, hkb.trans b.is_lt⟩, hkb, ?_, ?_⟩ · rw [Fin.le_iff_val_le_val, Fin.val_add_one] split_ifs <;> simp [Nat.succ_le_iff, hkb] simp [Fin.ext_iff, Fin.val_add, ← hk, Nat.mod_eq_of_lt b.is_lt] lemma pos_of_ne_zero {n : ℕ} {a : Fin (n + 1)} (h : a ≠ 0) : 0 < a := Nat.pos_of_ne_zero (val_ne_of_ne h) end AddGroup @[simp] theorem coe_ofNat_eq_mod (m n : ℕ) [NeZero m] : ((n : Fin m) : ℕ) = n % m := rfl section Mul /-! ### mul -/ protected theorem mul_one' [NeZero n] (k : Fin n) : k * 1 = k := by cases' n with n · simp [eq_iff_true_of_subsingleton] cases n · simp [fin_one_eq_zero] simp [Fin.ext_iff, mul_def, mod_eq_of_lt (is_lt k)] protected theorem one_mul' [NeZero n] (k : Fin n) : (1 : Fin n) * k = k := by rw [Fin.mul_comm, Fin.mul_one'] protected theorem mul_zero' [NeZero n] (k : Fin n) : k * 0 = 0 := by simp [Fin.ext_iff, mul_def] protected theorem zero_mul' [NeZero n] (k : Fin n) : (0 : Fin n) * k = 0 := by simp [Fin.ext_iff, mul_def] end Mul open Qq in instance toExpr (n : ℕ) : Lean.ToExpr (Fin n) where toTypeExpr := q(Fin $n) toExpr := match n with | 0 => finZeroElim | k + 1 => fun i => show Q(Fin $n) from have i : Q(Nat) := Lean.mkRawNatLit i -- raw literal to avoid ofNat-double-wrapping have : Q(NeZero $n) := haveI : $n =Q $k + 1 := ⟨⟩; by exact q(NeZero.succ) q(OfNat.ofNat $i) end Fin
Data\Fin\Fin2.lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Data.Nat.Notation import Mathlib.Data.Fintype.Basic import Mathlib.Logic.Function.Basic /-! # Inductive type variant of `Fin` `Fin` is defined as a subtype of `ℕ`. This file defines an equivalent type, `Fin2`, which is defined inductively. This is useful for its induction principle and different definitional equalities. ## Main declarations * `Fin2 n`: Inductive type variant of `Fin n`. `fz` corresponds to `0` and `fs n` corresponds to `n`. * `Fin2.toNat`, `Fin2.optOfNat`, `Fin2.ofNat'`: Conversions to and from `ℕ`. `ofNat' m` takes a proof that `m < n` through the class `Fin2.IsLT`. * `Fin2.add k`: Takes `i : Fin2 n` to `i + k : Fin2 (n + k)`. * `Fin2.left`: Embeds `Fin2 n` into `Fin2 (n + k)`. * `Fin2.insertPerm a`: Permutation of `Fin2 n` which cycles `0, ..., a - 1` and leaves `a, ..., n - 1` unchanged. * `Fin2.remapLeft f`: Function `Fin2 (m + k) → Fin2 (n + k)` by applying `f : Fin m → Fin n` to `0, ..., m - 1` and sending `m + i` to `n + i`. -/ open Nat universe u /-- An alternate definition of `Fin n` defined as an inductive type instead of a subtype of `ℕ`. -/ inductive Fin2 : ℕ → Type /-- `0` as a member of `Fin (n + 1)` (`Fin 0` is empty) -/ | fz {n} : Fin2 (n + 1) /-- `n` as a member of `Fin (n + 1)` -/ | fs {n} : Fin2 n → Fin2 (n + 1) namespace Fin2 /-- Define a dependent function on `Fin2 (succ n)` by giving its value at zero (`H1`) and by giving a dependent function on the rest (`H2`). -/ @[elab_as_elim] protected def cases' {n} {C : Fin2 (succ n) → Sort u} (H1 : C fz) (H2 : ∀ n, C (fs n)) : ∀ i : Fin2 (succ n), C i | fz => H1 | fs n => H2 n /-- Ex falso. The dependent eliminator for the empty `Fin2 0` type. -/ def elim0 {C : Fin2 0 → Sort u} : ∀ i : Fin2 0, C i := nofun /-- Converts a `Fin2` into a natural. -/ def toNat : ∀ {n}, Fin2 n → ℕ | _, @fz _ => 0 | _, @fs _ i => succ (toNat i) /-- Converts a natural into a `Fin2` if it is in range -/ def optOfNat : ∀ {n}, ℕ → Option (Fin2 n) | 0, _ => none | succ _, 0 => some fz | succ m, succ k => fs <$> @optOfNat m k /-- `i + k : Fin2 (n + k)` when `i : Fin2 n` and `k : ℕ` -/ def add {n} (i : Fin2 n) : ∀ k, Fin2 (n + k) | 0 => i | succ k => fs (add i k) /-- `left k` is the embedding `Fin2 n → Fin2 (k + n)` -/ def left (k) : ∀ {n}, Fin2 n → Fin2 (k + n) | _, @fz _ => fz | _, @fs _ i => fs (left k i) /-- `insertPerm a` is a permutation of `Fin2 n` with the following properties: * `insertPerm a i = i+1` if `i < a` * `insertPerm a a = 0` * `insertPerm a i = i` if `i > a` -/ def insertPerm : ∀ {n}, Fin2 n → Fin2 n → Fin2 n | _, @fz _, @fz _ => fz | _, @fz _, @fs _ j => fs j | _, @fs (succ _) _, @fz _ => fs fz | _, @fs (succ _) i, @fs _ j => match insertPerm i j with | fz => fz | fs k => fs (fs k) /-- `remapLeft f k : Fin2 (m + k) → Fin2 (n + k)` applies the function `f : Fin2 m → Fin2 n` to inputs less than `m`, and leaves the right part on the right (that is, `remapLeft f k (m + i) = n + i`). -/ def remapLeft {m n} (f : Fin2 m → Fin2 n) : ∀ k, Fin2 (m + k) → Fin2 (n + k) | 0, i => f i | _k + 1, @fz _ => fz | _k + 1, @fs _ i => fs (remapLeft f _ i) /-- This is a simple type class inference prover for proof obligations of the form `m < n` where `m n : ℕ`. -/ class IsLT (m n : ℕ) : Prop where /-- The unique field of `Fin2.IsLT`, a proof that `m < n`. -/ h : m < n instance IsLT.zero (n) : IsLT 0 (succ n) := ⟨succ_pos _⟩ instance IsLT.succ (m n) [l : IsLT m n] : IsLT (succ m) (succ n) := ⟨succ_lt_succ l.h⟩ /-- Use type class inference to infer the boundedness proof, so that we can directly convert a `Nat` into a `Fin2 n`. This supports notation like `&1 : Fin 3`. -/ def ofNat' : ∀ {n} (m) [IsLT m n], Fin2 n | 0, _, h => absurd h.h (Nat.not_lt_zero _) | succ _, 0, _ => fz | succ n, succ m, h => fs (@ofNat' n m ⟨lt_of_succ_lt_succ h.h⟩) /-- `castSucc i` embeds `i : Fin2 n` in `Fin2 (n+1)`. -/ def castSucc {n} : Fin2 n → Fin2 (n + 1) | fz => fz | fs k => fs <| castSucc k /-- The greatest value of `Fin2 (n+1)`. -/ def last : {n : Nat} → Fin2 (n+1) | 0 => fz | n+1 => fs (@last n) /-- Maps `0` to `n-1`, `1` to `n-2`, ..., `n-1` to `0`. -/ def rev {n : Nat} : Fin2 n → Fin2 n | .fz => last | .fs i => i.rev.castSucc @[simp] lemma rev_last {n} : rev (@last n) = fz := by induction n <;> simp_all [rev, castSucc, last] @[simp] lemma rev_castSucc {n} (i : Fin2 n) : rev (castSucc i) = fs (rev i) := by induction i <;> simp_all [rev, castSucc, last] @[simp] lemma rev_rev {n} (i : Fin2 n) : i.rev.rev = i := by induction i <;> simp_all [rev] theorem rev_involutive {n} : Function.Involutive (@rev n) := rev_rev @[inherit_doc] local prefix:arg "&" => ofNat' instance : Inhabited (Fin2 1) := ⟨fz⟩ instance instFintype : ∀ n, Fintype (Fin2 n) | 0 => ⟨∅, Fin2.elim0⟩ | n+1 => let ⟨elems, compl⟩ := instFintype n { elems := elems.map ⟨Fin2.fs, @fs.inj _⟩ |>.cons .fz (by simp) complete := by rintro (_|i) <;> simp [compl] } end Fin2
Data\Fin\FlagRange.lean
/- Copyright (c) 2023 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import Mathlib.Data.Fin.Basic import Mathlib.Order.Chain import Mathlib.Order.Cover import Mathlib.Order.Fin.Basic /-! # Range of `f : Fin (n + 1) → α` as a `Flag` Let `f : Fin (n + 1) → α` be an `(n + 1)`-tuple `(f₀, …, fₙ)` such that - `f₀ = ⊥` and `fₙ = ⊤`; - `fₖ₊₁` weakly covers `fₖ` for all `0 ≤ k < n`; this means that `fₖ ≤ fₖ₊₁` and there is no `c` such that `fₖ<c<fₖ₊₁`. Then the range of `f` is a maximal chain. We formulate this result in terms of `IsMaxChain` and `Flag`. -/ open Set variable {α : Type*} [PartialOrder α] [BoundedOrder α] {n : ℕ} {f : Fin (n + 1) → α} /-- Let `f : Fin (n + 1) → α` be an `(n + 1)`-tuple `(f₀, …, fₙ)` such that - `f₀ = ⊥` and `fₙ = ⊤`; - `fₖ₊₁` weakly covers `fₖ` for all `0 ≤ k < n`; this means that `fₖ ≤ fₖ₊₁` and there is no `c` such that `fₖ<c<fₖ₊₁`. Then the range of `f` is a maximal chain. -/ theorem IsMaxChain.range_fin_of_covBy (h0 : f 0 = ⊥) (hlast : f (.last n) = ⊤) (hcovBy : ∀ k : Fin n, f k.castSucc ⩿ f k.succ) : IsMaxChain (· ≤ ·) (range f) := by have hmono : Monotone f := Fin.monotone_iff_le_succ.2 fun k ↦ (hcovBy k).1 refine ⟨hmono.isChain_range, fun t htc hbt ↦ hbt.antisymm fun x hx ↦ ?_⟩ rw [mem_range]; by_contra! h suffices ∀ k, f k < x by simpa [hlast] using this (.last _) intro k induction k using Fin.induction with | zero => simpa [h0, bot_lt_iff_ne_bot] using (h 0).symm | succ k ihk => rw [range_subset_iff] at hbt exact (htc.lt_of_le (hbt k.succ) hx (h _)).resolve_right ((hcovBy k).2 ihk) /-- Let `f : Fin (n + 1) → α` be an `(n + 1)`-tuple `(f₀, …, fₙ)` such that - `f₀ = ⊥` and `fₙ = ⊤`; - `fₖ₊₁` weakly covers `fₖ` for all `0 ≤ k < n`; this means that `fₖ ≤ fₖ₊₁` and there is no `c` such that `fₖ<c<fₖ₊₁`. Then the range of `f` is a `Flag α`. -/ @[simps] def Flag.rangeFin (f : Fin (n + 1) → α) (h0 : f 0 = ⊥) (hlast : f (.last n) = ⊤) (hcovBy : ∀ k : Fin n, f k.castSucc ⩿ f k.succ) : Flag α where carrier := range f Chain' := (IsMaxChain.range_fin_of_covBy h0 hlast hcovBy).1 max_chain' := (IsMaxChain.range_fin_of_covBy h0 hlast hcovBy).2 @[simp] theorem Flag.mem_rangeFin {x h0 hlast hcovBy} : x ∈ rangeFin f h0 hlast hcovBy ↔ ∃ k, f k = x := Iff.rfl
Data\Fin\SuccPred.lean
/- Copyright (c) 2022 Eric Rodriguez. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Rodriguez -/ import Mathlib.Algebra.Group.Fin.Basic import Mathlib.Order.Fin.Basic import Mathlib.Order.SuccPred.Basic /-! # Successors and predecessors of `Fin n` In this file, we show that `Fin n` is both a `SuccOrder` and a `PredOrder`. Note that they are also archimedean, but this is derived from the general instance for well-orderings as opposed to a specific `Fin` instance. -/ namespace Fin instance : ∀ {n : ℕ}, SuccOrder (Fin n) | 0 => by constructor <;> intro a <;> exact elim0 a | n + 1 => SuccOrder.ofCore (fun i => if i < Fin.last n then i + 1 else i) (by intro a ha b rw [isMax_iff_eq_top, eq_top_iff, not_le, top_eq_last] at ha dsimp rw [if_pos ha, lt_iff_val_lt_val, le_iff_val_le_val, val_add_one_of_lt ha] exact Nat.lt_iff_add_one_le) (by intro a ha rw [isMax_iff_eq_top, top_eq_last] at ha dsimp rw [if_neg ha.not_lt]) @[simp] theorem succ_eq {n : ℕ} : SuccOrder.succ = fun a => if a < Fin.last n then a + 1 else a := rfl @[simp] theorem succ_apply {n : ℕ} (a) : SuccOrder.succ a = if a < Fin.last n then a + 1 else a := rfl instance : ∀ {n : ℕ}, PredOrder (Fin n) | 0 => by constructor <;> first | intro a; exact elim0 a | n + 1 => PredOrder.ofCore (fun x => if x = 0 then 0 else x - 1) (by intro a ha b rw [isMin_iff_eq_bot, eq_bot_iff, not_le, bot_eq_zero] at ha dsimp rw [if_neg ha.ne', lt_iff_val_lt_val, le_iff_val_le_val, coe_sub_one, if_neg ha.ne', Nat.lt_iff_add_one_le, Nat.le_sub_iff_add_le] exact ha) (by intro a ha rw [isMin_iff_eq_bot, bot_eq_zero] at ha dsimp rwa [if_pos ha, eq_comm]) @[simp] theorem pred_eq {n} : PredOrder.pred = fun a : Fin (n + 1) => if a = 0 then 0 else a - 1 := rfl @[simp] theorem pred_apply {n : ℕ} (a : Fin (n + 1)) : PredOrder.pred a = if a = 0 then 0 else a - 1 := rfl end Fin
Data\Fin\VecNotation.lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import Mathlib.Data.Fin.Tuple.Basic import Mathlib.Data.List.Range /-! # Matrix and vector notation This file defines notation for vectors and matrices. Given `a b c d : α`, the notation allows us to write `![a, b, c, d] : Fin 4 → α`. Nesting vectors gives coefficients of a matrix, so `![![a, b], ![c, d]] : Fin 2 → Fin 2 → α`. In later files we introduce `!![a, b; c, d]` as notation for `Matrix.of ![![a, b], ![c, d]]`. ## Main definitions * `vecEmpty` is the empty vector (or `0` by `n` matrix) `![]` * `vecCons` prepends an entry to a vector, so `![a, b]` is `vecCons a (vecCons b vecEmpty)` ## Implementation notes The `simp` lemmas require that one of the arguments is of the form `vecCons _ _`. This ensures `simp` works with entries only when (some) entries are already given. In other words, this notation will only appear in the output of `simp` if it already appears in the input. ## Notations The main new notation is `![a, b]`, which gets expanded to `vecCons a (vecCons b vecEmpty)`. ## Examples Examples of usage can be found in the `test/matrix.lean` file. -/ namespace Matrix universe u variable {α : Type u} section MatrixNotation /-- `![]` is the vector with no entries. -/ def vecEmpty : Fin 0 → α := Fin.elim0 /-- `vecCons h t` prepends an entry `h` to a vector `t`. The inverse functions are `vecHead` and `vecTail`. The notation `![a, b, ...]` expands to `vecCons a (vecCons b ...)`. -/ def vecCons {n : ℕ} (h : α) (t : Fin n → α) : Fin n.succ → α := Fin.cons h t /-- `![...]` notation is used to construct a vector `Fin n → α` using `Matrix.vecEmpty` and `Matrix.vecCons`. For instance, `![a, b, c] : Fin 3` is syntax for `vecCons a (vecCons b (vecCons c vecEmpty))`. Note that this should not be used as syntax for `Matrix` as it generates a term with the wrong type. The `!![a, b; c, d]` syntax (provided by `Matrix.matrixNotation`) should be used instead. -/ syntax (name := vecNotation) "![" term,* "]" : term macro_rules | `(![$term:term, $terms:term,*]) => `(vecCons $term ![$terms,*]) | `(![$term:term]) => `(vecCons $term ![]) | `(![]) => `(vecEmpty) /-- Unexpander for the `![x, y, ...]` notation. -/ @[app_unexpander vecCons] def vecConsUnexpander : Lean.PrettyPrinter.Unexpander | `($_ $term ![$term2, $terms,*]) => `(![$term, $term2, $terms,*]) | `($_ $term ![$term2]) => `(![$term, $term2]) | `($_ $term ![]) => `(![$term]) | _ => throw () /-- Unexpander for the `![]` notation. -/ @[app_unexpander vecEmpty] def vecEmptyUnexpander : Lean.PrettyPrinter.Unexpander | `($_:ident) => `(![]) | _ => throw () /-- `vecHead v` gives the first entry of the vector `v` -/ def vecHead {n : ℕ} (v : Fin n.succ → α) : α := v 0 /-- `vecTail v` gives a vector consisting of all entries of `v` except the first -/ def vecTail {n : ℕ} (v : Fin n.succ → α) : Fin n → α := v ∘ Fin.succ variable {m n : ℕ} /-- Use `![...]` notation for displaying a vector `Fin n → α`, for example: ``` #eval ![1, 2] + ![3, 4] -- ![4, 6] ``` -/ instance _root_.PiFin.hasRepr [Repr α] : Repr (Fin n → α) where reprPrec f _ := Std.Format.bracket "![" (Std.Format.joinSep ((List.finRange n).map fun n => repr (f n)) ("," ++ Std.Format.line)) "]" end MatrixNotation variable {m n o : ℕ} {m' n' o' : Type*} theorem empty_eq (v : Fin 0 → α) : v = ![] := Subsingleton.elim _ _ section Val @[simp] theorem head_fin_const (a : α) : (vecHead fun _ : Fin (n + 1) => a) = a := rfl @[simp] theorem cons_val_zero (x : α) (u : Fin m → α) : vecCons x u 0 = x := rfl theorem cons_val_zero' (h : 0 < m.succ) (x : α) (u : Fin m → α) : vecCons x u ⟨0, h⟩ = x := rfl @[simp] theorem cons_val_succ (x : α) (u : Fin m → α) (i : Fin m) : vecCons x u i.succ = u i := by simp [vecCons] @[simp] theorem cons_val_succ' {i : ℕ} (h : i.succ < m.succ) (x : α) (u : Fin m → α) : vecCons x u ⟨i.succ, h⟩ = u ⟨i, Nat.lt_of_succ_lt_succ h⟩ := by simp only [vecCons, Fin.cons, Fin.cases_succ'] @[simp] theorem head_cons (x : α) (u : Fin m → α) : vecHead (vecCons x u) = x := rfl @[simp] theorem tail_cons (x : α) (u : Fin m → α) : vecTail (vecCons x u) = u := by ext simp [vecTail] @[simp] theorem empty_val' {n' : Type*} (j : n') : (fun i => (![] : Fin 0 → n' → α) i j) = ![] := empty_eq _ @[simp] theorem cons_head_tail (u : Fin m.succ → α) : vecCons (vecHead u) (vecTail u) = u := Fin.cons_self_tail _ @[simp] theorem range_cons (x : α) (u : Fin n → α) : Set.range (vecCons x u) = {x} ∪ Set.range u := Set.ext fun y => by simp [Fin.exists_fin_succ, eq_comm] @[simp] theorem range_empty (u : Fin 0 → α) : Set.range u = ∅ := Set.range_eq_empty _ -- @[simp] -- Porting note (#10618): simp can prove this theorem range_cons_empty (x : α) (u : Fin 0 → α) : Set.range (Matrix.vecCons x u) = {x} := by rw [range_cons, range_empty, Set.union_empty] -- @[simp] -- Porting note (#10618): simp can prove this (up to commutativity) theorem range_cons_cons_empty (x y : α) (u : Fin 0 → α) : Set.range (vecCons x <| vecCons y u) = {x, y} := by rw [range_cons, range_cons_empty, Set.singleton_union] @[simp] theorem vecCons_const (a : α) : (vecCons a fun _ : Fin n => a) = fun _ => a := funext <| Fin.forall_fin_succ.2 ⟨rfl, cons_val_succ _ _⟩ theorem vec_single_eq_const (a : α) : ![a] = fun _ => a := let _ : Unique (Fin 1) := inferInstance funext <| Unique.forall_iff.2 rfl /-- `![a, b, ...] 1` is equal to `b`. The simplifier needs a special lemma for length `≥ 2`, in addition to `cons_val_succ`, because `1 : Fin 1 = 0 : Fin 1`. -/ @[simp] theorem cons_val_one (x : α) (u : Fin m.succ → α) : vecCons x u 1 = vecHead u := rfl @[simp] theorem cons_val_two (x : α) (u : Fin m.succ.succ → α) : vecCons x u 2 = vecHead (vecTail u) := rfl @[simp] lemma cons_val_three (x : α) (u : Fin m.succ.succ.succ → α) : vecCons x u 3 = vecHead (vecTail (vecTail u)) := rfl @[simp] lemma cons_val_four (x : α) (u : Fin m.succ.succ.succ.succ → α) : vecCons x u 4 = vecHead (vecTail (vecTail (vecTail u))) := rfl @[simp] theorem cons_val_fin_one (x : α) (u : Fin 0 → α) : ∀ (i : Fin 1), vecCons x u i = x := by rw [Fin.forall_fin_one] rfl theorem cons_fin_one (x : α) (u : Fin 0 → α) : vecCons x u = fun _ => x := funext (cons_val_fin_one x u) open Lean in open Qq in protected instance _root_.PiFin.toExpr [ToLevel.{u}] [ToExpr α] (n : ℕ) : ToExpr (Fin n → α) := have lu := toLevel.{u} have eα : Q(Type $lu) := toTypeExpr α have toTypeExpr := q(Fin $n → $eα) match n with | 0 => { toTypeExpr, toExpr := fun _ => q(@vecEmpty $eα) } | n + 1 => { toTypeExpr, toExpr := fun v => have := PiFin.toExpr n have eh : Q($eα) := toExpr (vecHead v) have et : Q(Fin $n → $eα) := toExpr (vecTail v) q(vecCons $eh $et) } -- Porting note: the next decl is commented out. TODO(eric-wieser) -- /-- Convert a vector of pexprs to the pexpr constructing that vector. -/ -- unsafe def _root_.pi_fin.to_pexpr : ∀ {n}, (Fin n → pexpr) → pexpr -- | 0, v => ``(![]) -- | n + 1, v => ``(vecCons $(v 0) $(_root_.pi_fin.to_pexpr <| vecTail v)) /-! ### `bit0` and `bit1` indices The following definitions and `simp` lemmas are used to allow numeral-indexed element of a vector given with matrix notation to be extracted by `simp` in Lean 3 (even when the numeral is larger than the number of elements in the vector, which is taken modulo that number of elements by virtue of the semantics of `bit0` and `bit1` and of addition on `Fin n`). -/ /-- `vecAppend ho u v` appends two vectors of lengths `m` and `n` to produce one of length `o = m + n`. This is a variant of `Fin.append` with an additional `ho` argument, which provides control of definitional equality for the vector length. This turns out to be helpful when providing simp lemmas to reduce `![a, b, c] n`, and also means that `vecAppend ho u v 0` is valid. `Fin.append u v 0` is not valid in this case because there is no `Zero (Fin (m + n))` instance. -/ def vecAppend {α : Type*} {o : ℕ} (ho : o = m + n) (u : Fin m → α) (v : Fin n → α) : Fin o → α := Fin.append u v ∘ Fin.cast ho theorem vecAppend_eq_ite {α : Type*} {o : ℕ} (ho : o = m + n) (u : Fin m → α) (v : Fin n → α) : vecAppend ho u v = fun i : Fin o => if h : (i : ℕ) < m then u ⟨i, h⟩ else v ⟨(i : ℕ) - m, by omega⟩ := by ext i rw [vecAppend, Fin.append, Function.comp_apply, Fin.addCases] congr with hi simp only [eq_rec_constant] rfl -- Porting note: proof was `rfl`, so this is no longer a `dsimp`-lemma -- Could become one again with change to `Nat.ble`: -- https://github.com/leanprover-community/mathlib4/pull/1741/files/#r1083902351 @[simp] theorem vecAppend_apply_zero {α : Type*} {o : ℕ} (ho : o + 1 = m + 1 + n) (u : Fin (m + 1) → α) (v : Fin n → α) : vecAppend ho u v 0 = u 0 := dif_pos _ @[simp] theorem empty_vecAppend (v : Fin n → α) : vecAppend n.zero_add.symm ![] v = v := by ext simp [vecAppend_eq_ite] @[simp] theorem cons_vecAppend (ho : o + 1 = m + 1 + n) (x : α) (u : Fin m → α) (v : Fin n → α) : vecAppend ho (vecCons x u) v = vecCons x (vecAppend (by omega) u v) := by ext i simp_rw [vecAppend_eq_ite] split_ifs with h · rcases i with ⟨⟨⟩ | i, hi⟩ · simp · simp only [Nat.add_lt_add_iff_right, Fin.val_mk] at h simp [h] · rcases i with ⟨⟨⟩ | i, hi⟩ · simp at h · rw [not_lt, Fin.val_mk, Nat.add_le_add_iff_right] at h simp [h, not_lt.2 h] /-- `vecAlt0 v` gives a vector with half the length of `v`, with only alternate elements (even-numbered). -/ def vecAlt0 (hm : m = n + n) (v : Fin m → α) (k : Fin n) : α := v ⟨(k : ℕ) + k, by omega⟩ /-- `vecAlt1 v` gives a vector with half the length of `v`, with only alternate elements (odd-numbered). -/ def vecAlt1 (hm : m = n + n) (v : Fin m → α) (k : Fin n) : α := v ⟨(k : ℕ) + k + 1, hm.symm ▸ Nat.add_succ_lt_add k.2 k.2⟩ section bits theorem vecAlt0_vecAppend (v : Fin n → α) : vecAlt0 rfl (vecAppend rfl v v) = v ∘ (fun n ↦ n + n) := by ext i simp_rw [Function.comp, vecAlt0, vecAppend_eq_ite] split_ifs with h <;> congr · rw [Fin.val_mk] at h exact (Nat.mod_eq_of_lt h).symm · rw [Fin.val_mk, not_lt] at h simp only [Fin.ext_iff, Fin.val_add, Fin.val_mk, Nat.mod_eq_sub_mod h] refine (Nat.mod_eq_of_lt ?_).symm omega theorem vecAlt1_vecAppend (v : Fin (n + 1) → α) : vecAlt1 rfl (vecAppend rfl v v) = v ∘ (fun n ↦ (n + n) + 1) := by ext i simp_rw [Function.comp, vecAlt1, vecAppend_eq_ite] cases n with | zero => cases' i with i hi simp only [Nat.zero_eq, Nat.zero_add, Nat.lt_one_iff] at hi; subst i; rfl | succ n => split_ifs with h <;> congr · simp [Nat.mod_eq_of_lt, h] · rw [Fin.val_mk, not_lt] at h simp only [Fin.ext_iff, Fin.val_add, Fin.val_mk, Nat.mod_add_mod, Fin.val_one, Nat.mod_eq_sub_mod h, show 1 % (n + 2) = 1 from Nat.mod_eq_of_lt (by omega)] refine (Nat.mod_eq_of_lt ?_).symm omega @[simp] theorem vecHead_vecAlt0 (hm : m + 2 = n + 1 + (n + 1)) (v : Fin (m + 2) → α) : vecHead (vecAlt0 hm v) = v 0 := rfl @[simp] theorem vecHead_vecAlt1 (hm : m + 2 = n + 1 + (n + 1)) (v : Fin (m + 2) → α) : vecHead (vecAlt1 hm v) = v 1 := by simp [vecHead, vecAlt1] @[simp] theorem cons_vec_bit0_eq_alt0 (x : α) (u : Fin n → α) (i : Fin (n + 1)) : vecCons x u (i + i) = vecAlt0 rfl (vecAppend rfl (vecCons x u) (vecCons x u)) i := by rw [vecAlt0_vecAppend]; rfl @[simp] theorem cons_vec_bit1_eq_alt1 (x : α) (u : Fin n → α) (i : Fin (n + 1)) : vecCons x u ((i + i) + 1) = vecAlt1 rfl (vecAppend rfl (vecCons x u) (vecCons x u)) i := by rw [vecAlt1_vecAppend]; rfl end bits @[simp] theorem cons_vecAlt0 (h : m + 1 + 1 = n + 1 + (n + 1)) (x y : α) (u : Fin m → α) : vecAlt0 h (vecCons x (vecCons y u)) = vecCons x (vecAlt0 (by omega) u) := by ext i simp_rw [vecAlt0] rcases i with ⟨⟨⟩ | i, hi⟩ · rfl · simp only [← Nat.add_assoc, Nat.add_right_comm, cons_val_succ', cons_vecAppend, Nat.add_eq, vecAlt0] -- Although proved by simp, extracting element 8 of a five-element -- vector does not work by simp unless this lemma is present. @[simp] theorem empty_vecAlt0 (α) {h} : vecAlt0 h (![] : Fin 0 → α) = ![] := by simp [eq_iff_true_of_subsingleton] @[simp] theorem cons_vecAlt1 (h : m + 1 + 1 = n + 1 + (n + 1)) (x y : α) (u : Fin m → α) : vecAlt1 h (vecCons x (vecCons y u)) = vecCons y (vecAlt1 (by omega) u) := by ext i simp_rw [vecAlt1] rcases i with ⟨⟨⟩ | i, hi⟩ · rfl · simp [vecAlt1, Nat.add_right_comm, ← Nat.add_assoc] -- Although proved by simp, extracting element 9 of a five-element -- vector does not work by simp unless this lemma is present. @[simp] theorem empty_vecAlt1 (α) {h} : vecAlt1 h (![] : Fin 0 → α) = ![] := by simp [eq_iff_true_of_subsingleton] end Val lemma const_fin1_eq (x : α) : (fun _ : Fin 1 => x) = ![x] := (cons_fin_one x _).symm end Matrix
Data\Fin\Tuple\Basic.lean
/- Copyright (c) 2019 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Yury Kudryashov, Sébastien Gouëzel, Chris Hughes -/ import Mathlib.Data.Fin.Basic import Mathlib.Data.Nat.Find import Batteries.Data.Fin.Lemmas /-! # Operation on tuples We interpret maps `∀ i : Fin n, α i` as `n`-tuples of elements of possibly varying type `α i`, `(α 0, …, α (n-1))`. A particular case is `Fin n → α` of elements with all the same type. In this case when `α i` is a constant map, then tuples are isomorphic (but not definitionally equal) to `Vector`s. ## Main declarations There are three (main) ways to consider `Fin n` as a subtype of `Fin (n + 1)`, hence three (main) ways to move between tuples of length `n` and of length `n + 1` by adding/removing an entry. ### Adding at the start * `Fin.succ`: Send `i : Fin n` to `i + 1 : Fin (n + 1)`. This is defined in Core. * `Fin.cases`: Induction/recursion principle for `Fin`: To prove a property/define a function for all `Fin (n + 1)`, it is enough to prove/define it for `0` and for `i.succ` for all `i : Fin n`. This is defined in Core. * `Fin.cons`: Turn a tuple `f : Fin n → α` and an entry `a : α` into a tuple `Fin.cons a f : Fin (n + 1) → α` by adding `a` at the start. In general, tuples can be dependent functions, in which case `f : ∀ i : Fin n, α i.succ` and `a : α 0`. This is a special case of `Fin.cases`. * `Fin.tail`: Turn a tuple `f : Fin (n + 1) → α` into a tuple `Fin.tail f : Fin n → α` by forgetting the start. In general, tuples can be dependent functions, in which case `Fin.tail f : ∀ i : Fin n, α i.succ`. ### Adding at the end * `Fin.castSucc`: Send `i : Fin n` to `i : Fin (n + 1)`. This is defined in Core. * `Fin.lastCases`: Induction/recursion principle for `Fin`: To prove a property/define a function for all `Fin (n + 1)`, it is enough to prove/define it for `last n` and for `i.castSucc` for all `i : Fin n`. This is defined in Core. * `Fin.snoc`: Turn a tuple `f : Fin n → α` and an entry `a : α` into a tuple `Fin.snoc f a : Fin (n + 1) → α` by adding `a` at the end. In general, tuples can be dependent functions, in which case `f : ∀ i : Fin n, α i.castSucc` and `a : α (last n)`. This is a special case of `Fin.lastCases`. * `Fin.init`: Turn a tuple `f : Fin (n + 1) → α` into a tuple `Fin.init f : Fin n → α` by forgetting the start. In general, tuples can be dependent functions, in which case `Fin.init f : ∀ i : Fin n, α i.castSucc`. ### Adding in the middle For a **pivot** `p : Fin (n + 1)`, * `Fin.succAbove`: Send `i : Fin n` to * `i : Fin (n + 1)` if `i < p`, * `i + 1 : Fin (n + 1)` if `p ≤ i`. * `Fin.succAboveCases`: Induction/recursion principle for `Fin`: To prove a property/define a function for all `Fin (n + 1)`, it is enough to prove/define it for `p` and for `p.succAbove i` for all `i : Fin n`. * `Fin.insertNth`: Turn a tuple `f : Fin n → α` and an entry `a : α` into a tuple `Fin.insertNth f a : Fin (n + 1) → α` by adding `a` in position `p`. In general, tuples can be dependent functions, in which case `f : ∀ i : Fin n, α (p.succAbove i)` and `a : α p`. This is a special case of `Fin.succAboveCases`. * `Fin.removeNth`: Turn a tuple `f : Fin (n + 1) → α` into a tuple `Fin.removeNth p f : Fin n → α` by forgetting the `p`-th value. In general, tuples can be dependent functions, in which case `Fin.removeNth f : ∀ i : Fin n, α (succAbove p i)`. `p = 0` means we add at the start. `p = last n` means we add at the end. ### Miscellaneous * `Fin.find p` : returns the first index `n` where `p n` is satisfied, and `none` if it is never satisfied. * `Fin.append a b` : append two tuples. * `Fin.repeat n a` : repeat a tuple `n` times. -/ assert_not_exists Monoid universe u v namespace Fin variable {m n : ℕ} open Function section Tuple /-- There is exactly one tuple of size zero. -/ example (α : Fin 0 → Sort u) : Unique (∀ i : Fin 0, α i) := by infer_instance theorem tuple0_le {α : Fin 0 → Type*} [∀ i, Preorder (α i)] (f g : ∀ i, α i) : f ≤ g := finZeroElim variable {α : Fin (n + 1) → Type u} (x : α 0) (q : ∀ i, α i) (p : ∀ i : Fin n, α i.succ) (i : Fin n) (y : α i.succ) (z : α 0) /-- The tail of an `n+1` tuple, i.e., its last `n` entries. -/ def tail (q : ∀ i, α i) : ∀ i : Fin n, α i.succ := fun i ↦ q i.succ theorem tail_def {n : ℕ} {α : Fin (n + 1) → Type*} {q : ∀ i, α i} : (tail fun k : Fin (n + 1) ↦ q k) = fun k : Fin n ↦ q k.succ := rfl /-- Adding an element at the beginning of an `n`-tuple, to get an `n+1`-tuple. -/ def cons (x : α 0) (p : ∀ i : Fin n, α i.succ) : ∀ i, α i := fun j ↦ Fin.cases x p j @[simp] theorem tail_cons : tail (cons x p) = p := by simp (config := { unfoldPartialApp := true }) [tail, cons] @[simp] theorem cons_succ : cons x p i.succ = p i := by simp [cons] @[simp] theorem cons_zero : cons x p 0 = x := by simp [cons] @[simp] theorem cons_one {α : Fin (n + 2) → Type*} (x : α 0) (p : ∀ i : Fin n.succ, α i.succ) : cons x p 1 = p 0 := by rw [← cons_succ x p]; rfl /-- Updating a tuple and adding an element at the beginning commute. -/ @[simp] theorem cons_update : cons x (update p i y) = update (cons x p) i.succ y := by ext j by_cases h : j = 0 · rw [h] simp [Ne.symm (succ_ne_zero i)] · let j' := pred j h have : j'.succ = j := succ_pred j h rw [← this, cons_succ] by_cases h' : j' = i · rw [h'] simp · have : j'.succ ≠ i.succ := by rwa [Ne, succ_inj] rw [update_noteq h', update_noteq this, cons_succ] /-- As a binary function, `Fin.cons` is injective. -/ theorem cons_injective2 : Function.Injective2 (@cons n α) := fun x₀ y₀ x y h ↦ ⟨congr_fun h 0, funext fun i ↦ by simpa using congr_fun h (Fin.succ i)⟩ @[simp] theorem cons_eq_cons {x₀ y₀ : α 0} {x y : ∀ i : Fin n, α i.succ} : cons x₀ x = cons y₀ y ↔ x₀ = y₀ ∧ x = y := cons_injective2.eq_iff theorem cons_left_injective (x : ∀ i : Fin n, α i.succ) : Function.Injective fun x₀ ↦ cons x₀ x := cons_injective2.left _ theorem cons_right_injective (x₀ : α 0) : Function.Injective (cons x₀) := cons_injective2.right _ /-- Adding an element at the beginning of a tuple and then updating it amounts to adding it directly. -/ theorem update_cons_zero : update (cons x p) 0 z = cons z p := by ext j by_cases h : j = 0 · rw [h] simp · simp only [h, update_noteq, Ne, not_false_iff] let j' := pred j h have : j'.succ = j := succ_pred j h rw [← this, cons_succ, cons_succ] /-- Concatenating the first element of a tuple with its tail gives back the original tuple -/ @[simp, nolint simpNF] -- Porting note: linter claims LHS doesn't simplify theorem cons_self_tail : cons (q 0) (tail q) = q := by ext j by_cases h : j = 0 · rw [h] simp · let j' := pred j h have : j'.succ = j := succ_pred j h rw [← this] unfold tail rw [cons_succ] -- Porting note: Mathport removes `_root_`? /-- Recurse on an `n+1`-tuple by splitting it into a single element and an `n`-tuple. -/ @[elab_as_elim] def consCases {P : (∀ i : Fin n.succ, α i) → Sort v} (h : ∀ x₀ x, P (Fin.cons x₀ x)) (x : ∀ i : Fin n.succ, α i) : P x := _root_.cast (by rw [cons_self_tail]) <| h (x 0) (tail x) @[simp] theorem consCases_cons {P : (∀ i : Fin n.succ, α i) → Sort v} (h : ∀ x₀ x, P (Fin.cons x₀ x)) (x₀ : α 0) (x : ∀ i : Fin n, α i.succ) : @consCases _ _ _ h (cons x₀ x) = h x₀ x := by rw [consCases, cast_eq] congr /-- Recurse on a tuple by splitting into `Fin.elim0` and `Fin.cons`. -/ @[elab_as_elim] def consInduction {α : Type*} {P : ∀ {n : ℕ}, (Fin n → α) → Sort v} (h0 : P Fin.elim0) (h : ∀ {n} (x₀) (x : Fin n → α), P x → P (Fin.cons x₀ x)) : ∀ {n : ℕ} (x : Fin n → α), P x | 0, x => by convert h0 | n + 1, x => consCases (fun x₀ x ↦ h _ _ <| consInduction h0 h _) x theorem cons_injective_of_injective {α} {x₀ : α} {x : Fin n → α} (hx₀ : x₀ ∉ Set.range x) (hx : Function.Injective x) : Function.Injective (cons x₀ x : Fin n.succ → α) := by refine Fin.cases ?_ ?_ · refine Fin.cases ?_ ?_ · intro rfl · intro j h rw [cons_zero, cons_succ] at h exact hx₀.elim ⟨_, h.symm⟩ · intro i refine Fin.cases ?_ ?_ · intro h rw [cons_zero, cons_succ] at h exact hx₀.elim ⟨_, h⟩ · intro j h rw [cons_succ, cons_succ] at h exact congr_arg _ (hx h) theorem cons_injective_iff {α} {x₀ : α} {x : Fin n → α} : Function.Injective (cons x₀ x : Fin n.succ → α) ↔ x₀ ∉ Set.range x ∧ Function.Injective x := by refine ⟨fun h ↦ ⟨?_, ?_⟩, fun h ↦ cons_injective_of_injective h.1 h.2⟩ · rintro ⟨i, hi⟩ replace h := @h i.succ 0 simp [hi, succ_ne_zero] at h · simpa [Function.comp] using h.comp (Fin.succ_injective _) @[simp] theorem forall_fin_zero_pi {α : Fin 0 → Sort*} {P : (∀ i, α i) → Prop} : (∀ x, P x) ↔ P finZeroElim := ⟨fun h ↦ h _, fun h x ↦ Subsingleton.elim finZeroElim x ▸ h⟩ @[simp] theorem exists_fin_zero_pi {α : Fin 0 → Sort*} {P : (∀ i, α i) → Prop} : (∃ x, P x) ↔ P finZeroElim := ⟨fun ⟨x, h⟩ ↦ Subsingleton.elim x finZeroElim ▸ h, fun h ↦ ⟨_, h⟩⟩ theorem forall_fin_succ_pi {P : (∀ i, α i) → Prop} : (∀ x, P x) ↔ ∀ a v, P (Fin.cons a v) := ⟨fun h a v ↦ h (Fin.cons a v), consCases⟩ theorem exists_fin_succ_pi {P : (∀ i, α i) → Prop} : (∃ x, P x) ↔ ∃ a v, P (Fin.cons a v) := ⟨fun ⟨x, h⟩ ↦ ⟨x 0, tail x, (cons_self_tail x).symm ▸ h⟩, fun ⟨_, _, h⟩ ↦ ⟨_, h⟩⟩ /-- Updating the first element of a tuple does not change the tail. -/ @[simp] theorem tail_update_zero : tail (update q 0 z) = tail q := by ext j simp [tail, Fin.succ_ne_zero] /-- Updating a nonzero element and taking the tail commute. -/ @[simp] theorem tail_update_succ : tail (update q i.succ y) = update (tail q) i y := by ext j by_cases h : j = i · rw [h] simp [tail] · simp [tail, (Fin.succ_injective n).ne h, h] theorem comp_cons {α : Type*} {β : Type*} (g : α → β) (y : α) (q : Fin n → α) : g ∘ cons y q = cons (g y) (g ∘ q) := by ext j by_cases h : j = 0 · rw [h] rfl · let j' := pred j h have : j'.succ = j := succ_pred j h rw [← this, cons_succ, comp_apply, comp_apply, cons_succ] theorem comp_tail {α : Type*} {β : Type*} (g : α → β) (q : Fin n.succ → α) : g ∘ tail q = tail (g ∘ q) := by ext j simp [tail] theorem le_cons [∀ i, Preorder (α i)] {x : α 0} {q : ∀ i, α i} {p : ∀ i : Fin n, α i.succ} : q ≤ cons x p ↔ q 0 ≤ x ∧ tail q ≤ p := forall_fin_succ.trans <| and_congr Iff.rfl <| forall_congr' fun j ↦ by simp [tail] theorem cons_le [∀ i, Preorder (α i)] {x : α 0} {q : ∀ i, α i} {p : ∀ i : Fin n, α i.succ} : cons x p ≤ q ↔ x ≤ q 0 ∧ p ≤ tail q := @le_cons _ (fun i ↦ (α i)ᵒᵈ) _ x q p theorem cons_le_cons [∀ i, Preorder (α i)] {x₀ y₀ : α 0} {x y : ∀ i : Fin n, α i.succ} : cons x₀ x ≤ cons y₀ y ↔ x₀ ≤ y₀ ∧ x ≤ y := forall_fin_succ.trans <| and_congr_right' <| by simp only [cons_succ, Pi.le_def] theorem range_fin_succ {α} (f : Fin (n + 1) → α) : Set.range f = insert (f 0) (Set.range (Fin.tail f)) := Set.ext fun _ ↦ exists_fin_succ.trans <| eq_comm.or Iff.rfl @[simp] theorem range_cons {α : Type*} {n : ℕ} (x : α) (b : Fin n → α) : Set.range (Fin.cons x b : Fin n.succ → α) = insert x (Set.range b) := by rw [range_fin_succ, cons_zero, tail_cons] section Append /-- Append a tuple of length `m` to a tuple of length `n` to get a tuple of length `m + n`. This is a non-dependent version of `Fin.add_cases`. -/ def append {α : Type*} (a : Fin m → α) (b : Fin n → α) : Fin (m + n) → α := @Fin.addCases _ _ (fun _ => α) a b @[simp] theorem append_left {α : Type*} (u : Fin m → α) (v : Fin n → α) (i : Fin m) : append u v (Fin.castAdd n i) = u i := addCases_left _ @[simp] theorem append_right {α : Type*} (u : Fin m → α) (v : Fin n → α) (i : Fin n) : append u v (natAdd m i) = v i := addCases_right _ theorem append_right_nil {α : Type*} (u : Fin m → α) (v : Fin n → α) (hv : n = 0) : append u v = u ∘ Fin.cast (by rw [hv, Nat.add_zero]) := by refine funext (Fin.addCases (fun l => ?_) fun r => ?_) · rw [append_left, Function.comp_apply] refine congr_arg u (Fin.ext ?_) simp · exact (Fin.cast hv r).elim0 @[simp] theorem append_elim0 {α : Type*} (u : Fin m → α) : append u Fin.elim0 = u ∘ Fin.cast (Nat.add_zero _) := append_right_nil _ _ rfl theorem append_left_nil {α : Type*} (u : Fin m → α) (v : Fin n → α) (hu : m = 0) : append u v = v ∘ Fin.cast (by rw [hu, Nat.zero_add]) := by refine funext (Fin.addCases (fun l => ?_) fun r => ?_) · exact (Fin.cast hu l).elim0 · rw [append_right, Function.comp_apply] refine congr_arg v (Fin.ext ?_) simp [hu] @[simp] theorem elim0_append {α : Type*} (v : Fin n → α) : append Fin.elim0 v = v ∘ Fin.cast (Nat.zero_add _) := append_left_nil _ _ rfl theorem append_assoc {p : ℕ} {α : Type*} (a : Fin m → α) (b : Fin n → α) (c : Fin p → α) : append (append a b) c = append a (append b c) ∘ Fin.cast (Nat.add_assoc ..) := by ext i rw [Function.comp_apply] refine Fin.addCases (fun l => ?_) (fun r => ?_) i · rw [append_left] refine Fin.addCases (fun ll => ?_) (fun lr => ?_) l · rw [append_left] simp [castAdd_castAdd] · rw [append_right] simp [castAdd_natAdd] · rw [append_right] simp [← natAdd_natAdd] /-- Appending a one-tuple to the left is the same as `Fin.cons`. -/ theorem append_left_eq_cons {α : Type*} {n : ℕ} (x₀ : Fin 1 → α) (x : Fin n → α) : Fin.append x₀ x = Fin.cons (x₀ 0) x ∘ Fin.cast (Nat.add_comm ..) := by ext i refine Fin.addCases ?_ ?_ i <;> clear i · intro i rw [Subsingleton.elim i 0, Fin.append_left, Function.comp_apply, eq_comm] exact Fin.cons_zero _ _ · intro i rw [Fin.append_right, Function.comp_apply, Fin.cast_natAdd, eq_comm, Fin.addNat_one] exact Fin.cons_succ _ _ _ /-- `Fin.cons` is the same as appending a one-tuple to the left. -/ theorem cons_eq_append {α : Type*} (x : α) (xs : Fin n → α) : cons x xs = append (cons x Fin.elim0) xs ∘ Fin.cast (Nat.add_comm ..) := by funext i; simp [append_left_eq_cons] @[simp] lemma append_cast_left {n m} {α : Type*} (xs : Fin n → α) (ys : Fin m → α) (n' : ℕ) (h : n' = n) : Fin.append (xs ∘ Fin.cast h) ys = Fin.append xs ys ∘ (Fin.cast <| by rw [h]) := by subst h; simp @[simp] lemma append_cast_right {n m} {α : Type*} (xs : Fin n → α) (ys : Fin m → α) (m' : ℕ) (h : m' = m) : Fin.append xs (ys ∘ Fin.cast h) = Fin.append xs ys ∘ (Fin.cast <| by rw [h]) := by subst h; simp lemma append_rev {m n} {α : Type*} (xs : Fin m → α) (ys : Fin n → α) (i : Fin (m + n)) : append xs ys (rev i) = append (ys ∘ rev) (xs ∘ rev) (cast (Nat.add_comm ..) i) := by rcases rev_surjective i with ⟨i, rfl⟩ rw [rev_rev] induction i using Fin.addCases · simp [rev_castAdd] · simp [cast_rev, rev_addNat] lemma append_comp_rev {m n} {α : Type*} (xs : Fin m → α) (ys : Fin n → α) : append xs ys ∘ rev = append (ys ∘ rev) (xs ∘ rev) ∘ cast (Nat.add_comm ..) := funext <| append_rev xs ys end Append section Repeat /-- Repeat `a` `m` times. For example `Fin.repeat 2 ![0, 3, 7] = ![0, 3, 7, 0, 3, 7]`. -/ -- Porting note: removed @[simp] def «repeat» {α : Type*} (m : ℕ) (a : Fin n → α) : Fin (m * n) → α | i => a i.modNat -- Porting note: added (leanprover/lean4#2042) @[simp] theorem repeat_apply {α : Type*} (a : Fin n → α) (i : Fin (m * n)) : Fin.repeat m a i = a i.modNat := rfl @[simp] theorem repeat_zero {α : Type*} (a : Fin n → α) : Fin.repeat 0 a = Fin.elim0 ∘ cast (Nat.zero_mul _) := funext fun x => (cast (Nat.zero_mul _) x).elim0 @[simp] theorem repeat_one {α : Type*} (a : Fin n → α) : Fin.repeat 1 a = a ∘ cast (Nat.one_mul _) := by generalize_proofs h apply funext rw [(Fin.rightInverse_cast h.symm).surjective.forall] intro i simp [modNat, Nat.mod_eq_of_lt i.is_lt] theorem repeat_succ {α : Type*} (a : Fin n → α) (m : ℕ) : Fin.repeat m.succ a = append a (Fin.repeat m a) ∘ cast ((Nat.succ_mul _ _).trans (Nat.add_comm ..)) := by generalize_proofs h apply funext rw [(Fin.rightInverse_cast h.symm).surjective.forall] refine Fin.addCases (fun l => ?_) fun r => ?_ · simp [modNat, Nat.mod_eq_of_lt l.is_lt] · simp [modNat] @[simp] theorem repeat_add {α : Type*} (a : Fin n → α) (m₁ m₂ : ℕ) : Fin.repeat (m₁ + m₂) a = append (Fin.repeat m₁ a) (Fin.repeat m₂ a) ∘ cast (Nat.add_mul ..) := by generalize_proofs h apply funext rw [(Fin.rightInverse_cast h.symm).surjective.forall] refine Fin.addCases (fun l => ?_) fun r => ?_ · simp [modNat, Nat.mod_eq_of_lt l.is_lt] · simp [modNat, Nat.add_mod] theorem repeat_rev {α : Type*} (a : Fin n → α) (k : Fin (m * n)) : Fin.repeat m a k.rev = Fin.repeat m (a ∘ Fin.rev) k := congr_arg a k.modNat_rev theorem repeat_comp_rev {α} (a : Fin n → α) : Fin.repeat m a ∘ Fin.rev = Fin.repeat m (a ∘ Fin.rev) := funext <| repeat_rev a end Repeat end Tuple section TupleRight /-! In the previous section, we have discussed inserting or removing elements on the left of a tuple. In this section, we do the same on the right. A difference is that `Fin (n+1)` is constructed inductively from `Fin n` starting from the left, not from the right. This implies that Lean needs more help to realize that elements belong to the right types, i.e., we need to insert casts at several places. -/ -- Porting note: `i.castSucc` does not work like it did in Lean 3; -- `(castSucc i)` must be used. variable {α : Fin (n + 1) → Type u} (x : α (last n)) (q : ∀ i, α i) (p : ∀ i : Fin n, α (castSucc i)) (i : Fin n) (y : α (castSucc i)) (z : α (last n)) /-- The beginning of an `n+1` tuple, i.e., its first `n` entries -/ def init (q : ∀ i, α i) (i : Fin n) : α (castSucc i) := q (castSucc i) theorem init_def {n : ℕ} {α : Fin (n + 1) → Type*} {q : ∀ i, α i} : (init fun k : Fin (n + 1) ↦ q k) = fun k : Fin n ↦ q (castSucc k) := rfl /-- Adding an element at the end of an `n`-tuple, to get an `n+1`-tuple. The name `snoc` comes from `cons` (i.e., adding an element to the left of a tuple) read in reverse order. -/ def snoc (p : ∀ i : Fin n, α (castSucc i)) (x : α (last n)) (i : Fin (n + 1)) : α i := if h : i.val < n then _root_.cast (by rw [Fin.castSucc_castLT i h]) (p (castLT i h)) else _root_.cast (by rw [eq_last_of_not_lt h]) x @[simp] theorem init_snoc : init (snoc p x) = p := by ext i simp only [init, snoc, coe_castSucc, is_lt, cast_eq, dite_true] convert cast_eq rfl (p i) @[simp] theorem snoc_castSucc : snoc p x (castSucc i) = p i := by simp only [snoc, coe_castSucc, is_lt, cast_eq, dite_true] convert cast_eq rfl (p i) @[simp] theorem snoc_comp_castSucc {n : ℕ} {α : Sort _} {a : α} {f : Fin n → α} : (snoc f a : Fin (n + 1) → α) ∘ castSucc = f := funext fun i ↦ by rw [Function.comp_apply, snoc_castSucc] @[simp] theorem snoc_last : snoc p x (last n) = x := by simp [snoc] lemma snoc_zero {α : Type*} (p : Fin 0 → α) (x : α) : Fin.snoc p x = fun _ ↦ x := by ext y have : Subsingleton (Fin (0 + 1)) := Fin.subsingleton_one simp only [Subsingleton.elim y (Fin.last 0), snoc_last] @[simp] theorem snoc_comp_nat_add {n m : ℕ} {α : Sort _} (f : Fin (m + n) → α) (a : α) : (snoc f a : Fin _ → α) ∘ (natAdd m : Fin (n + 1) → Fin (m + n + 1)) = snoc (f ∘ natAdd m) a := by ext i refine Fin.lastCases ?_ (fun i ↦ ?_) i · simp only [Function.comp_apply] rw [snoc_last, natAdd_last, snoc_last] · simp only [comp_apply, snoc_castSucc] rw [natAdd_castSucc, snoc_castSucc] @[simp] theorem snoc_cast_add {α : Fin (n + m + 1) → Type*} (f : ∀ i : Fin (n + m), α (castSucc i)) (a : α (last (n + m))) (i : Fin n) : (snoc f a) (castAdd (m + 1) i) = f (castAdd m i) := dif_pos _ -- Porting note: Had to `unfold comp` @[simp] theorem snoc_comp_cast_add {n m : ℕ} {α : Sort _} (f : Fin (n + m) → α) (a : α) : (snoc f a : Fin _ → α) ∘ castAdd (m + 1) = f ∘ castAdd m := funext (by unfold comp; exact snoc_cast_add _ _) /-- Updating a tuple and adding an element at the end commute. -/ @[simp] theorem snoc_update : snoc (update p i y) x = update (snoc p x) (castSucc i) y := by ext j by_cases h : j.val < n · rw [snoc] simp only [h] simp only [dif_pos] by_cases h' : j = castSucc i · have C1 : α (castSucc i) = α j := by rw [h'] have E1 : update (snoc p x) (castSucc i) y j = _root_.cast C1 y := by have : update (snoc p x) j (_root_.cast C1 y) j = _root_.cast C1 y := by simp convert this · exact h'.symm · exact heq_of_cast_eq (congr_arg α (Eq.symm h')) rfl have C2 : α (castSucc i) = α (castSucc (castLT j h)) := by rw [castSucc_castLT, h'] have E2 : update p i y (castLT j h) = _root_.cast C2 y := by have : update p (castLT j h) (_root_.cast C2 y) (castLT j h) = _root_.cast C2 y := by simp convert this · simp [h, h'] · exact heq_of_cast_eq C2 rfl rw [E1, E2] exact eq_rec_compose (Eq.trans C2.symm C1) C2 y · have : ¬castLT j h = i := by intro E apply h' rw [← E, castSucc_castLT] simp [h', this, snoc, h] · rw [eq_last_of_not_lt h] simp [Fin.ne_of_gt i.castSucc_lt_last] /-- Adding an element at the beginning of a tuple and then updating it amounts to adding it directly. -/ theorem update_snoc_last : update (snoc p x) (last n) z = snoc p z := by ext j by_cases h : j.val < n · have : j ≠ last n := Fin.ne_of_lt h simp [h, update_noteq, this, snoc] · rw [eq_last_of_not_lt h] simp /-- Concatenating the first element of a tuple with its tail gives back the original tuple -/ @[simp] theorem snoc_init_self : snoc (init q) (q (last n)) = q := by ext j by_cases h : j.val < n · simp only [init, snoc, h, cast_eq, dite_true, castSucc_castLT] · rw [eq_last_of_not_lt h] simp /-- Updating the last element of a tuple does not change the beginning. -/ @[simp] theorem init_update_last : init (update q (last n) z) = init q := by ext j simp [init, Fin.ne_of_lt, castSucc_lt_last] /-- Updating an element and taking the beginning commute. -/ @[simp] theorem init_update_castSucc : init (update q (castSucc i) y) = update (init q) i y := by ext j by_cases h : j = i · rw [h] simp [init] · simp [init, h, castSucc_inj] /-- `tail` and `init` commute. We state this lemma in a non-dependent setting, as otherwise it would involve a cast to convince Lean that the two types are equal, making it harder to use. -/ theorem tail_init_eq_init_tail {β : Type*} (q : Fin (n + 2) → β) : tail (init q) = init (tail q) := by ext i simp [tail, init, castSucc_fin_succ] /-- `cons` and `snoc` commute. We state this lemma in a non-dependent setting, as otherwise it would involve a cast to convince Lean that the two types are equal, making it harder to use. -/ theorem cons_snoc_eq_snoc_cons {β : Type*} (a : β) (q : Fin n → β) (b : β) : @cons n.succ (fun _ ↦ β) a (snoc q b) = snoc (cons a q) b := by ext i by_cases h : i = 0 · rw [h] -- Porting note: `refl` finished it here in Lean 3, but I had to add more. simp [snoc, castLT] set j := pred i h with ji have : i = j.succ := by rw [ji, succ_pred] rw [this, cons_succ] by_cases h' : j.val < n · set k := castLT j h' with jk have : j = castSucc k := by rw [jk, castSucc_castLT] rw [this, ← castSucc_fin_succ, snoc] simp [pred, snoc, cons] rw [eq_last_of_not_lt h', succ_last] simp theorem comp_snoc {α : Type*} {β : Type*} (g : α → β) (q : Fin n → α) (y : α) : g ∘ snoc q y = snoc (g ∘ q) (g y) := by ext j by_cases h : j.val < n · simp [h, snoc, castSucc_castLT] · rw [eq_last_of_not_lt h] simp /-- Appending a one-tuple to the right is the same as `Fin.snoc`. -/ theorem append_right_eq_snoc {α : Type*} {n : ℕ} (x : Fin n → α) (x₀ : Fin 1 → α) : Fin.append x x₀ = Fin.snoc x (x₀ 0) := by ext i refine Fin.addCases ?_ ?_ i <;> clear i · intro i rw [Fin.append_left] exact (@snoc_castSucc _ (fun _ => α) _ _ i).symm · intro i rw [Subsingleton.elim i 0, Fin.append_right] exact (@snoc_last _ (fun _ => α) _ _).symm /-- `Fin.snoc` is the same as appending a one-tuple -/ theorem snoc_eq_append {α : Type*} (xs : Fin n → α) (x : α) : snoc xs x = append xs (cons x Fin.elim0) := (append_right_eq_snoc xs (cons x Fin.elim0)).symm theorem append_left_snoc {n m} {α : Type*} (xs : Fin n → α) (x : α) (ys : Fin m → α) : Fin.append (Fin.snoc xs x) ys = Fin.append xs (Fin.cons x ys) ∘ Fin.cast (Nat.succ_add_eq_add_succ ..) := by rw [snoc_eq_append, append_assoc, append_left_eq_cons, append_cast_right]; rfl theorem append_right_cons {n m} {α : Type*} (xs : Fin n → α) (y : α) (ys : Fin m → α) : Fin.append xs (Fin.cons y ys) = Fin.append (Fin.snoc xs y) ys ∘ Fin.cast (Nat.succ_add_eq_add_succ ..).symm := by rw [append_left_snoc]; rfl theorem append_cons {α} (a : α) (as : Fin n → α) (bs : Fin m → α) : Fin.append (cons a as) bs = cons a (Fin.append as bs) ∘ (Fin.cast <| Nat.add_right_comm n 1 m) := by funext i rcases i with ⟨i, -⟩ simp only [append, addCases, cons, castLT, cast, comp_apply] cases' i with i · simp · split_ifs with h · have : i < n := Nat.lt_of_succ_lt_succ h simp [addCases, this] · have : ¬i < n := Nat.not_le.mpr <| Nat.lt_succ.mp <| Nat.not_le.mp h simp [addCases, this] theorem append_snoc {α} (as : Fin n → α) (bs : Fin m → α) (b : α) : Fin.append as (snoc bs b) = snoc (Fin.append as bs) b := by funext i rcases i with ⟨i, isLt⟩ simp only [append, addCases, castLT, cast_mk, subNat_mk, natAdd_mk, cast, snoc.eq_1, cast_eq, eq_rec_constant, Nat.add_eq, Nat.add_zero, castLT_mk] split_ifs with lt_n lt_add sub_lt nlt_add lt_add <;> (try rfl) · have := Nat.lt_add_right m lt_n contradiction · obtain rfl := Nat.eq_of_le_of_lt_succ (Nat.not_lt.mp nlt_add) isLt simp [Nat.add_comm n m] at sub_lt · have := Nat.sub_lt_left_of_lt_add (Nat.not_lt.mp lt_n) lt_add contradiction theorem comp_init {α : Type*} {β : Type*} (g : α → β) (q : Fin n.succ → α) : g ∘ init q = init (g ∘ q) := by ext j simp [init] /-- Recurse on an `n+1`-tuple by splitting it its initial `n`-tuple and its last element. -/ @[elab_as_elim, inline] def snocCases {P : (∀ i : Fin n.succ, α i) → Sort*} (h : ∀ xs x, P (Fin.snoc xs x)) (x : ∀ i : Fin n.succ, α i) : P x := _root_.cast (by rw [Fin.snoc_init_self]) <| h (Fin.init x) (x <| Fin.last _) @[simp] lemma snocCases_snoc {P : (∀ i : Fin (n+1), α i) → Sort*} (h : ∀ x x₀, P (Fin.snoc x x₀)) (x : ∀ i : Fin n, (Fin.init α) i) (x₀ : α (Fin.last _)) : snocCases h (Fin.snoc x x₀) = h x x₀ := by rw [snocCases, cast_eq_iff_heq, Fin.init_snoc, Fin.snoc_last] /-- Recurse on a tuple by splitting into `Fin.elim0` and `Fin.snoc`. -/ @[elab_as_elim] def snocInduction {α : Type*} {P : ∀ {n : ℕ}, (Fin n → α) → Sort*} (h0 : P Fin.elim0) (h : ∀ {n} (x : Fin n → α) (x₀), P x → P (Fin.snoc x x₀)) : ∀ {n : ℕ} (x : Fin n → α), P x | 0, x => by convert h0 | n + 1, x => snocCases (fun x₀ x ↦ h _ _ <| snocInduction h0 h _) x end TupleRight section InsertNth variable {α : Fin (n + 1) → Type u} {β : Type v} /- Porting note: Lean told me `(fun x x_1 ↦ α x)` was an invalid motive, but disabling automatic insertion and specifying that motive seems to work. -/ /-- Define a function on `Fin (n + 1)` from a value on `i : Fin (n + 1)` and values on each `Fin.succAbove i j`, `j : Fin n`. This version is elaborated as eliminator and works for propositions, see also `Fin.insertNth` for a version without an `@[elab_as_elim]` attribute. -/ @[elab_as_elim] def succAboveCases {α : Fin (n + 1) → Sort u} (i : Fin (n + 1)) (x : α i) (p : ∀ j : Fin n, α (i.succAbove j)) (j : Fin (n + 1)) : α j := if hj : j = i then Eq.rec x hj.symm else if hlt : j < i then @Eq.recOn _ _ (fun x _ ↦ α x) _ (succAbove_castPred_of_lt _ _ hlt) (p _) else @Eq.recOn _ _ (fun x _ ↦ α x) _ (succAbove_pred_of_lt _ _ <| (Fin.lt_or_lt_of_ne hj).resolve_left hlt) (p _) theorem forall_iff_succAbove {p : Fin (n + 1) → Prop} (i : Fin (n + 1)) : (∀ j, p j) ↔ p i ∧ ∀ j, p (i.succAbove j) := ⟨fun h ↦ ⟨h _, fun _ ↦ h _⟩, fun h ↦ succAboveCases i h.1 h.2⟩ /-- Remove the `p`-th entry of a tuple. -/ def removeNth (p : Fin (n + 1)) (f : ∀ i, α i) : ∀ i, α (p.succAbove i) := fun i ↦ f (p.succAbove i) /-- Insert an element into a tuple at a given position. For `i = 0` see `Fin.cons`, for `i = Fin.last n` see `Fin.snoc`. See also `Fin.succAboveCases` for a version elaborated as an eliminator. -/ def insertNth (i : Fin (n + 1)) (x : α i) (p : ∀ j : Fin n, α (i.succAbove j)) (j : Fin (n + 1)) : α j := succAboveCases i x p j @[simp] theorem insertNth_apply_same (i : Fin (n + 1)) (x : α i) (p : ∀ j, α (i.succAbove j)) : insertNth i x p i = x := by simp [insertNth, succAboveCases] @[simp] theorem insertNth_apply_succAbove (i : Fin (n + 1)) (x : α i) (p : ∀ j, α (i.succAbove j)) (j : Fin n) : insertNth i x p (i.succAbove j) = p j := by simp only [insertNth, succAboveCases, dif_neg (succAbove_ne _ _), succAbove_lt_iff_castSucc_lt] split_ifs with hlt · generalize_proofs H₁ H₂; revert H₂ generalize hk : castPred ((succAbove i) j) H₁ = k rw [castPred_succAbove _ _ hlt] at hk; cases hk intro; rfl · generalize_proofs H₁ H₂; revert H₂ generalize hk : pred (succAbove i j) H₁ = k erw [pred_succAbove _ _ (Fin.not_lt.1 hlt)] at hk; cases hk intro; rfl @[simp] theorem succAbove_cases_eq_insertNth : @succAboveCases.{u + 1} = @insertNth.{u} := rfl @[simp] lemma removeNth_insertNth (p : Fin (n + 1)) (a : α p) (f : ∀ i, α (succAbove p i)) : removeNth p (insertNth p a f) = f := by ext; unfold removeNth; simp @[simp] lemma removeNth_zero (f : ∀ i, α i) : removeNth 0 f = tail f := by ext; simp [tail, removeNth] @[simp] lemma removeNth_last {α : Type*} (f : Fin (n + 1) → α) : removeNth (last n) f = init f := by ext; simp [init, removeNth] /- Porting note: Had to `unfold comp`. Sometimes, when I use a placeholder, if I try to insert what Lean says it synthesized, it gives me a type error anyway. In this case, it's `x` and `p`. -/ @[simp] theorem insertNth_comp_succAbove (i : Fin (n + 1)) (x : β) (p : Fin n → β) : insertNth i x p ∘ i.succAbove = p := funext (by unfold comp; exact insertNth_apply_succAbove i _ _) theorem insertNth_eq_iff {p : Fin (n + 1)} {a : α p} {f : ∀ i, α (p.succAbove i)} {g : ∀ j, α j} : insertNth p a f = g ↔ a = g p ∧ f = removeNth p g := by simp [funext_iff, forall_iff_succAbove p, removeNth] theorem eq_insertNth_iff {p : Fin (n + 1)} {a : α p} {f : ∀ i, α (p.succAbove i)} {g : ∀ j, α j} : g = insertNth p a f ↔ g p = a ∧ removeNth p g = f := by simpa [eq_comm] using insertNth_eq_iff /- Porting note: Once again, Lean told me `(fun x x_1 ↦ α x)` was an invalid motive, but disabling automatic insertion and specifying that motive seems to work. -/ theorem insertNth_apply_below {i j : Fin (n + 1)} (h : j < i) (x : α i) (p : ∀ k, α (i.succAbove k)) : i.insertNth x p j = @Eq.recOn _ _ (fun x _ ↦ α x) _ (succAbove_castPred_of_lt _ _ h) (p <| j.castPred _) := by rw [insertNth, succAboveCases, dif_neg (Fin.ne_of_lt h), dif_pos h] /- Porting note: Once again, Lean told me `(fun x x_1 ↦ α x)` was an invalid motive, but disabling automatic insertion and specifying that motive seems to work. -/ theorem insertNth_apply_above {i j : Fin (n + 1)} (h : i < j) (x : α i) (p : ∀ k, α (i.succAbove k)) : i.insertNth x p j = @Eq.recOn _ _ (fun x _ ↦ α x) _ (succAbove_pred_of_lt _ _ h) (p <| j.pred _) := by rw [insertNth, succAboveCases, dif_neg (Fin.ne_of_gt h), dif_neg (Fin.lt_asymm h)] theorem insertNth_zero (x : α 0) (p : ∀ j : Fin n, α (succAbove 0 j)) : insertNth 0 x p = cons x fun j ↦ _root_.cast (congr_arg α (congr_fun succAbove_zero j)) (p j) := by refine insertNth_eq_iff.2 ⟨by simp, ?_⟩ ext j convert (cons_succ x p j).symm @[simp] theorem insertNth_zero' (x : β) (p : Fin n → β) : @insertNth _ (fun _ ↦ β) 0 x p = cons x p := by simp [insertNth_zero] theorem insertNth_last (x : α (last n)) (p : ∀ j : Fin n, α ((last n).succAbove j)) : insertNth (last n) x p = snoc (fun j ↦ _root_.cast (congr_arg α (succAbove_last_apply j)) (p j)) x := by refine insertNth_eq_iff.2 ⟨by simp, ?_⟩ ext j apply eq_of_heq trans snoc (fun j ↦ _root_.cast (congr_arg α (succAbove_last_apply j)) (p j)) x (castSucc j) · rw [snoc_castSucc] exact (cast_heq _ _).symm · apply congr_arg_heq rw [succAbove_last] @[simp] theorem insertNth_last' (x : β) (p : Fin n → β) : @insertNth _ (fun _ ↦ β) (last n) x p = snoc p x := by simp [insertNth_last] lemma insertNth_rev {α : Type*} (i : Fin (n + 1)) (a : α) (f : Fin n → α) (j : Fin (n + 1)) : insertNth (α := fun _ ↦ α) i a f (rev j) = insertNth (α := fun _ ↦ α) i.rev a (f ∘ rev) j := by induction j using Fin.succAboveCases · exact rev i · simp · simp [rev_succAbove] theorem insertNth_comp_rev {α} (i : Fin (n + 1)) (x : α) (p : Fin n → α) : (Fin.insertNth i x p) ∘ Fin.rev = Fin.insertNth (Fin.rev i) x (p ∘ Fin.rev) := by funext x apply insertNth_rev theorem cons_rev {α n} (a : α) (f : Fin n → α) (i : Fin <| n + 1) : cons (α := fun _ => α) a f i.rev = snoc (α := fun _ => α) (f ∘ Fin.rev : Fin _ → α) a i := by simpa using insertNth_rev 0 a f i theorem cons_comp_rev {α n} (a : α) (f : Fin n → α) : Fin.cons a f ∘ Fin.rev = Fin.snoc (f ∘ Fin.rev) a := by funext i; exact cons_rev .. theorem snoc_rev {α n} (a : α) (f : Fin n → α) (i : Fin <| n + 1) : snoc (α := fun _ => α) f a i.rev = cons (α := fun _ => α) a (f ∘ Fin.rev : Fin _ → α) i := by simpa using insertNth_rev (last n) a f i theorem snoc_comp_rev {α n} (a : α) (f : Fin n → α) : Fin.snoc f a ∘ Fin.rev = Fin.cons a (f ∘ Fin.rev) := funext <| snoc_rev a f theorem insertNth_binop (op : ∀ j, α j → α j → α j) (i : Fin (n + 1)) (x y : α i) (p q : ∀ j, α (i.succAbove j)) : (i.insertNth (op i x y) fun j ↦ op _ (p j) (q j)) = fun j ↦ op j (i.insertNth x p j) (i.insertNth y q j) := insertNth_eq_iff.2 <| by unfold removeNth; simp section variable [∀ i, Preorder (α i)] theorem insertNth_le_iff {i : Fin (n + 1)} {x : α i} {p : ∀ j, α (i.succAbove j)} {q : ∀ j, α j} : i.insertNth x p ≤ q ↔ x ≤ q i ∧ p ≤ fun j ↦ q (i.succAbove j) := by simp [Pi.le_def, forall_iff_succAbove i] theorem le_insertNth_iff {i : Fin (n + 1)} {x : α i} {p : ∀ j, α (i.succAbove j)} {q : ∀ j, α j} : q ≤ i.insertNth x p ↔ q i ≤ x ∧ (fun j ↦ q (i.succAbove j)) ≤ p := by simp [Pi.le_def, forall_iff_succAbove i] end open Set @[simp] lemma removeNth_update (p : Fin (n + 1)) (x) (f : ∀ j, α j) : removeNth p (update f p x) = removeNth p f := by ext i; simp [removeNth, succAbove_ne] @[simp] lemma insertNth_removeNth (p : Fin (n + 1)) (x) (f : ∀ j, α j) : insertNth p x (removeNth p f) = update f p x := by simp [Fin.insertNth_eq_iff] lemma insertNth_self_removeNth (p : Fin (n + 1)) (f : ∀ j, α j) : insertNth p (f p) (removeNth p f) = f := by simp /-- Separates an `n+1`-tuple, returning a selected index and then the rest of the tuple. Functional form of `Equiv.piFinSuccAbove`. -/ @[deprecated removeNth (since := "2024-06-19")] def extractNth (i : Fin (n + 1)) (f : (∀ j, α j)) : α i × ∀ j, α (i.succAbove j) := (f i, removeNth i f) end InsertNth section Find /-- `find p` returns the first index `n` where `p n` is satisfied, and `none` if it is never satisfied. -/ def find : ∀ {n : ℕ} (p : Fin n → Prop) [DecidablePred p], Option (Fin n) | 0, _p, _ => none | n + 1, p, _ => by exact Option.casesOn (@find n (fun i ↦ p (i.castLT (Nat.lt_succ_of_lt i.2))) _) (if _ : p (Fin.last n) then some (Fin.last n) else none) fun i ↦ some (i.castLT (Nat.lt_succ_of_lt i.2)) /-- If `find p = some i`, then `p i` holds -/ theorem find_spec : ∀ {n : ℕ} (p : Fin n → Prop) [DecidablePred p] {i : Fin n} (_ : i ∈ Fin.find p), p i | 0, p, I, i, hi => Option.noConfusion hi | n + 1, p, I, i, hi => by rw [find] at hi cases' h : find fun i : Fin n ↦ p (i.castLT (Nat.lt_succ_of_lt i.2)) with j · rw [h] at hi dsimp at hi split_ifs at hi with hl · simp only [Option.mem_def, Option.some.injEq] at hi exact hi ▸ hl · exact (Option.not_mem_none _ hi).elim · rw [h] at hi dsimp at hi rw [← Option.some_inj.1 hi] exact @find_spec n (fun i ↦ p (i.castLT (Nat.lt_succ_of_lt i.2))) _ _ h /-- `find p` does not return `none` if and only if `p i` holds at some index `i`. -/ theorem isSome_find_iff : ∀ {n : ℕ} {p : Fin n → Prop} [DecidablePred p], (find p).isSome ↔ ∃ i, p i | 0, p, _ => iff_of_false (fun h ↦ Bool.noConfusion h) fun ⟨i, _⟩ ↦ Fin.elim0 i | n + 1, p, _ => ⟨fun h ↦ by rw [Option.isSome_iff_exists] at h cases' h with i hi exact ⟨i, find_spec _ hi⟩, fun ⟨⟨i, hin⟩, hi⟩ ↦ by dsimp [find] cases' h : find fun i : Fin n ↦ p (i.castLT (Nat.lt_succ_of_lt i.2)) with j · split_ifs with hl · exact Option.isSome_some · have := (@isSome_find_iff n (fun x ↦ p (x.castLT (Nat.lt_succ_of_lt x.2))) _).2 ⟨⟨i, lt_of_le_of_ne (Nat.le_of_lt_succ hin) fun h ↦ by cases h; exact hl hi⟩, hi⟩ rw [h] at this exact this · simp⟩ /-- `find p` returns `none` if and only if `p i` never holds. -/ theorem find_eq_none_iff {n : ℕ} {p : Fin n → Prop} [DecidablePred p] : find p = none ↔ ∀ i, ¬p i := by rw [← not_exists, ← isSome_find_iff]; cases find p <;> simp /-- If `find p` returns `some i`, then `p j` does not hold for `j < i`, i.e., `i` is minimal among the indices where `p` holds. -/ theorem find_min : ∀ {n : ℕ} {p : Fin n → Prop} [DecidablePred p] {i : Fin n} (_ : i ∈ Fin.find p) {j : Fin n} (_ : j < i), ¬p j | 0, p, _, i, hi, _, _, _ => Option.noConfusion hi | n + 1, p, _, i, hi, ⟨j, hjn⟩, hj, hpj => by rw [find] at hi cases' h : find fun i : Fin n ↦ p (i.castLT (Nat.lt_succ_of_lt i.2)) with k · simp only [h] at hi split_ifs at hi with hl · cases hi rw [find_eq_none_iff] at h exact h ⟨j, hj⟩ hpj · exact Option.not_mem_none _ hi · rw [h] at hi dsimp at hi obtain rfl := Option.some_inj.1 hi exact find_min h (show (⟨j, lt_trans hj k.2⟩ : Fin n) < k from hj) hpj theorem find_min' {p : Fin n → Prop} [DecidablePred p] {i : Fin n} (h : i ∈ Fin.find p) {j : Fin n} (hj : p j) : i ≤ j := Fin.not_lt.1 fun hij ↦ find_min h hij hj theorem nat_find_mem_find {p : Fin n → Prop} [DecidablePred p] (h : ∃ i, ∃ hin : i < n, p ⟨i, hin⟩) : (⟨Nat.find h, (Nat.find_spec h).fst⟩ : Fin n) ∈ find p := by let ⟨i, hin, hi⟩ := h cases' hf : find p with f · rw [find_eq_none_iff] at hf exact (hf ⟨i, hin⟩ hi).elim · refine Option.some_inj.2 (Fin.le_antisymm ?_ ?_) · exact find_min' hf (Nat.find_spec h).snd · exact Nat.find_min' _ ⟨f.2, by convert find_spec p hf⟩ theorem mem_find_iff {p : Fin n → Prop} [DecidablePred p] {i : Fin n} : i ∈ Fin.find p ↔ p i ∧ ∀ j, p j → i ≤ j := ⟨fun hi ↦ ⟨find_spec _ hi, fun _ ↦ find_min' hi⟩, by rintro ⟨hpi, hj⟩ cases hfp : Fin.find p · rw [find_eq_none_iff] at hfp exact (hfp _ hpi).elim · exact Option.some_inj.2 (Fin.le_antisymm (find_min' hfp hpi) (hj _ (find_spec _ hfp)))⟩ theorem find_eq_some_iff {p : Fin n → Prop} [DecidablePred p] {i : Fin n} : Fin.find p = some i ↔ p i ∧ ∀ j, p j → i ≤ j := mem_find_iff theorem mem_find_of_unique {p : Fin n → Prop} [DecidablePred p] (h : ∀ i j, p i → p j → i = j) {i : Fin n} (hi : p i) : i ∈ Fin.find p := mem_find_iff.2 ⟨hi, fun j hj ↦ Fin.le_of_eq <| h i j hi hj⟩ end Find section ContractNth variable {α : Type*} /-- Sends `(g₀, ..., gₙ)` to `(g₀, ..., op gⱼ gⱼ₊₁, ..., gₙ)`. -/ def contractNth (j : Fin (n + 1)) (op : α → α → α) (g : Fin (n + 1) → α) (k : Fin n) : α := if (k : ℕ) < j then g (Fin.castSucc k) else if (k : ℕ) = j then op (g (Fin.castSucc k)) (g k.succ) else g k.succ theorem contractNth_apply_of_lt (j : Fin (n + 1)) (op : α → α → α) (g : Fin (n + 1) → α) (k : Fin n) (h : (k : ℕ) < j) : contractNth j op g k = g (Fin.castSucc k) := if_pos h theorem contractNth_apply_of_eq (j : Fin (n + 1)) (op : α → α → α) (g : Fin (n + 1) → α) (k : Fin n) (h : (k : ℕ) = j) : contractNth j op g k = op (g (Fin.castSucc k)) (g k.succ) := by have : ¬(k : ℕ) < j := not_lt.2 (le_of_eq h.symm) rw [contractNth, if_neg this, if_pos h] theorem contractNth_apply_of_gt (j : Fin (n + 1)) (op : α → α → α) (g : Fin (n + 1) → α) (k : Fin n) (h : (j : ℕ) < k) : contractNth j op g k = g k.succ := by rw [contractNth, if_neg (not_lt_of_gt h), if_neg (Ne.symm <| ne_of_lt h)] theorem contractNth_apply_of_ne (j : Fin (n + 1)) (op : α → α → α) (g : Fin (n + 1) → α) (k : Fin n) (hjk : (j : ℕ) ≠ k) : contractNth j op g k = g (j.succAbove k) := by rcases lt_trichotomy (k : ℕ) j with (h | h | h) · rwa [j.succAbove_of_castSucc_lt, contractNth_apply_of_lt] · rwa [Fin.lt_iff_val_lt_val] · exact False.elim (hjk h.symm) · rwa [j.succAbove_of_le_castSucc, contractNth_apply_of_gt] · exact Fin.le_iff_val_le_val.2 (le_of_lt h) end ContractNth /-- To show two sigma pairs of tuples agree, it to show the second elements are related via `Fin.cast`. -/ theorem sigma_eq_of_eq_comp_cast {α : Type*} : ∀ {a b : Σii, Fin ii → α} (h : a.fst = b.fst), a.snd = b.snd ∘ Fin.cast h → a = b | ⟨ai, a⟩, ⟨bi, b⟩, hi, h => by dsimp only at hi subst hi simpa using h /-- `Fin.sigma_eq_of_eq_comp_cast` as an `iff`. -/ theorem sigma_eq_iff_eq_comp_cast {α : Type*} {a b : Σii, Fin ii → α} : a = b ↔ ∃ h : a.fst = b.fst, a.snd = b.snd ∘ Fin.cast h := ⟨fun h ↦ h ▸ ⟨rfl, funext <| Fin.rec fun _ _ ↦ rfl⟩, fun ⟨_, h'⟩ ↦ sigma_eq_of_eq_comp_cast _ h'⟩ end Fin
Data\Fin\Tuple\BubbleSortInduction.lean
/- Copyright (c) 2022 Michael Stoll. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Michael Stoll -/ import Mathlib.Data.Fin.Tuple.Sort import Mathlib.Order.WellFounded import Mathlib.Order.PiLex /-! # "Bubble sort" induction We implement the following induction principle `Tuple.bubble_sort_induction` on tuples with values in a linear order `α`. Let `f : Fin n → α` and let `P` be a predicate on `Fin n → α`. Then we can show that `f ∘ sort f` satisfies `P` if `f` satisfies `P`, and whenever some `g : Fin n → α` satisfies `P` and `g i > g j` for some `i < j`, then `g ∘ swap i j` also satisfies `P`. We deduce it from a stronger variant `Tuple.bubble_sort_induction'`, which requires the assumption only for `g` that are permutations of `f`. The latter is proved by well-founded induction via `WellFounded.induction_bot'` with respect to the lexicographic ordering on the finite set of all permutations of `f`. -/ namespace Tuple /-- *Bubble sort induction*: Prove that the sorted version of `f` has some property `P` if `f` satisfies `P` and `P` is preserved on permutations of `f` when swapping two antitone values. -/ theorem bubble_sort_induction' {n : ℕ} {α : Type*} [LinearOrder α] {f : Fin n → α} {P : (Fin n → α) → Prop} (hf : P f) (h : ∀ (σ : Equiv.Perm (Fin n)) (i j : Fin n), i < j → (f ∘ σ) j < (f ∘ σ) i → P (f ∘ σ) → P (f ∘ σ ∘ Equiv.swap i j)) : P (f ∘ sort f) := by letI := @Preorder.lift _ (Lex (Fin n → α)) _ fun σ : Equiv.Perm (Fin n) => toLex (f ∘ σ) refine @WellFounded.induction_bot' _ _ _ (IsWellFounded.wf : WellFounded (· < ·)) (Equiv.refl _) (sort f) P (fun σ => f ∘ σ) (fun σ hσ hfσ => ?_) hf obtain ⟨i, j, hij₁, hij₂⟩ := antitone_pair_of_not_sorted' hσ exact ⟨σ * Equiv.swap i j, Pi.lex_desc hij₁.le hij₂, h σ i j hij₁ hij₂ hfσ⟩ /-- *Bubble sort induction*: Prove that the sorted version of `f` has some property `P` if `f` satisfies `P` and `P` is preserved when swapping two antitone values. -/ theorem bubble_sort_induction {n : ℕ} {α : Type*} [LinearOrder α] {f : Fin n → α} {P : (Fin n → α) → Prop} (hf : P f) (h : ∀ (g : Fin n → α) (i j : Fin n), i < j → g j < g i → P g → P (g ∘ Equiv.swap i j)) : P (f ∘ sort f) := bubble_sort_induction' hf fun _ => h _ end Tuple
Data\Fin\Tuple\Curry.lean
/- Copyright (c) 2023 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser, Brendan Murphy -/ import Mathlib.Data.Fin.Tuple.Basic import Mathlib.Logic.Equiv.Fin import Mathlib.Logic.Function.OfArity /-! # Currying and uncurrying of n-ary functions A function of `n` arguments can either be written as `f a₁ a₂ ⋯ aₙ` or `f' ![a₁, a₂, ⋯, aₙ]`. This file provides the currying and uncurrying operations that convert between the two, as n-ary generalizations of the binary `curry` and `uncurry`. ## Main definitions * `Function.OfArity.uncurry`: convert an `n`-ary function to a function from `Fin n → α`. * `Function.OfArity.curry`: convert a function from `Fin n → α` to an `n`-ary function. * `Function.FromTypes.uncurry`: convert an `p`-ary heterogeneous function to a function from `(i : Fin n) → p i`. * `Function.FromTypes.curry`: convert a function from `(i : Fin n) → p i` to a `p`-ary heterogeneous function. -/ universe u v w w' namespace Function.FromTypes open Matrix (vecCons vecHead vecTail vecEmpty) /-- Uncurry all the arguments of `Function.FromTypes p τ` to get a function from a tuple. Note this can be used on raw functions if used. -/ def uncurry : {n : ℕ} → {p : Fin n → Type u} → {τ : Type u} → (f : Function.FromTypes p τ) → ((i : Fin n) → p i) → τ | 0 , _, _, f => fun _ => f | _ + 1, _, _, f => fun args => (f (args 0)).uncurry (args ∘' Fin.succ) /-- Curry all the arguments of `Function.FromTypes p τ` to get a function from a tuple. -/ def curry : {n : ℕ} → {p : Fin n → Type u} → {τ : Type u} → (((i : Fin n) → p i) → τ) → Function.FromTypes p τ | 0 , _, _, f => f isEmptyElim | _ + 1, _, _, f => fun a => curry (fun args => f (Fin.cons a args)) @[simp] theorem uncurry_apply_cons {n : ℕ} {α} {p : Fin n → Type u} {τ : Type u} (f : Function.FromTypes (vecCons α p) τ) (a : α) (args : (i : Fin n) → p i) : uncurry f (Fin.cons a args) = @uncurry _ p _ (f a) args := rfl @[simp low] theorem uncurry_apply_succ {n : ℕ} {p : Fin (n + 1) → Type u} {τ : Type u} (f : Function.FromTypes p τ) (args : (i : Fin (n + 1)) → p i) : uncurry f args = uncurry (f (args 0)) (Fin.tail args) := @uncurry_apply_cons n (p 0) (vecTail p) τ f (args 0) (Fin.tail args) @[simp] theorem curry_apply_cons {n : ℕ} {α} {p : Fin n → Type u} {τ : Type u} (f : ((i : Fin (n + 1)) → (vecCons α p) i) → τ) (a : α) : curry f a = @curry _ p _ (f ∘' Fin.cons a) := rfl @[simp low] theorem curry_apply_succ {n : ℕ} {p : Fin (n + 1) → Type u} {τ : Type u} (f : ((i : Fin (n + 1)) → p i) → τ) (a : p 0) : curry f a = curry (f ∘ Fin.cons a) := rfl variable {n : ℕ} {p : Fin n → Type u} {τ : Type u} @[simp] theorem curry_uncurry (f : Function.FromTypes p τ) : curry (uncurry f) = f := by induction n with | zero => rfl | succ n ih => exact funext (ih $ f ·) @[simp] theorem uncurry_curry (f : ((i : Fin n) → p i) → τ) : uncurry (curry f) = f := by ext args induction n with | zero => exact congrArg f (Subsingleton.allEq _ _) | succ n ih => exact Eq.trans (ih _ _) (congrArg f (Fin.cons_self_tail args)) /-- `Equiv.curry` for `p`-ary heterogeneous functions. -/ @[simps] def curryEquiv (p : Fin n → Type u) : (((i : Fin n) → p i) → τ) ≃ FromTypes p τ where toFun := curry invFun := uncurry left_inv := uncurry_curry right_inv := curry_uncurry lemma curry_two_eq_curry {p : Fin 2 → Type u} {τ : Type u} (f : ((i : Fin 2) → p i) → τ) : curry f = Function.curry (f ∘ (piFinTwoEquiv p).symm) := rfl lemma uncurry_two_eq_uncurry (p : Fin 2 → Type u) (τ : Type u) (f : Function.FromTypes p τ) : uncurry f = Function.uncurry f ∘ piFinTwoEquiv p := rfl end Function.FromTypes namespace Function.OfArity variable {α β : Type u} /-- Uncurry all the arguments of `Function.OfArity α n` to get a function from a tuple. Note this can be used on raw functions if used. -/ def uncurry {n} (f : Function.OfArity α β n) : (Fin n → α) → β := FromTypes.uncurry f /-- Curry all the arguments of `Function.OfArity α β n` to get a function from a tuple. -/ def curry {n} (f : (Fin n → α) → β) : Function.OfArity α β n := FromTypes.curry f @[simp] theorem curry_uncurry {n} (f : Function.OfArity α β n) : curry (uncurry f) = f := FromTypes.curry_uncurry f @[simp] theorem uncurry_curry {n} (f : (Fin n → α) → β) : uncurry (curry f) = f := FromTypes.uncurry_curry f /-- `Equiv.curry` for n-ary functions. -/ @[simps!] def curryEquiv (n : ℕ) : ((Fin n → α) → β) ≃ OfArity α β n := FromTypes.curryEquiv _ lemma curry_two_eq_curry {α β : Type u} (f : ((i : Fin 2) → α) → β) : curry f = Function.curry (f ∘ (finTwoArrowEquiv α).symm) := FromTypes.curry_two_eq_curry f lemma uncurry_two_eq_uncurry {α β : Type u} (f : OfArity α β 2) : uncurry f = Function.uncurry f ∘ (finTwoArrowEquiv α) := FromTypes.uncurry_two_eq_uncurry _ _ f end Function.OfArity
Data\Fin\Tuple\Finset.lean
/- Copyright (c) 2023 Bolton Bailey. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bolton Bailey -/ import Mathlib.Data.Fin.Tuple.Basic import Mathlib.Data.Fintype.Pi /-! # Fin-indexed tuples of finsets -/ open Fintype namespace Fin variable {n : ℕ} {α : Fin (n + 1) → Type*} lemma mem_piFinset_succ {x : ∀ i, α i} {s : ∀ i, Finset (α i)} : x ∈ piFinset s ↔ x 0 ∈ s 0 ∧ tail x ∈ piFinset (tail s) := by simp only [mem_piFinset, forall_fin_succ, tail] lemma mem_piFinset_succ' {x : ∀ i, α i} {s : ∀ i, Finset (α i)} : x ∈ piFinset s ↔ init x ∈ piFinset (init s) ∧ x (last n) ∈ s (last n) := by simp only [mem_piFinset, forall_fin_succ', init] lemma cons_mem_piFinset_cons {x₀ : α 0} {x : ∀ i : Fin n, α i.succ} {s₀ : Finset (α 0)} {s : ∀ i : Fin n, Finset (α i.succ)} : cons x₀ x ∈ piFinset (cons s₀ s) ↔ x₀ ∈ s₀ ∧ x ∈ piFinset s := by simp_rw [mem_piFinset_succ, cons_zero, tail_cons] lemma snoc_mem_piFinset_snoc {x : ∀ i : Fin n, α i.castSucc} {xₙ : α (.last n)} {s : ∀ i : Fin n, Finset (α i.castSucc)} {sₙ : Finset (α $ .last n)} : snoc x xₙ ∈ piFinset (snoc s sₙ) ↔ x ∈ piFinset s ∧ xₙ ∈ sₙ := by simp_rw [mem_piFinset_succ', init_snoc, snoc_last] end Fin
Data\Fin\Tuple\NatAntidiagonal.lean
/- Copyright (c) 2022 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import Mathlib.Algebra.BigOperators.Fin import Mathlib.Algebra.Group.Fin.Tuple import Mathlib.Data.Finset.NatAntidiagonal import Mathlib.Order.Fin.Tuple /-! # Collections of tuples of naturals with the same sum This file generalizes `List.Nat.Antidiagonal n`, `Multiset.Nat.Antidiagonal n`, and `Finset.Nat.Antidiagonal n` from the pair of elements `x : ℕ × ℕ` such that `n = x.1 + x.2`, to the sequence of elements `x : Fin k → ℕ` such that `n = ∑ i, x i`. ## Main definitions * `List.Nat.antidiagonalTuple` * `Multiset.Nat.antidiagonalTuple` * `Finset.Nat.antidiagonalTuple` ## Main results * `antidiagonalTuple 2 n` is analogous to `antidiagonal n`: * `List.Nat.antidiagonalTuple_two` * `Multiset.Nat.antidiagonalTuple_two` * `Finset.Nat.antidiagonalTuple_two` ## Implementation notes While we could implement this by filtering `(Fintype.PiFinset fun _ ↦ range (n + 1))` or similar, this implementation would be much slower. In the future, we could consider generalizing `Finset.Nat.antidiagonalTuple` further to support finitely-supported functions, as is done with `cut` in `archive/100-theorems-list/45_partition.lean`. -/ /-! ### Lists -/ namespace List.Nat /-- `List.antidiagonalTuple k n` is a list of all `k`-tuples which sum to `n`. This list contains no duplicates (`List.Nat.nodup_antidiagonalTuple`), and is sorted lexicographically (`List.Nat.antidiagonalTuple_pairwise_pi_lex`), starting with `![0, ..., n]` and ending with `![n, ..., 0]`. ``` #eval antidiagonalTuple 3 2 -- [![0, 0, 2], ![0, 1, 1], ![0, 2, 0], ![1, 0, 1], ![1, 1, 0], ![2, 0, 0]] ``` -/ def antidiagonalTuple : ∀ k, ℕ → List (Fin k → ℕ) | 0, 0 => [![]] | 0, _ + 1 => [] | k + 1, n => (List.Nat.antidiagonal n).bind fun ni => (antidiagonalTuple k ni.2).map fun x => Fin.cons ni.1 x @[simp] theorem antidiagonalTuple_zero_zero : antidiagonalTuple 0 0 = [![]] := rfl @[simp] theorem antidiagonalTuple_zero_succ (n : ℕ) : antidiagonalTuple 0 (n + 1) = [] := rfl theorem mem_antidiagonalTuple {n : ℕ} {k : ℕ} {x : Fin k → ℕ} : x ∈ antidiagonalTuple k n ↔ ∑ i, x i = n := by induction x using Fin.consInduction generalizing n with | h0 => cases n · decide · simp [eq_comm] | h x₀ x ih => simp_rw [Fin.sum_cons, antidiagonalTuple, List.mem_bind, List.mem_map, List.Nat.mem_antidiagonal, Fin.cons_eq_cons, exists_eq_right_right, ih, @eq_comm _ _ (Prod.snd _), and_comm (a := Prod.snd _ = _), ← Prod.mk.inj_iff (a₁ := Prod.fst _), exists_eq_right] /-- The antidiagonal of `n` does not contain duplicate entries. -/ theorem nodup_antidiagonalTuple (k n : ℕ) : List.Nodup (antidiagonalTuple k n) := by induction' k with k ih generalizing n · cases n · simp · simp [eq_comm] simp_rw [antidiagonalTuple, List.nodup_bind] constructor · intro i _ exact (ih i.snd).map (Fin.cons_right_injective (α := fun _ => ℕ) i.fst) induction' n with n n_ih · exact List.pairwise_singleton _ _ · rw [List.Nat.antidiagonal_succ] refine List.Pairwise.cons (fun a ha x hx₁ hx₂ => ?_) (n_ih.map _ fun a b h x hx₁ hx₂ => ?_) · rw [List.mem_map] at hx₁ hx₂ ha obtain ⟨⟨a, -, rfl⟩, ⟨x₁, -, rfl⟩, ⟨x₂, -, h⟩⟩ := ha, hx₁, hx₂ rw [Fin.cons_eq_cons] at h injection h.1 · rw [List.mem_map] at hx₁ hx₂ obtain ⟨⟨x₁, hx₁, rfl⟩, ⟨x₂, hx₂, h₁₂⟩⟩ := hx₁, hx₂ dsimp at h₁₂ rw [Fin.cons_eq_cons, Nat.succ_inj'] at h₁₂ obtain ⟨h₁₂, rfl⟩ := h₁₂ rw [h₁₂] at h exact h (List.mem_map_of_mem _ hx₁) (List.mem_map_of_mem _ hx₂) theorem antidiagonalTuple_zero_right : ∀ k, antidiagonalTuple k 0 = [0] | 0 => (congr_arg fun x => [x]) <| Subsingleton.elim _ _ | k + 1 => by rw [antidiagonalTuple, antidiagonal_zero, List.bind_singleton, antidiagonalTuple_zero_right k, List.map_singleton] exact congr_arg (fun x => [x]) Matrix.cons_zero_zero @[simp] theorem antidiagonalTuple_one (n : ℕ) : antidiagonalTuple 1 n = [![n]] := by simp_rw [antidiagonalTuple, antidiagonal, List.range_succ, List.map_append, List.map_singleton, tsub_self, List.bind_append, List.bind_singleton, List.bind_map] conv_rhs => rw [← List.nil_append [![n]]] congr 1 simp_rw [List.bind_eq_nil, List.mem_range, List.map_eq_nil] intro x hx obtain ⟨m, rfl⟩ := Nat.exists_eq_add_of_lt hx rw [add_assoc, add_tsub_cancel_left, antidiagonalTuple_zero_succ] theorem antidiagonalTuple_two (n : ℕ) : antidiagonalTuple 2 n = (antidiagonal n).map fun i => ![i.1, i.2] := by rw [antidiagonalTuple] simp_rw [antidiagonalTuple_one, List.map_singleton] rw [List.map_eq_bind] rfl theorem antidiagonalTuple_pairwise_pi_lex : ∀ k n, (antidiagonalTuple k n).Pairwise (Pi.Lex (· < ·) @fun _ => (· < ·)) | 0, 0 => List.pairwise_singleton _ _ | 0, _ + 1 => List.Pairwise.nil | k + 1, n => by simp_rw [antidiagonalTuple, List.pairwise_bind, List.pairwise_map, List.mem_map, forall_exists_index, and_imp, forall_apply_eq_imp_iff₂] simp only [mem_antidiagonal, Prod.forall, and_imp, forall_apply_eq_imp_iff₂] simp only [Fin.pi_lex_lt_cons_cons, eq_self_iff_true, true_and_iff, lt_self_iff_false, false_or_iff] refine ⟨fun _ _ _ => antidiagonalTuple_pairwise_pi_lex k _, ?_⟩ induction' n with n n_ih · rw [antidiagonal_zero] exact List.pairwise_singleton _ _ · rw [antidiagonal_succ, List.pairwise_cons, List.pairwise_map] refine ⟨fun p hp x hx y hy => ?_, ?_⟩ · rw [List.mem_map, Prod.exists] at hp obtain ⟨a, b, _, rfl : (Nat.succ a, b) = p⟩ := hp exact Or.inl (Nat.zero_lt_succ _) dsimp simp_rw [Nat.succ_inj', Nat.succ_lt_succ_iff] exact n_ih end List.Nat /-! ### Multisets -/ namespace Multiset.Nat /-- `Multiset.Nat.antidiagonalTuple k n` is a multiset of `k`-tuples summing to `n` -/ def antidiagonalTuple (k n : ℕ) : Multiset (Fin k → ℕ) := List.Nat.antidiagonalTuple k n @[simp] theorem antidiagonalTuple_zero_zero : antidiagonalTuple 0 0 = {![]} := rfl @[simp] theorem antidiagonalTuple_zero_succ (n : ℕ) : antidiagonalTuple 0 n.succ = 0 := rfl theorem mem_antidiagonalTuple {n : ℕ} {k : ℕ} {x : Fin k → ℕ} : x ∈ antidiagonalTuple k n ↔ ∑ i, x i = n := List.Nat.mem_antidiagonalTuple theorem nodup_antidiagonalTuple (k n : ℕ) : (antidiagonalTuple k n).Nodup := List.Nat.nodup_antidiagonalTuple _ _ theorem antidiagonalTuple_zero_right (k : ℕ) : antidiagonalTuple k 0 = {0} := congr_arg _ (List.Nat.antidiagonalTuple_zero_right k) @[simp] theorem antidiagonalTuple_one (n : ℕ) : antidiagonalTuple 1 n = {![n]} := congr_arg _ (List.Nat.antidiagonalTuple_one n) theorem antidiagonalTuple_two (n : ℕ) : antidiagonalTuple 2 n = (antidiagonal n).map fun i => ![i.1, i.2] := congr_arg _ (List.Nat.antidiagonalTuple_two n) end Multiset.Nat /-! ### Finsets -/ namespace Finset.Nat /-- `Finset.Nat.antidiagonalTuple k n` is a finset of `k`-tuples summing to `n` -/ def antidiagonalTuple (k n : ℕ) : Finset (Fin k → ℕ) := ⟨Multiset.Nat.antidiagonalTuple k n, Multiset.Nat.nodup_antidiagonalTuple k n⟩ @[simp] theorem antidiagonalTuple_zero_zero : antidiagonalTuple 0 0 = {![]} := rfl @[simp] theorem antidiagonalTuple_zero_succ (n : ℕ) : antidiagonalTuple 0 n.succ = ∅ := rfl theorem mem_antidiagonalTuple {n : ℕ} {k : ℕ} {x : Fin k → ℕ} : x ∈ antidiagonalTuple k n ↔ ∑ i, x i = n := List.Nat.mem_antidiagonalTuple theorem antidiagonalTuple_zero_right (k : ℕ) : antidiagonalTuple k 0 = {0} := Finset.eq_of_veq (Multiset.Nat.antidiagonalTuple_zero_right k) @[simp] theorem antidiagonalTuple_one (n : ℕ) : antidiagonalTuple 1 n = {![n]} := Finset.eq_of_veq (Multiset.Nat.antidiagonalTuple_one n) theorem antidiagonalTuple_two (n : ℕ) : antidiagonalTuple 2 n = (antidiagonal n).map (piFinTwoEquiv fun _ => ℕ).symm.toEmbedding := Finset.eq_of_veq (Multiset.Nat.antidiagonalTuple_two n) section EquivProd /-- The disjoint union of antidiagonal tuples `Σ n, antidiagonalTuple k n` is equivalent to the `k`-tuple `Fin k → ℕ`. This is such an equivalence, obtained by mapping `(n, x)` to `x`. This is the tuple version of `Finset.sigmaAntidiagonalEquivProd`. -/ @[simps] def sigmaAntidiagonalTupleEquivTuple (k : ℕ) : (Σ n, antidiagonalTuple k n) ≃ (Fin k → ℕ) where toFun x := x.2 invFun x := ⟨∑ i, x i, x, mem_antidiagonalTuple.mpr rfl⟩ left_inv := fun ⟨_, _, h⟩ => Sigma.subtype_ext (mem_antidiagonalTuple.mp h) rfl right_inv _ := rfl end EquivProd end Finset.Nat
Data\Fin\Tuple\Reflection.lean
/- Copyright (c) 2022 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import Mathlib.Data.Fin.VecNotation import Mathlib.Algebra.BigOperators.Fin /-! # Lemmas for tuples `Fin m → α` This file contains alternative definitions of common operators on vectors which expand definitionally to the expected expression when evaluated on `![]` notation. This allows "proof by reflection", where we prove `f = ![f 0, f 1]` by defining `FinVec.etaExpand f` to be equal to the RHS definitionally, and then prove that `f = etaExpand f`. The definitions in this file should normally not be used directly; the intent is for the corresponding `*_eq` lemmas to be used in a place where they are definitionally unfolded. ## Main definitions * `FinVec.seq` * `FinVec.map` * `FinVec.sum` * `FinVec.etaExpand` -/ namespace FinVec variable {m n : ℕ} {α β γ : Type*} /-- Evaluate `FinVec.seq f v = ![(f 0) (v 0), (f 1) (v 1), ...]` -/ def seq : ∀ {m}, (Fin m → α → β) → (Fin m → α) → Fin m → β | 0, _, _ => ![] | _ + 1, f, v => Matrix.vecCons (f 0 (v 0)) (seq (Matrix.vecTail f) (Matrix.vecTail v)) @[simp] theorem seq_eq : ∀ {m} (f : Fin m → α → β) (v : Fin m → α), seq f v = fun i => f i (v i) | 0, f, v => Subsingleton.elim _ _ | n + 1, f, v => funext fun i => by simp_rw [seq, seq_eq] refine i.cases ?_ fun i => ?_ · rfl · rw [Matrix.cons_val_succ] rfl example {f₁ f₂ : α → β} (a₁ a₂ : α) : seq ![f₁, f₂] ![a₁, a₂] = ![f₁ a₁, f₂ a₂] := rfl /-- `FinVec.map f v = ![f (v 0), f (v 1), ...]` -/ def map (f : α → β) {m} : (Fin m → α) → Fin m → β := seq fun _ => f /-- This can be use to prove ```lean example {f : α → β} (a₁ a₂ : α) : f ∘ ![a₁, a₂] = ![f a₁, f a₂] := (map_eq _ _).symm ``` -/ @[simp] theorem map_eq (f : α → β) {m} (v : Fin m → α) : map f v = f ∘ v := seq_eq _ _ example {f : α → β} (a₁ a₂ : α) : f ∘ ![a₁, a₂] = ![f a₁, f a₂] := (map_eq _ _).symm /-- Expand `v` to `![v 0, v 1, ...]` -/ def etaExpand {m} (v : Fin m → α) : Fin m → α := map id v /-- This can be use to prove ```lean example (a : Fin 2 → α) : a = ![a 0, a 1] := (etaExpand_eq _).symm ``` -/ @[simp] theorem etaExpand_eq {m} (v : Fin m → α) : etaExpand v = v := map_eq id v example (a : Fin 2 → α) : a = ![a 0, a 1] := (etaExpand_eq _).symm /-- `∀` with better defeq for `∀ x : Fin m → α, P x`. -/ def Forall : ∀ {m} (_ : (Fin m → α) → Prop), Prop | 0, P => P ![] | _ + 1, P => ∀ x : α, Forall fun v => P (Matrix.vecCons x v) /-- This can be use to prove ```lean example (P : (Fin 2 → α) → Prop) : (∀ f, P f) ↔ ∀ a₀ a₁, P ![a₀, a₁] := (forall_iff _).symm ``` -/ @[simp] theorem forall_iff : ∀ {m} (P : (Fin m → α) → Prop), Forall P ↔ ∀ x, P x | 0, P => by simp only [Forall, Fin.forall_fin_zero_pi] rfl | .succ n, P => by simp only [Forall, forall_iff, Fin.forall_fin_succ_pi, Matrix.vecCons] example (P : (Fin 2 → α) → Prop) : (∀ f, P f) ↔ ∀ a₀ a₁, P ![a₀, a₁] := (forall_iff _).symm /-- `∃` with better defeq for `∃ x : Fin m → α, P x`. -/ def Exists : ∀ {m} (_ : (Fin m → α) → Prop), Prop | 0, P => P ![] | _ + 1, P => ∃ x : α, Exists fun v => P (Matrix.vecCons x v) /-- This can be use to prove ```lean example (P : (Fin 2 → α) → Prop) : (∃ f, P f) ↔ ∃ a₀ a₁, P ![a₀, a₁] := (exists_iff _).symm ``` -/ theorem exists_iff : ∀ {m} (P : (Fin m → α) → Prop), Exists P ↔ ∃ x, P x | 0, P => by simp only [Exists, Fin.exists_fin_zero_pi, Matrix.vecEmpty] rfl | .succ n, P => by simp only [Exists, exists_iff, Fin.exists_fin_succ_pi, Matrix.vecCons] example (P : (Fin 2 → α) → Prop) : (∃ f, P f) ↔ ∃ a₀ a₁, P ![a₀, a₁] := (exists_iff _).symm /-- `Finset.univ.sum` with better defeq for `Fin`. -/ def sum [Add α] [Zero α] : ∀ {m} (_ : Fin m → α), α | 0, _ => 0 | 1, v => v 0 -- Porting note: inline `∘` since it is no longer reducible | _ + 2, v => sum (fun i => v (Fin.castSucc i)) + v (Fin.last _) /-- This can be used to prove ```lean example [AddCommMonoid α] (a : Fin 3 → α) : ∑ i, a i = a 0 + a 1 + a 2 := (sum_eq _).symm ``` -/ @[simp] theorem sum_eq [AddCommMonoid α] : ∀ {m} (a : Fin m → α), sum a = ∑ i, a i | 0, a => rfl | 1, a => (Fintype.sum_unique a).symm | n + 2, a => by rw [Fin.sum_univ_castSucc, sum, sum_eq] example [AddCommMonoid α] (a : Fin 3 → α) : ∑ i, a i = a 0 + a 1 + a 2 := (sum_eq _).symm end FinVec
Data\Fin\Tuple\Sort.lean
/- Copyright (c) 2021 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller -/ import Mathlib.Data.Finset.Sort import Mathlib.Data.List.FinRange import Mathlib.Data.Prod.Lex import Mathlib.GroupTheory.Perm.Basic import Mathlib.Order.Interval.Finset.Fin /-! # Sorting tuples by their values Given an `n`-tuple `f : Fin n → α` where `α` is ordered, we may want to turn it into a sorted `n`-tuple. This file provides an API for doing so, with the sorted `n`-tuple given by `f ∘ Tuple.sort f`. ## Main declarations * `Tuple.sort`: given `f : Fin n → α`, produces a permutation on `Fin n` * `Tuple.monotone_sort`: `f ∘ Tuple.sort f` is `Monotone` -/ namespace Tuple variable {n : ℕ} variable {α : Type*} [LinearOrder α] /-- `graph f` produces the finset of pairs `(f i, i)` equipped with the lexicographic order. -/ def graph (f : Fin n → α) : Finset (α ×ₗ Fin n) := Finset.univ.image fun i => (f i, i) /-- Given `p : α ×ₗ (Fin n) := (f i, i)` with `p ∈ graph f`, `graph.proj p` is defined to be `f i`. -/ def graph.proj {f : Fin n → α} : graph f → α := fun p => p.1.1 @[simp] theorem graph.card (f : Fin n → α) : (graph f).card = n := by rw [graph, Finset.card_image_of_injective] · exact Finset.card_fin _ · intro _ _ -- porting note (#10745): was `simp` dsimp only rw [Prod.ext_iff] simp /-- `graphEquiv₁ f` is the natural equivalence between `Fin n` and `graph f`, mapping `i` to `(f i, i)`. -/ def graphEquiv₁ (f : Fin n → α) : Fin n ≃ graph f where toFun i := ⟨(f i, i), by simp [graph]⟩ invFun p := p.1.2 left_inv i := by simp right_inv := fun ⟨⟨x, i⟩, h⟩ => by -- Porting note: was `simpa [graph] using h` simp only [graph, Finset.mem_image, Finset.mem_univ, true_and] at h obtain ⟨i', hi'⟩ := h obtain ⟨-, rfl⟩ := Prod.mk.inj_iff.mp hi' simpa @[simp] theorem proj_equiv₁' (f : Fin n → α) : graph.proj ∘ graphEquiv₁ f = f := rfl /-- `graphEquiv₂ f` is an equivalence between `Fin n` and `graph f` that respects the order. -/ def graphEquiv₂ (f : Fin n → α) : Fin n ≃o graph f := Finset.orderIsoOfFin _ (by simp) /-- `sort f` is the permutation that orders `Fin n` according to the order of the outputs of `f`. -/ def sort (f : Fin n → α) : Equiv.Perm (Fin n) := (graphEquiv₂ f).toEquiv.trans (graphEquiv₁ f).symm theorem graphEquiv₂_apply (f : Fin n → α) (i : Fin n) : graphEquiv₂ f i = graphEquiv₁ f (sort f i) := ((graphEquiv₁ f).apply_symm_apply _).symm theorem self_comp_sort (f : Fin n → α) : f ∘ sort f = graph.proj ∘ graphEquiv₂ f := show graph.proj ∘ (graphEquiv₁ f ∘ (graphEquiv₁ f).symm) ∘ (graphEquiv₂ f).toEquiv = _ by simp theorem monotone_proj (f : Fin n → α) : Monotone (graph.proj : graph f → α) := by rintro ⟨⟨x, i⟩, hx⟩ ⟨⟨y, j⟩, hy⟩ (_ | h) · exact le_of_lt ‹_› · simp [graph.proj] theorem monotone_sort (f : Fin n → α) : Monotone (f ∘ sort f) := by rw [self_comp_sort] exact (monotone_proj f).comp (graphEquiv₂ f).monotone end Tuple namespace Tuple open List variable {n : ℕ} {α : Type*} /-- If `f₀ ≤ f₁ ≤ f₂ ≤ ⋯` is a sorted `m`-tuple of elements of `α`, then for any `j : Fin m` and `a : α` we have `j < #{i | fᵢ ≤ a}` iff `fⱼ ≤ a`. -/ theorem lt_card_le_iff_apply_le_of_monotone [PartialOrder α] [DecidableRel (α := α) LE.le] {m : ℕ} (f : Fin m → α) (a : α) (h_sorted : Monotone f) (j : Fin m) : j < Fintype.card {i // f i ≤ a} ↔ f j ≤ a := by suffices h1 : ∀ k : Fin m, (k < Fintype.card {i // f i ≤ a}) → f k ≤ a by refine ⟨h1 j, fun h ↦ ?_⟩ by_contra! hc let p : Fin m → Prop := fun x ↦ f x ≤ a let q : Fin m → Prop := fun x ↦ x < Fintype.card {i // f i ≤ a} let q' : {i // f i ≤ a} → Prop := fun x ↦ q x have hw : 0 < Fintype.card {j : {x : Fin m // f x ≤ a} // ¬ q' j} := Fintype.card_pos_iff.2 ⟨⟨⟨j, h⟩, not_lt.2 hc⟩⟩ apply hw.ne' have he := Fintype.card_congr <| Equiv.sumCompl <| q' have h4 := (Fintype.card_congr (@Equiv.subtypeSubtypeEquivSubtype _ p q (h1 _))) have h_le : Fintype.card { i // f i ≤ a } ≤ m := by conv_rhs => rw [← Fintype.card_fin m] exact Fintype.card_subtype_le _ rwa [Fintype.card_sum, h4, Fintype.card_fin_lt_of_le h_le, add_right_eq_self] at he intro _ h contrapose! h rw [← Fin.card_Iio, Fintype.card_subtype] refine Finset.card_mono (fun i => Function.mtr ?_) simp_rw [Finset.mem_filter, Finset.mem_univ, true_and, Finset.mem_Iio] intro hij hia apply h exact (h_sorted (le_of_not_lt hij)).trans hia theorem lt_card_ge_iff_apply_ge_of_antitone [PartialOrder α] [DecidableRel (α := α) LE.le] {m : ℕ} (f : Fin m → α) (a : α) (h_sorted : Antitone f) (j : Fin m) : j < Fintype.card {i // a ≤ f i} ↔ a ≤ f j := lt_card_le_iff_apply_le_of_monotone _ (OrderDual.toDual a) h_sorted.dual_right j /-- If two permutations of a tuple `f` are both monotone, then they are equal. -/ theorem unique_monotone [PartialOrder α] {f : Fin n → α} {σ τ : Equiv.Perm (Fin n)} (hfσ : Monotone (f ∘ σ)) (hfτ : Monotone (f ∘ τ)) : f ∘ σ = f ∘ τ := ofFn_injective <| eq_of_perm_of_sorted ((σ.ofFn_comp_perm f).trans (τ.ofFn_comp_perm f).symm) hfσ.ofFn_sorted hfτ.ofFn_sorted variable [LinearOrder α] {f : Fin n → α} {σ : Equiv.Perm (Fin n)} /-- A permutation `σ` equals `sort f` if and only if the map `i ↦ (f (σ i), σ i)` is strictly monotone (w.r.t. the lexicographic ordering on the target). -/ theorem eq_sort_iff' : σ = sort f ↔ StrictMono (σ.trans <| graphEquiv₁ f) := by constructor <;> intro h · rw [h, sort, Equiv.trans_assoc, Equiv.symm_trans_self] exact (graphEquiv₂ f).strictMono · have := Subsingleton.elim (graphEquiv₂ f) (h.orderIsoOfSurjective _ <| Equiv.surjective _) ext1 x exact (graphEquiv₁ f).apply_eq_iff_eq_symm_apply.1 (DFunLike.congr_fun this x).symm /-- A permutation `σ` equals `sort f` if and only if `f ∘ σ` is monotone and whenever `i < j` and `f (σ i) = f (σ j)`, then `σ i < σ j`. This means that `sort f` is the lexicographically smallest permutation `σ` such that `f ∘ σ` is monotone. -/ theorem eq_sort_iff : σ = sort f ↔ Monotone (f ∘ σ) ∧ ∀ i j, i < j → f (σ i) = f (σ j) → σ i < σ j := by rw [eq_sort_iff'] refine ⟨fun h => ⟨(monotone_proj f).comp h.monotone, fun i j hij hfij => ?_⟩, fun h i j hij => ?_⟩ · exact (((Prod.Lex.lt_iff _ _).1 <| h hij).resolve_left hfij.not_lt).2 · obtain he | hl := (h.1 hij.le).eq_or_lt <;> apply (Prod.Lex.lt_iff _ _).2 exacts [Or.inr ⟨he, h.2 i j hij he⟩, Or.inl hl] /-- The permutation that sorts `f` is the identity if and only if `f` is monotone. -/ theorem sort_eq_refl_iff_monotone : sort f = Equiv.refl _ ↔ Monotone f := by rw [eq_comm, eq_sort_iff, Equiv.coe_refl, Function.comp_id] simp only [id, and_iff_left_iff_imp] exact fun _ _ _ hij _ => hij /-- A permutation of a tuple `f` is `f` sorted if and only if it is monotone. -/ theorem comp_sort_eq_comp_iff_monotone : f ∘ σ = f ∘ sort f ↔ Monotone (f ∘ σ) := ⟨fun h => h.symm ▸ monotone_sort f, fun h => unique_monotone h (monotone_sort f)⟩ /-- The sorted versions of a tuple `f` and of any permutation of `f` agree. -/ theorem comp_perm_comp_sort_eq_comp_sort : (f ∘ σ) ∘ sort (f ∘ σ) = f ∘ sort f := by rw [Function.comp.assoc, ← Equiv.Perm.coe_mul] exact unique_monotone (monotone_sort (f ∘ σ)) (monotone_sort f) /-- If a permutation `f ∘ σ` of the tuple `f` is not the same as `f ∘ sort f`, then `f ∘ σ` has a pair of strictly decreasing entries. -/ theorem antitone_pair_of_not_sorted' (h : f ∘ σ ≠ f ∘ sort f) : ∃ i j, i < j ∧ (f ∘ σ) j < (f ∘ σ) i := by contrapose! h exact comp_sort_eq_comp_iff_monotone.mpr (monotone_iff_forall_lt.mpr h) /-- If the tuple `f` is not the same as `f ∘ sort f`, then `f` has a pair of strictly decreasing entries. -/ theorem antitone_pair_of_not_sorted (h : f ≠ f ∘ sort f) : ∃ i j, i < j ∧ f j < f i := antitone_pair_of_not_sorted' (id h : f ∘ Equiv.refl _ ≠ _) end Tuple
Data\Finite\Basic.lean
/- Copyright (c) 2022 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller -/ import Mathlib.Data.Fintype.Powerset import Mathlib.Data.Fintype.Prod import Mathlib.Data.Fintype.Sigma import Mathlib.Data.Fintype.Sum import Mathlib.Data.Fintype.Vector /-! # Finite types In this file we prove some theorems about `Finite` and provide some instances. This typeclass is a `Prop`-valued counterpart of the typeclass `Fintype`. See more details in the file where `Finite` is defined. ## Main definitions * `Fintype.finite`, `Finite.of_fintype` creates a `Finite` instance from a `Fintype` instance. The former lemma takes `Fintype α` as an explicit argument while the latter takes it as an instance argument. * `Fintype.of_finite` noncomputably creates a `Fintype` instance from a `Finite` instance. ## Implementation notes There is an apparent duplication of many `Fintype` instances in this module, however they follow a pattern: if a `Fintype` instance depends on `Decidable` instances or other `Fintype` instances, then we need to "lower" the instance to be a `Finite` instance by removing the `Decidable` instances and switching the `Fintype` instances to `Finite` instances. These are precisely the ones that cannot be inferred using `Finite.of_fintype`. (However, when using `open scoped Classical` or the `classical` tactic the instances relying only on `Decidable` instances will give `Finite` instances.) In the future we might consider writing automation to create these "lowered" instances. ## Tags finiteness, finite types -/ open Mathlib noncomputable section open scoped Classical variable {α β γ : Type*} namespace Finite -- see Note [lower instance priority] instance (priority := 100) of_subsingleton {α : Sort*} [Subsingleton α] : Finite α := of_injective (Function.const α ()) <| Function.injective_of_subsingleton _ -- Higher priority for `Prop`s -- Porting note(#12096): removed @[nolint instance_priority], linter not ported yet instance prop (p : Prop) : Finite p := Finite.of_subsingleton instance [Finite α] [Finite β] : Finite (α × β) := by haveI := Fintype.ofFinite α haveI := Fintype.ofFinite β infer_instance instance {α β : Sort*} [Finite α] [Finite β] : Finite (PProd α β) := of_equiv _ Equiv.pprodEquivProdPLift.symm theorem prod_left (β) [Finite (α × β)] [Nonempty β] : Finite α := of_surjective (Prod.fst : α × β → α) Prod.fst_surjective theorem prod_right (α) [Finite (α × β)] [Nonempty α] : Finite β := of_surjective (Prod.snd : α × β → β) Prod.snd_surjective instance [Finite α] [Finite β] : Finite (α ⊕ β) := by haveI := Fintype.ofFinite α haveI := Fintype.ofFinite β infer_instance theorem sum_left (β) [Finite (α ⊕ β)] : Finite α := of_injective (Sum.inl : α → α ⊕ β) Sum.inl_injective theorem sum_right (α) [Finite (α ⊕ β)] : Finite β := of_injective (Sum.inr : β → α ⊕ β) Sum.inr_injective instance {β : α → Type*} [Finite α] [∀ a, Finite (β a)] : Finite (Σa, β a) := by letI := Fintype.ofFinite α letI := fun a => Fintype.ofFinite (β a) infer_instance instance {ι : Sort*} {π : ι → Sort*} [Finite ι] [∀ i, Finite (π i)] : Finite (Σ'i, π i) := of_equiv _ (Equiv.psigmaEquivSigmaPLift π).symm instance [Finite α] : Finite (Set α) := by cases nonempty_fintype α infer_instance end Finite instance Pi.finite {α : Sort*} {β : α → Sort*} [Finite α] [∀ a, Finite (β a)] : Finite (∀ a, β a) := by haveI := Fintype.ofFinite (PLift α) haveI := fun a => Fintype.ofFinite (PLift (β a)) exact Finite.of_equiv (∀ a : PLift α, PLift (β (Equiv.plift a))) (Equiv.piCongr Equiv.plift fun _ => Equiv.plift) instance Vector.finite {α : Type*} [Finite α] {n : ℕ} : Finite (Vector α n) := by haveI := Fintype.ofFinite α infer_instance instance Quot.finite {α : Sort*} [Finite α] (r : α → α → Prop) : Finite (Quot r) := Finite.of_surjective _ (surjective_quot_mk r) instance Quotient.finite {α : Sort*} [Finite α] (s : Setoid α) : Finite (Quotient s) := Quot.finite _ instance Function.Embedding.finite {α β : Sort*} [Finite β] : Finite (α ↪ β) := by cases' isEmpty_or_nonempty (α ↪ β) with _ h · -- Porting note: infer_instance fails because it applies `Finite.of_fintype` and produces a -- "stuck at solving universe constraint" error. apply Finite.of_subsingleton · refine h.elim fun f => ?_ haveI : Finite α := Finite.of_injective _ f.injective exact Finite.of_injective _ DFunLike.coe_injective instance Equiv.finite_right {α β : Sort*} [Finite β] : Finite (α ≃ β) := Finite.of_injective Equiv.toEmbedding fun e₁ e₂ h => Equiv.ext <| by convert DFunLike.congr_fun h using 0 instance Equiv.finite_left {α β : Sort*} [Finite α] : Finite (α ≃ β) := Finite.of_equiv _ ⟨Equiv.symm, Equiv.symm, Equiv.symm_symm, Equiv.symm_symm⟩ instance [Finite α] {n : ℕ} : Finite (Sym α n) := by haveI := Fintype.ofFinite α infer_instance
Data\Finite\Card.lean
/- Copyright (c) 2022 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller -/ import Mathlib.SetTheory.Cardinal.Finite /-! # Cardinality of finite types The cardinality of a finite type `α` is given by `Nat.card α`. This function has the "junk value" of `0` for infinite types, but to ensure the function has valid output, one just needs to know that it's possible to produce a `Finite` instance for the type. (Note: we could have defined a `Finite.card` that required you to supply a `Finite` instance, but (a) the function would be `noncomputable` anyway so there is no need to supply the instance and (b) the function would have a more complicated dependent type that easily leads to "motive not type correct" errors.) ## Implementation notes Theorems about `Nat.card` are sometimes incidentally true for both finite and infinite types. If removing a finiteness constraint results in no loss in legibility, we remove it. We generally put such theorems into the `SetTheory.Cardinal.Finite` module. -/ noncomputable section open scoped Classical variable {α β γ : Type*} /-- There is (noncomputably) an equivalence between a finite type `α` and `Fin (Nat.card α)`. -/ def Finite.equivFin (α : Type*) [Finite α] : α ≃ Fin (Nat.card α) := by have := (Finite.exists_equiv_fin α).choose_spec.some rwa [Nat.card_eq_of_equiv_fin this] /-- Similar to `Finite.equivFin` but with control over the term used for the cardinality. -/ def Finite.equivFinOfCardEq [Finite α] {n : ℕ} (h : Nat.card α = n) : α ≃ Fin n := by subst h apply Finite.equivFin theorem Nat.card_eq (α : Type*) : Nat.card α = if h : Finite α then @Fintype.card α (Fintype.ofFinite α) else 0 := by cases finite_or_infinite α · letI := Fintype.ofFinite α simp only [*, Nat.card_eq_fintype_card, dif_pos] · simp only [*, card_eq_zero_of_infinite, not_finite_iff_infinite.mpr, dite_false] theorem Finite.card_pos_iff [Finite α] : 0 < Nat.card α ↔ Nonempty α := by haveI := Fintype.ofFinite α rw [Nat.card_eq_fintype_card, Fintype.card_pos_iff] theorem Finite.card_pos [Finite α] [h : Nonempty α] : 0 < Nat.card α := Finite.card_pos_iff.mpr h namespace Finite theorem cast_card_eq_mk {α : Type*} [Finite α] : ↑(Nat.card α) = Cardinal.mk α := Cardinal.cast_toNat_of_lt_aleph0 (Cardinal.lt_aleph0_of_finite α) theorem card_eq [Finite α] [Finite β] : Nat.card α = Nat.card β ↔ Nonempty (α ≃ β) := by haveI := Fintype.ofFinite α haveI := Fintype.ofFinite β simp only [Nat.card_eq_fintype_card, Fintype.card_eq] theorem card_le_one_iff_subsingleton [Finite α] : Nat.card α ≤ 1 ↔ Subsingleton α := by haveI := Fintype.ofFinite α simp only [Nat.card_eq_fintype_card, Fintype.card_le_one_iff_subsingleton] theorem one_lt_card_iff_nontrivial [Finite α] : 1 < Nat.card α ↔ Nontrivial α := by haveI := Fintype.ofFinite α simp only [Nat.card_eq_fintype_card, Fintype.one_lt_card_iff_nontrivial] theorem one_lt_card [Finite α] [h : Nontrivial α] : 1 < Nat.card α := one_lt_card_iff_nontrivial.mpr h @[simp] theorem card_option [Finite α] : Nat.card (Option α) = Nat.card α + 1 := by haveI := Fintype.ofFinite α simp only [Nat.card_eq_fintype_card, Fintype.card_option] theorem card_le_of_injective [Finite β] (f : α → β) (hf : Function.Injective f) : Nat.card α ≤ Nat.card β := by haveI := Fintype.ofFinite β haveI := Fintype.ofInjective f hf simpa only [Nat.card_eq_fintype_card] using Fintype.card_le_of_injective f hf theorem card_le_of_embedding [Finite β] (f : α ↪ β) : Nat.card α ≤ Nat.card β := card_le_of_injective _ f.injective theorem card_le_of_surjective [Finite α] (f : α → β) (hf : Function.Surjective f) : Nat.card β ≤ Nat.card α := by haveI := Fintype.ofFinite α haveI := Fintype.ofSurjective f hf simpa only [Nat.card_eq_fintype_card] using Fintype.card_le_of_surjective f hf theorem card_eq_zero_iff [Finite α] : Nat.card α = 0 ↔ IsEmpty α := by haveI := Fintype.ofFinite α simp only [Nat.card_eq_fintype_card, Fintype.card_eq_zero_iff] /-- If `f` is injective, then `Nat.card α ≤ Nat.card β`. We must also assume `Nat.card β = 0 → Nat.card α = 0` since `Nat.card` is defined to be `0` for infinite types. -/ theorem card_le_of_injective' {f : α → β} (hf : Function.Injective f) (h : Nat.card β = 0 → Nat.card α = 0) : Nat.card α ≤ Nat.card β := (or_not_of_imp h).casesOn (fun h => le_of_eq_of_le h zero_le') fun h => @card_le_of_injective α β (Nat.finite_of_card_ne_zero h) f hf /-- If `f` is an embedding, then `Nat.card α ≤ Nat.card β`. We must also assume `Nat.card β = 0 → Nat.card α = 0` since `Nat.card` is defined to be `0` for infinite types. -/ theorem card_le_of_embedding' (f : α ↪ β) (h : Nat.card β = 0 → Nat.card α = 0) : Nat.card α ≤ Nat.card β := card_le_of_injective' f.2 h /-- If `f` is surjective, then `Nat.card β ≤ Nat.card α`. We must also assume `Nat.card α = 0 → Nat.card β = 0` since `Nat.card` is defined to be `0` for infinite types. -/ theorem card_le_of_surjective' {f : α → β} (hf : Function.Surjective f) (h : Nat.card α = 0 → Nat.card β = 0) : Nat.card β ≤ Nat.card α := (or_not_of_imp h).casesOn (fun h => le_of_eq_of_le h zero_le') fun h => @card_le_of_surjective α β (Nat.finite_of_card_ne_zero h) f hf /-- NB: `Nat.card` is defined to be `0` for infinite types. -/ theorem card_eq_zero_of_surjective {f : α → β} (hf : Function.Surjective f) (h : Nat.card β = 0) : Nat.card α = 0 := by cases finite_or_infinite β · haveI := card_eq_zero_iff.mp h haveI := Function.isEmpty f exact Nat.card_of_isEmpty · haveI := Infinite.of_surjective f hf exact Nat.card_eq_zero_of_infinite /-- NB: `Nat.card` is defined to be `0` for infinite types. -/ theorem card_eq_zero_of_injective [Nonempty α] {f : α → β} (hf : Function.Injective f) (h : Nat.card α = 0) : Nat.card β = 0 := card_eq_zero_of_surjective (Function.invFun_surjective hf) h /-- NB: `Nat.card` is defined to be `0` for infinite types. -/ theorem card_eq_zero_of_embedding [Nonempty α] (f : α ↪ β) (h : Nat.card α = 0) : Nat.card β = 0 := card_eq_zero_of_injective f.2 h theorem card_sum [Finite α] [Finite β] : Nat.card (α ⊕ β) = Nat.card α + Nat.card β := by haveI := Fintype.ofFinite α haveI := Fintype.ofFinite β simp only [Nat.card_eq_fintype_card, Fintype.card_sum] theorem card_image_le {s : Set α} [Finite s] (f : α → β) : Nat.card (f '' s) ≤ Nat.card s := card_le_of_surjective _ Set.surjective_onto_image theorem card_range_le [Finite α] (f : α → β) : Nat.card (Set.range f) ≤ Nat.card α := card_le_of_surjective _ Set.surjective_onto_range theorem card_subtype_le [Finite α] (p : α → Prop) : Nat.card { x // p x } ≤ Nat.card α := by haveI := Fintype.ofFinite α simpa only [Nat.card_eq_fintype_card] using Fintype.card_subtype_le p theorem card_subtype_lt [Finite α] {p : α → Prop} {x : α} (hx : ¬p x) : Nat.card { x // p x } < Nat.card α := by haveI := Fintype.ofFinite α simpa only [Nat.card_eq_fintype_card, gt_iff_lt] using Fintype.card_subtype_lt hx end Finite namespace PartENat theorem card_eq_coe_natCard (α : Type*) [Finite α] : card α = Nat.card α := by unfold PartENat.card apply symm rw [Cardinal.natCast_eq_toPartENat_iff] exact Finite.cast_card_eq_mk @[deprecated (since := "2024-05-25")] alias card_eq_coe_nat_card := card_eq_coe_natCard end PartENat namespace Set theorem card_union_le (s t : Set α) : Nat.card (↥(s ∪ t)) ≤ Nat.card s + Nat.card t := by cases' _root_.finite_or_infinite (↥(s ∪ t)) with h h · rw [finite_coe_iff, finite_union, ← finite_coe_iff, ← finite_coe_iff] at h cases h rw [← Cardinal.natCast_le, Nat.cast_add, Finite.cast_card_eq_mk, Finite.cast_card_eq_mk, Finite.cast_card_eq_mk] exact Cardinal.mk_union_le s t · exact Nat.card_eq_zero_of_infinite.trans_le (zero_le _) namespace Finite variable {s t : Set α} theorem card_lt_card (ht : t.Finite) (hsub : s ⊂ t) : Nat.card s < Nat.card t := by have : Fintype t := Finite.fintype ht have : Fintype s := Finite.fintype (subset ht (subset_of_ssubset hsub)) simp only [Nat.card_eq_fintype_card] exact Set.card_lt_card hsub theorem eq_of_subset_of_card_le (ht : t.Finite) (hsub : s ⊆ t) (hcard : Nat.card t ≤ Nat.card s) : s = t := (eq_or_ssubset_of_subset hsub).elim id fun h ↦ absurd hcard <| not_le_of_lt <| ht.card_lt_card h theorem equiv_image_eq_iff_subset (e : α ≃ α) (hs : s.Finite) : e '' s = s ↔ e '' s ⊆ s := ⟨fun h ↦ by rw [h], fun h ↦ hs.eq_of_subset_of_card_le h <| ge_of_eq (Nat.card_congr (e.image s).symm)⟩ end Finite end Set
Data\Finite\Defs.lean
/- Copyright (c) 2022 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller -/ import Mathlib.Logic.Equiv.Defs /-! # Definition of the `Finite` typeclass This file defines a typeclass `Finite` saying that `α : Sort*` is finite. A type is `Finite` if it is equivalent to `Fin n` for some `n`. We also define `Infinite α` as a typeclass equivalent to `¬Finite α`. The `Finite` predicate has no computational relevance and, being `Prop`-valued, gets to enjoy proof irrelevance -- it represents the mere fact that the type is finite. While the `Finite` class also represents finiteness of a type, a key difference is that a `Fintype` instance represents finiteness in a computable way: it gives a concrete algorithm to produce a `Finset` whose elements enumerate the terms of the given type. As such, one generally relies on congruence lemmas when rewriting expressions involving `Fintype` instances. Every `Fintype` instance automatically gives a `Finite` instance, see `Fintype.finite`, but not vice versa. Every `Fintype` instance should be computable since they are meant for computation. If it's not possible to write a computable `Fintype` instance, one should prefer writing a `Finite` instance instead. ## Main definitions * `Finite α` denotes that `α` is a finite type. * `Infinite α` denotes that `α` is an infinite type. ## Implementation notes The definition of `Finite α` is not just `Nonempty (Fintype α)` since `Fintype` requires that `α : Type*`, and the definition in this module allows for `α : Sort*`. This means we can write the instance `Finite.prop`. ## Tags finite, fintype -/ universe u v open Function variable {α β : Sort*} /-- A type is `Finite` if it is in bijective correspondence to some `Fin n`. This is similar to `Fintype`, but `Finite` is a proposition rather than data. A particular benefit to this is that `Finite` instances are definitionally equal to one another (due to proof irrelevance) rather than being merely propositionally equal, and, furthermore, `Finite` instances generally avoid the need for `Decidable` instances. One other notable difference is that `Finite` allows there to be `Finite p` instances for all `p : Prop`, which is not allowed by `Fintype` due to universe constraints. An application of this is that `Finite (x ∈ s → β x)` follows from the general instance for pi types, assuming `[∀ x, Finite (β x)]`. Implementation note: this is a reason `Finite α` is not defined as `Nonempty (Fintype α)`. Every `Fintype` instance provides a `Finite` instance via `Finite.of_fintype`. Conversely, one can noncomputably create a `Fintype` instance from a `Finite` instance via `Fintype.ofFinite`. In a proof one might write ```lean have := Fintype.ofFinite α ``` to obtain such an instance. Do not write noncomputable `Fintype` instances; instead write `Finite` instances and use this `Fintype.ofFinite` interface. The `Fintype` instances should be relied upon to be computable for evaluation purposes. Theorems should use `Finite` instead of `Fintype`, unless definitions in the theorem statement require `Fintype`. Definitions should prefer `Finite` as well, unless it is important that the definitions are meant to be computable in the reduction or `#eval` sense. -/ class inductive Finite (α : Sort*) : Prop | intro {n : ℕ} : α ≃ Fin n → Finite _ theorem finite_iff_exists_equiv_fin {α : Sort*} : Finite α ↔ ∃ n, Nonempty (α ≃ Fin n) := ⟨fun ⟨e⟩ => ⟨_, ⟨e⟩⟩, fun ⟨_, ⟨e⟩⟩ => ⟨e⟩⟩ theorem Finite.exists_equiv_fin (α : Sort*) [h : Finite α] : ∃ n : ℕ, Nonempty (α ≃ Fin n) := finite_iff_exists_equiv_fin.mp h theorem Finite.of_equiv (α : Sort*) [h : Finite α] (f : α ≃ β) : Finite β := let ⟨e⟩ := h; ⟨f.symm.trans e⟩ theorem Equiv.finite_iff (f : α ≃ β) : Finite α ↔ Finite β := ⟨fun _ => Finite.of_equiv _ f, fun _ => Finite.of_equiv _ f.symm⟩ theorem Function.Bijective.finite_iff {f : α → β} (h : Bijective f) : Finite α ↔ Finite β := (Equiv.ofBijective f h).finite_iff theorem Finite.ofBijective [Finite α] {f : α → β} (h : Bijective f) : Finite β := h.finite_iff.mp ‹_› instance [Finite α] : Finite (PLift α) := Finite.of_equiv α Equiv.plift.symm instance {α : Type v} [Finite α] : Finite (ULift.{u} α) := Finite.of_equiv α Equiv.ulift.symm /-- A type is said to be infinite if it is not finite. Note that `Infinite α` is equivalent to `IsEmpty (Fintype α)` or `IsEmpty (Finite α)`. -/ class Infinite (α : Sort*) : Prop where /-- assertion that `α` is `¬Finite`-/ not_finite : ¬Finite α @[simp] theorem not_finite_iff_infinite : ¬Finite α ↔ Infinite α := ⟨Infinite.mk, fun h => h.1⟩ @[simp] theorem not_infinite_iff_finite : ¬Infinite α ↔ Finite α := not_finite_iff_infinite.not_right.symm theorem Equiv.infinite_iff (e : α ≃ β) : Infinite α ↔ Infinite β := not_finite_iff_infinite.symm.trans <| e.finite_iff.not.trans not_finite_iff_infinite instance [Infinite α] : Infinite (PLift α) := Equiv.plift.infinite_iff.2 ‹_› instance {α : Type v} [Infinite α] : Infinite (ULift.{u} α) := Equiv.ulift.infinite_iff.2 ‹_› theorem finite_or_infinite (α : Sort*) : Finite α ∨ Infinite α := or_iff_not_imp_left.2 not_finite_iff_infinite.1 /-- `Infinite α` is not `Finite`-/ theorem not_finite (α : Sort*) [Infinite α] [Finite α] : False := @Infinite.not_finite α ‹_› ‹_› protected theorem Finite.false [Infinite α] (_ : Finite α) : False := not_finite α protected theorem Infinite.false [Finite α] (_ : Infinite α) : False := @Infinite.not_finite α ‹_› ‹_› alias ⟨Finite.of_not_infinite, Finite.not_infinite⟩ := not_infinite_iff_finite
Data\Finite\Set.lean
/- Copyright (c) 2022 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller -/ import Mathlib.Data.Fintype.Card /-! # Lemmas about `Finite` and `Set`s In this file we prove two lemmas about `Finite` and `Set`s. ## Tags finiteness, finite sets -/ open Set universe u v w variable {α : Type u} {β : Type v} {ι : Sort w} theorem Finite.Set.finite_of_finite_image (s : Set α) {f : α → β} (h : s.InjOn f) [Finite (f '' s)] : Finite s := Finite.of_equiv _ (Equiv.ofBijective _ h.bijOn_image.bijective).symm theorem Finite.of_injective_finite_range {f : ι → α} (hf : Function.Injective f) [Finite (range f)] : Finite ι := Finite.of_injective (Set.rangeFactorization f) (hf.codRestrict _)
Data\Finset\Attr.lean
/- Copyright (c) 2024 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import Aesop import Qq /-! # Aesop rule set for finsets This file defines `finsetNonempty`, an aesop rule set to prove that a given finset is nonempty. -/ -- `finsetNonempty` rules try to prove that a given finset is nonempty, -- for use in positivity extensions. declare_aesop_rule_sets [finsetNonempty] (default := true) open Qq Lean Meta
Data\Finset\Basic.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, Jeremy Avigad, Minchao Wu, Mario Carneiro -/ import Mathlib.Data.Finset.Attr import Mathlib.Data.Multiset.FinsetOps import Mathlib.Logic.Equiv.Set import Mathlib.Order.Directed import Mathlib.Order.Interval.Set.Basic /-! # Finite sets Terms of type `Finset α` are one way of talking about finite subsets of `α` in mathlib. Below, `Finset α` is defined as a structure with 2 fields: 1. `val` is a `Multiset α` of elements; 2. `nodup` is a proof that `val` has no duplicates. Finsets in Lean are constructive in that they have an underlying `List` that enumerates their elements. In particular, any function that uses the data of the underlying list cannot depend on its ordering. This is handled on the `Multiset` level by multiset API, so in most cases one needn't worry about it explicitly. Finsets give a basic foundation for defining finite sums and products over types: 1. `∑ i ∈ (s : Finset α), f i`; 2. `∏ i ∈ (s : Finset α), f i`. Lean refers to these operations as big operators. More information can be found in `Mathlib/Algebra/BigOperators/Group/Finset.lean`. Finsets are directly used to define fintypes in Lean. A `Fintype α` instance for a type `α` consists of a universal `Finset α` containing every term of `α`, called `univ`. See `Mathlib/Data/Fintype/Basic.lean`. There is also `univ'`, the noncomputable partner to `univ`, which is defined to be `α` as a finset if `α` is finite, and the empty finset otherwise. See `Mathlib/Data/Fintype/Basic.lean`. `Finset.card`, the size of a finset is defined in `Mathlib/Data/Finset/Card.lean`. This is then used to define `Fintype.card`, the size of a type. ## Main declarations ### Main definitions * `Finset`: Defines a type for the finite subsets of `α`. Constructing a `Finset` requires two pieces of data: `val`, a `Multiset α` of elements, and `nodup`, a proof that `val` has no duplicates. * `Finset.instMembershipFinset`: Defines membership `a ∈ (s : Finset α)`. * `Finset.instCoeTCFinsetSet`: Provides a coercion `s : Finset α` to `s : Set α`. * `Finset.instCoeSortFinsetType`: Coerce `s : Finset α` to the type of all `x ∈ s`. * `Finset.induction_on`: Induction on finsets. 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. * `Finset.choose`: Given a proof `h` of existence and uniqueness of a certain element satisfying a predicate, `choose s h` returns the element of `s` satisfying that predicate. ### Finset constructions * `Finset.instSingletonFinset`: Denoted by `{a}`; the finset consisting of one element. * `Finset.empty`: Denoted by `∅`. The finset associated to any type consisting of no elements. * `Finset.range`: For any `n : ℕ`, `range n` is equal to `{0, 1, ... , n - 1} ⊆ ℕ`. This convention is consistent with other languages and normalizes `card (range n) = n`. Beware, `n` is not in `range n`. * `Finset.attach`: Given `s : Finset α`, `attach s` forms a finset of elements of the subtype `{a // a ∈ s}`; in other words, it attaches elements to a proof of membership in the set. ### Finsets from functions * `Finset.filter`: Given a decidable predicate `p : α → Prop`, `s.filter p` is the finset consisting of those elements in `s` satisfying the predicate `p`. ### The lattice structure on subsets of finsets There is a natural lattice structure on the subsets of a set. In Lean, we use lattice notation to talk about things involving unions and intersections. See `Mathlib/Order/Lattice.lean`. For the lattice structure on finsets, `⊥` is called `bot` with `⊥ = ∅` and `⊤` is called `top` with `⊤ = univ`. * `Finset.instHasSubsetFinset`: Lots of API about lattices, otherwise behaves as one would expect. * `Finset.instUnionFinset`: Defines `s ∪ t` (or `s ⊔ t`) as the union of `s` and `t`. See `Finset.sup`/`Finset.biUnion` for finite unions. * `Finset.instInterFinset`: Defines `s ∩ t` (or `s ⊓ t`) as the intersection of `s` and `t`. See `Finset.inf` for finite intersections. ### Operations on two or more finsets * `insert` and `Finset.cons`: For any `a : α`, `insert s a` returns `s ∪ {a}`. `cons s a h` returns the same except that it requires a hypothesis stating that `a` is not already in `s`. This does not require decidable equality on the type `α`. * `Finset.instUnionFinset`: see "The lattice structure on subsets of finsets" * `Finset.instInterFinset`: see "The lattice structure on subsets of finsets" * `Finset.erase`: For any `a : α`, `erase s a` returns `s` with the element `a` removed. * `Finset.instSDiffFinset`: Defines the set difference `s \ t` for finsets `s` and `t`. * `Finset.product`: Given finsets of `α` and `β`, defines finsets of `α × β`. For arbitrary dependent products, see `Mathlib/Data/Finset/Pi.lean`. ### Predicates on finsets * `Disjoint`: defined via the lattice structure on finsets; two sets are disjoint if their intersection is empty. * `Finset.Nonempty`: A finset is nonempty if it has elements. This is equivalent to saying `s ≠ ∅`. ### Equivalences between finsets * The `Mathlib/Data/Equiv.lean` files describe a general type of equivalence, so look in there for any lemmas. There is some API for rewriting sums and products from `s` to `t` given that `s ≃ t`. TODO: examples ## Tags finite sets, finset -/ -- Assert that we define `Finset` without the material on `List.sublists`. -- Note that we cannot use `List.sublists` itself as that is defined very early. assert_not_exists List.sublistsLen assert_not_exists Multiset.Powerset assert_not_exists CompleteLattice open Multiset Subtype Nat Function universe u variable {α : 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*) where /-- The underlying multiset -/ val : Multiset α /-- `val` contains no duplicates -/ nodup : Nodup val instance Multiset.canLiftFinset {α} : CanLift (Multiset α) (Finset α) Finset.val Multiset.Nodup := ⟨fun m hm => ⟨⟨m, hm⟩, rfl⟩⟩ namespace Finset theorem eq_of_veq : ∀ {s t : Finset α}, s.1 = t.1 → s = t | ⟨s, _⟩, ⟨t, _⟩, h => by cases h; rfl theorem val_injective : Injective (val : Finset α → Multiset α) := fun _ _ => eq_of_veq @[simp] theorem val_inj {s t : Finset α} : s.1 = t.1 ↔ s = t := val_injective.eq_iff @[simp] theorem dedup_eq_self [DecidableEq α] (s : Finset α) : dedup s.1 = s.1 := s.2.dedup instance decidableEq [DecidableEq α] : DecidableEq (Finset α) | _, _ => decidable_of_iff _ val_inj /-! ### membership -/ instance : Membership α (Finset α) := ⟨fun a s => a ∈ s.1⟩ theorem mem_def {a : α} {s : Finset α} : a ∈ s ↔ a ∈ s.1 := Iff.rfl @[simp] theorem mem_val {a : α} {s : Finset α} : a ∈ s.1 ↔ a ∈ s := Iff.rfl @[simp] theorem mem_mk {a : α} {s nd} : a ∈ @Finset.mk α s nd ↔ a ∈ s := Iff.rfl instance decidableMem [_h : DecidableEq α] (a : α) (s : Finset α) : Decidable (a ∈ s) := Multiset.decidableMem _ _ @[simp] lemma forall_mem_not_eq {s : Finset α} {a : α} : (∀ b ∈ s, ¬ a = b) ↔ a ∉ s := by aesop @[simp] lemma forall_mem_not_eq' {s : Finset α} {a : α} : (∀ b ∈ s, ¬ b = a) ↔ a ∉ s := by aesop /-! ### set coercion -/ -- Porting note (#11445): new definition /-- Convert a finset to a set in the natural way. -/ @[coe] def toSet (s : Finset α) : Set α := { a | a ∈ s } /-- Convert a finset to a set in the natural way. -/ instance : CoeTC (Finset α) (Set α) := ⟨toSet⟩ @[simp, norm_cast] theorem mem_coe {a : α} {s : Finset α} : a ∈ (s : Set α) ↔ a ∈ (s : Finset α) := Iff.rfl @[simp] theorem setOf_mem {α} {s : Finset α} : { a | a ∈ s } = s := rfl @[simp] theorem coe_mem {s : Finset α} (x : (s : Set α)) : ↑x ∈ s := x.2 -- Porting note (#10618): @[simp] can prove this theorem mk_coe {s : Finset α} (x : (s : Set α)) {h} : (⟨x, h⟩ : (s : Set α)) = x := Subtype.coe_eta _ _ instance decidableMem' [DecidableEq α] (a : α) (s : Finset α) : Decidable (a ∈ (s : Set α)) := s.decidableMem _ /-! ### extensionality -/ theorem ext_iff {s₁ s₂ : Finset α} : s₁ = s₂ ↔ ∀ a, a ∈ s₁ ↔ a ∈ s₂ := val_inj.symm.trans <| s₁.nodup.ext s₂.nodup @[ext] theorem ext {s₁ s₂ : Finset α} : (∀ a, a ∈ s₁ ↔ a ∈ s₂) → s₁ = s₂ := ext_iff.2 @[simp, norm_cast] theorem coe_inj {s₁ s₂ : Finset α} : (s₁ : Set α) = s₂ ↔ s₁ = s₂ := Set.ext_iff.trans ext_iff.symm theorem coe_injective {α} : Injective ((↑) : Finset α → Set α) := fun _s _t => coe_inj.1 /-! ### type coercion -/ /-- Coercion from a finset to the corresponding subtype. -/ instance {α : Type u} : CoeSort (Finset α) (Type u) := ⟨fun s => { x // x ∈ s }⟩ -- Porting note (#10618): @[simp] can prove this protected theorem forall_coe {α : Type*} (s : Finset α) (p : s → Prop) : (∀ x : s, p x) ↔ ∀ (x : α) (h : x ∈ s), p ⟨x, h⟩ := Subtype.forall -- Porting note (#10618): @[simp] can prove this protected theorem exists_coe {α : Type*} (s : Finset α) (p : s → Prop) : (∃ x : s, p x) ↔ ∃ (x : α) (h : x ∈ s), p ⟨x, h⟩ := Subtype.exists instance PiFinsetCoe.canLift (ι : Type*) (α : ι → Type*) [_ne : ∀ i, Nonempty (α i)] (s : Finset ι) : CanLift (∀ i : s, α i) (∀ i, α i) (fun f i => f i) fun _ => True := PiSubtype.canLift ι α (· ∈ s) instance PiFinsetCoe.canLift' (ι α : Type*) [_ne : Nonempty α] (s : Finset ι) : CanLift (s → α) (ι → α) (fun f i => f i) fun _ => True := PiFinsetCoe.canLift ι (fun _ => α) s instance FinsetCoe.canLift (s : Finset α) : CanLift α s (↑) fun a => a ∈ s where prf a ha := ⟨⟨a, ha⟩, rfl⟩ @[simp, norm_cast] theorem coe_sort_coe (s : Finset α) : ((s : Set α) : Sort _) = s := rfl /-! ### Subset and strict subset relations -/ section Subset variable {s t : Finset α} instance : HasSubset (Finset α) := ⟨fun s t => ∀ ⦃a⦄, a ∈ s → a ∈ t⟩ instance : HasSSubset (Finset α) := ⟨fun s t => s ⊆ t ∧ ¬t ⊆ s⟩ instance partialOrder : PartialOrder (Finset α) where le := (· ⊆ ·) lt := (· ⊂ ·) le_refl s a := id le_trans s t u hst htu a ha := htu <| hst ha le_antisymm s t hst hts := ext fun a => ⟨@hst _, @hts _⟩ instance : IsRefl (Finset α) (· ⊆ ·) := show IsRefl (Finset α) (· ≤ ·) by infer_instance instance : IsTrans (Finset α) (· ⊆ ·) := show IsTrans (Finset α) (· ≤ ·) by infer_instance instance : IsAntisymm (Finset α) (· ⊆ ·) := show IsAntisymm (Finset α) (· ≤ ·) by infer_instance instance : IsIrrefl (Finset α) (· ⊂ ·) := show IsIrrefl (Finset α) (· < ·) by infer_instance instance : IsTrans (Finset α) (· ⊂ ·) := show IsTrans (Finset α) (· < ·) by infer_instance instance : IsAsymm (Finset α) (· ⊂ ·) := show IsAsymm (Finset α) (· < ·) by infer_instance instance : IsNonstrictStrictOrder (Finset α) (· ⊆ ·) (· ⊂ ·) := ⟨fun _ _ => Iff.rfl⟩ theorem subset_def : s ⊆ t ↔ s.1 ⊆ t.1 := Iff.rfl theorem ssubset_def : s ⊂ t ↔ s ⊆ t ∧ ¬t ⊆ s := Iff.rfl theorem Subset.refl (s : Finset α) : s ⊆ s := Multiset.Subset.refl _ protected theorem Subset.rfl {s : Finset α} : s ⊆ s := Subset.refl _ protected theorem subset_of_eq {s t : Finset α} (h : s = t) : s ⊆ t := h ▸ Subset.refl _ theorem Subset.trans {s₁ s₂ s₃ : Finset α} : s₁ ⊆ s₂ → s₂ ⊆ s₃ → s₁ ⊆ s₃ := Multiset.Subset.trans theorem Superset.trans {s₁ s₂ s₃ : Finset α} : s₁ ⊇ s₂ → s₂ ⊇ s₃ → s₁ ⊇ s₃ := fun h' h => Subset.trans h h' theorem mem_of_subset {s₁ s₂ : Finset α} {a : α} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ := Multiset.mem_of_subset theorem not_mem_mono {s t : Finset α} (h : s ⊆ t) {a : α} : a ∉ t → a ∉ s := mt <| @h _ theorem Subset.antisymm {s₁ s₂ : Finset α} (H₁ : s₁ ⊆ s₂) (H₂ : s₂ ⊆ s₁) : s₁ = s₂ := ext fun a => ⟨@H₁ a, @H₂ a⟩ theorem subset_iff {s₁ s₂ : Finset α} : s₁ ⊆ s₂ ↔ ∀ ⦃x⦄, x ∈ s₁ → x ∈ s₂ := Iff.rfl @[simp, norm_cast] theorem coe_subset {s₁ s₂ : Finset α} : (s₁ : Set α) ⊆ s₂ ↔ s₁ ⊆ s₂ := Iff.rfl @[gcongr] protected alias ⟨_, GCongr.coe_subset_coe⟩ := coe_subset @[simp] theorem val_le_iff {s₁ s₂ : Finset α} : s₁.1 ≤ s₂.1 ↔ s₁ ⊆ s₂ := le_iff_subset s₁.2 theorem Subset.antisymm_iff {s₁ s₂ : Finset α} : s₁ = s₂ ↔ s₁ ⊆ s₂ ∧ s₂ ⊆ s₁ := le_antisymm_iff theorem not_subset : ¬s ⊆ t ↔ ∃ x ∈ s, x ∉ t := by simp only [← coe_subset, Set.not_subset, mem_coe] @[simp] theorem le_eq_subset : ((· ≤ ·) : Finset α → Finset α → Prop) = (· ⊆ ·) := rfl @[simp] theorem lt_eq_subset : ((· < ·) : Finset α → Finset α → Prop) = (· ⊂ ·) := rfl theorem le_iff_subset {s₁ s₂ : Finset α} : s₁ ≤ s₂ ↔ s₁ ⊆ s₂ := Iff.rfl theorem lt_iff_ssubset {s₁ s₂ : Finset α} : s₁ < s₂ ↔ s₁ ⊂ s₂ := Iff.rfl @[simp, norm_cast] theorem 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 lemma val_strictMono : StrictMono (val : Finset α → Multiset α) := fun _ _ ↦ val_lt_iff.2 theorem ssubset_iff_subset_ne {s t : Finset α} : s ⊂ t ↔ s ⊆ t ∧ s ≠ t := @lt_iff_le_and_ne _ _ s t theorem ssubset_iff_of_subset {s₁ s₂ : Finset α} (h : s₁ ⊆ s₂) : s₁ ⊂ s₂ ↔ ∃ x ∈ s₂, x ∉ s₁ := Set.ssubset_iff_of_subset h theorem ssubset_of_ssubset_of_subset {s₁ s₂ s₃ : Finset α} (hs₁s₂ : s₁ ⊂ s₂) (hs₂s₃ : s₂ ⊆ s₃) : s₁ ⊂ s₃ := Set.ssubset_of_ssubset_of_subset hs₁s₂ hs₂s₃ theorem ssubset_of_subset_of_ssubset {s₁ s₂ s₃ : Finset α} (hs₁s₂ : s₁ ⊆ s₂) (hs₂s₃ : s₂ ⊂ s₃) : s₁ ⊂ s₃ := Set.ssubset_of_subset_of_ssubset hs₁s₂ hs₂s₃ theorem exists_of_ssubset {s₁ s₂ : Finset α} (h : s₁ ⊂ s₂) : ∃ x ∈ s₂, x ∉ s₁ := Set.exists_of_ssubset h instance isWellFounded_ssubset : IsWellFounded (Finset α) (· ⊂ ·) := Subrelation.isWellFounded (InvImage _ _) val_lt_iff.2 instance wellFoundedLT : WellFoundedLT (Finset α) := Finset.isWellFounded_ssubset end Subset -- TODO: these should be global attributes, but this will require fixing other files attribute [local trans] Subset.trans Superset.trans /-! ### Order embedding from `Finset α` to `Set α` -/ /-- Coercion to `Set α` as an `OrderEmbedding`. -/ def coeEmb : Finset α ↪o Set α := ⟨⟨(↑), coe_injective⟩, coe_subset⟩ @[simp] theorem coe_coeEmb : ⇑(coeEmb : Finset α ↪o Set α) = ((↑) : Finset α → Set α) := rfl /-! ### 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 -- Porting note: Much longer than in Lean3 instance decidableNonempty {s : Finset α} : Decidable s.Nonempty := Quotient.recOnSubsingleton (motive := fun s : Multiset α => Decidable (∃ a, a ∈ s)) s.1 (fun l : List α => match l with | [] => isFalse <| by simp | a::l => isTrue ⟨a, by simp⟩) @[simp, norm_cast] theorem coe_nonempty {s : Finset α} : (s : Set α).Nonempty ↔ s.Nonempty := Iff.rfl -- Porting note: Left-hand side simplifies @[simp] theorem nonempty_coe_sort {s : Finset α} : Nonempty (s : Type _) ↔ s.Nonempty := nonempty_subtype alias ⟨_, Nonempty.to_set⟩ := coe_nonempty alias ⟨_, Nonempty.coe_sort⟩ := nonempty_coe_sort theorem Nonempty.exists_mem {s : Finset α} (h : s.Nonempty) : ∃ x : α, x ∈ s := h @[deprecated (since := "2024-03-23")] alias Nonempty.bex := Nonempty.exists_mem theorem Nonempty.mono {s t : Finset α} (hst : s ⊆ t) (hs : s.Nonempty) : t.Nonempty := Set.Nonempty.mono hst hs theorem Nonempty.forall_const {s : Finset α} (h : s.Nonempty) {p : Prop} : (∀ x ∈ s, p) ↔ p := let ⟨x, hx⟩ := h ⟨fun h => h x hx, fun h _ _ => h⟩ theorem Nonempty.to_subtype {s : Finset α} : s.Nonempty → Nonempty s := nonempty_coe_sort.2 theorem Nonempty.to_type {s : Finset α} : s.Nonempty → Nonempty α := fun ⟨x, _hx⟩ => ⟨x⟩ /-! ### empty -/ section Empty variable {s : Finset α} /-- The empty finset -/ protected def empty : Finset α := ⟨0, nodup_zero⟩ instance : EmptyCollection (Finset α) := ⟨Finset.empty⟩ instance inhabitedFinset : Inhabited (Finset α) := ⟨∅⟩ @[simp] theorem empty_val : (∅ : Finset α).1 = 0 := rfl @[simp] theorem not_mem_empty (a : α) : a ∉ (∅ : Finset α) := by -- Porting note: was `id`. `a ∈ List.nil` is no longer definitionally equal to `False` simp only [mem_def, empty_val, not_mem_zero, not_false_iff] @[simp] theorem not_nonempty_empty : ¬(∅ : Finset α).Nonempty := fun ⟨x, hx⟩ => not_mem_empty x hx @[simp] theorem mk_zero : (⟨0, nodup_zero⟩ : Finset α) = ∅ := rfl theorem ne_empty_of_mem {a : α} {s : Finset α} (h : a ∈ s) : s ≠ ∅ := fun e => not_mem_empty a <| e ▸ h theorem Nonempty.ne_empty {s : Finset α} (h : s.Nonempty) : s ≠ ∅ := (Exists.elim h) fun _a => ne_empty_of_mem @[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) theorem eq_empty_iff_forall_not_mem {s : Finset α} : s = ∅ ↔ ∀ x, x ∉ s := -- Porting note: used `id` ⟨by rintro rfl x; apply not_mem_empty, fun 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 @[simp] theorem not_ssubset_empty (s : Finset α) : ¬s ⊂ ∅ := fun h => let ⟨_, he, _⟩ := exists_of_ssubset h -- Porting note: was `he` not_mem_empty _ he 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 ≠ ∅ := ⟨Nonempty.ne_empty, nonempty_of_ne_empty⟩ @[simp] theorem not_nonempty_iff_eq_empty {s : Finset α} : ¬s.Nonempty ↔ s = ∅ := nonempty_iff_ne_empty.not.trans not_not theorem eq_empty_or_nonempty (s : Finset α) : s = ∅ ∨ s.Nonempty := by_cases Or.inl fun h => Or.inr (nonempty_of_ne_empty h) @[simp, norm_cast] theorem coe_empty : ((∅ : Finset α) : Set α) = ∅ := Set.ext <| by simp @[simp, norm_cast] theorem coe_eq_empty {s : Finset α} : (s : Set α) = ∅ ↔ s = ∅ := by rw [← coe_empty, coe_inj] -- Porting note: Left-hand side simplifies @[simp] theorem isEmpty_coe_sort {s : Finset α} : IsEmpty (s : Type _) ↔ s = ∅ := by simpa using @Set.isEmpty_coe_sort α s instance instIsEmpty : IsEmpty (∅ : Finset α) := isEmpty_coe_sort.2 rfl /-- A `Finset` for an empty type is empty. -/ theorem eq_empty_of_isEmpty [IsEmpty α] (s : Finset α) : s = ∅ := Finset.eq_empty_of_forall_not_mem isEmptyElim instance : OrderBot (Finset α) where bot := ∅ bot_le := empty_subset @[simp] theorem bot_eq_empty : (⊥ : Finset α) = ∅ := rfl @[simp] theorem empty_ssubset : ∅ ⊂ s ↔ s.Nonempty := (@bot_lt_iff_ne_bot (Finset α) _ _ _).trans nonempty_iff_ne_empty.symm alias ⟨_, Nonempty.empty_ssubset⟩ := empty_ssubset end Empty /-! ### singleton -/ section Singleton variable {s : Finset α} {a b : α} /-- `{a} : Finset a` is the set `{a}` containing `a` and nothing else. This differs from `insert a ∅` in that it does not require a `DecidableEq` instance for `α`. -/ instance : Singleton α (Finset α) := ⟨fun a => ⟨{a}, nodup_singleton a⟩⟩ @[simp] theorem singleton_val (a : α) : ({a} : Finset α).1 = {a} := rfl @[simp] theorem mem_singleton {a b : α} : b ∈ ({a} : Finset α) ↔ b = a := Multiset.mem_singleton theorem eq_of_mem_singleton {x y : α} (h : x ∈ ({y} : Finset α)) : x = y := mem_singleton.1 h theorem not_mem_singleton {a b : α} : a ∉ ({b} : Finset α) ↔ a ≠ b := not_congr mem_singleton theorem mem_singleton_self (a : α) : a ∈ ({a} : Finset α) := -- Porting note: was `Or.inl rfl` mem_singleton.mpr rfl @[simp] theorem val_eq_singleton_iff {a : α} {s : Finset α} : s.val = {a} ↔ s = {a} := by rw [← val_inj] rfl theorem singleton_injective : Injective (singleton : α → Finset α) := fun _a _b h => mem_singleton.1 (h ▸ mem_singleton_self _) @[simp] theorem singleton_inj : ({a} : Finset α) = {b} ↔ a = b := singleton_injective.eq_iff @[simp, aesop safe apply (rule_sets := [finsetNonempty])] theorem singleton_nonempty (a : α) : ({a} : Finset α).Nonempty := ⟨a, mem_singleton_self a⟩ @[simp] theorem singleton_ne_empty (a : α) : ({a} : Finset α) ≠ ∅ := (singleton_nonempty a).ne_empty theorem empty_ssubset_singleton : (∅ : Finset α) ⊂ {a} := (singleton_nonempty _).empty_ssubset @[simp, norm_cast] theorem coe_singleton (a : α) : (({a} : Finset α) : Set α) = {a} := by ext simp @[simp, norm_cast] theorem coe_eq_singleton {s : Finset α} {a : α} : (s : Set α) = {a} ↔ s = {a} := by rw [← coe_singleton, coe_inj] @[norm_cast] lemma coe_subset_singleton : (s : Set α) ⊆ {a} ↔ s ⊆ {a} := by rw [← coe_subset, coe_singleton] @[norm_cast] lemma singleton_subset_coe : {a} ⊆ (s : Set α) ↔ {a} ⊆ s := by rw [← coe_subset, coe_singleton] theorem eq_singleton_iff_unique_mem {s : Finset α} {a : α} : s = {a} ↔ a ∈ s ∧ ∀ x ∈ s, x = a := by constructor <;> intro t · rw [t] exact ⟨Finset.mem_singleton_self _, fun _ => Finset.mem_singleton.1⟩ · ext rw [Finset.mem_singleton] exact ⟨t.right _, fun r => r.symm ▸ t.left⟩ theorem eq_singleton_iff_nonempty_unique_mem {s : Finset α} {a : α} : s = {a} ↔ s.Nonempty ∧ ∀ x ∈ s, x = a := by constructor · rintro rfl simp · rintro ⟨hne, h_uniq⟩ rw [eq_singleton_iff_unique_mem] refine ⟨?_, h_uniq⟩ rw [← h_uniq hne.choose hne.choose_spec] exact hne.choose_spec theorem nonempty_iff_eq_singleton_default [Unique α] {s : Finset α} : s.Nonempty ↔ s = {default} := by simp [eq_singleton_iff_nonempty_unique_mem, eq_iff_true_of_subsingleton] alias ⟨Nonempty.eq_singleton_default, _⟩ := nonempty_iff_eq_singleton_default theorem singleton_iff_unique_mem (s : Finset α) : (∃ a, s = {a}) ↔ ∃! a, a ∈ s := by simp only [eq_singleton_iff_unique_mem, ExistsUnique] theorem singleton_subset_set_iff {s : Set α} {a : α} : ↑({a} : Finset α) ⊆ s ↔ a ∈ s := by rw [coe_singleton, Set.singleton_subset_iff] @[simp] theorem singleton_subset_iff {s : Finset α} {a : α} : {a} ⊆ s ↔ a ∈ s := singleton_subset_set_iff @[simp] theorem subset_singleton_iff {s : Finset α} {a : α} : s ⊆ {a} ↔ s = ∅ ∨ s = {a} := by rw [← coe_subset, coe_singleton, Set.subset_singleton_iff_eq, coe_eq_empty, coe_eq_singleton] theorem singleton_subset_singleton : ({a} : Finset α) ⊆ {b} ↔ a = b := by simp protected theorem Nonempty.subset_singleton_iff {s : Finset α} {a : α} (h : s.Nonempty) : s ⊆ {a} ↔ s = {a} := subset_singleton_iff.trans <| or_iff_right h.ne_empty theorem subset_singleton_iff' {s : Finset α} {a : α} : s ⊆ {a} ↔ ∀ b ∈ s, b = a := forall₂_congr fun _ _ => mem_singleton @[simp] theorem ssubset_singleton_iff {s : Finset α} {a : α} : s ⊂ {a} ↔ s = ∅ := by rw [← coe_ssubset, coe_singleton, Set.ssubset_singleton_iff, coe_eq_empty] theorem eq_empty_of_ssubset_singleton {s : Finset α} {x : α} (hs : s ⊂ {x}) : s = ∅ := ssubset_singleton_iff.1 hs /-- A finset is nontrivial if it has at least two elements. -/ protected abbrev Nontrivial (s : Finset α) : Prop := (s : Set α).Nontrivial @[simp] theorem not_nontrivial_empty : ¬ (∅ : Finset α).Nontrivial := by simp [Finset.Nontrivial] @[simp] theorem not_nontrivial_singleton : ¬ ({a} : Finset α).Nontrivial := by simp [Finset.Nontrivial] theorem Nontrivial.ne_singleton (hs : s.Nontrivial) : s ≠ {a} := by rintro rfl; exact not_nontrivial_singleton hs nonrec lemma Nontrivial.exists_ne (hs : s.Nontrivial) (a : α) : ∃ b ∈ s, b ≠ a := hs.exists_ne _ theorem eq_singleton_or_nontrivial (ha : a ∈ s) : s = {a} ∨ s.Nontrivial := by rw [← coe_eq_singleton]; exact Set.eq_singleton_or_nontrivial ha theorem nontrivial_iff_ne_singleton (ha : a ∈ s) : s.Nontrivial ↔ s ≠ {a} := ⟨Nontrivial.ne_singleton, (eq_singleton_or_nontrivial ha).resolve_left⟩ theorem Nonempty.exists_eq_singleton_or_nontrivial : s.Nonempty → (∃ a, s = {a}) ∨ s.Nontrivial := fun ⟨a, ha⟩ => (eq_singleton_or_nontrivial ha).imp_left <| Exists.intro a instance instNontrivial [Nonempty α] : Nontrivial (Finset α) := ‹Nonempty α›.elim fun a => ⟨⟨{a}, ∅, singleton_ne_empty _⟩⟩ instance [IsEmpty α] : Unique (Finset α) where default := ∅ uniq _ := eq_empty_of_forall_not_mem isEmptyElim instance (i : α) : Unique ({i} : Finset α) where default := ⟨i, mem_singleton_self i⟩ uniq j := Subtype.ext <| mem_singleton.mp j.2 @[simp] lemma default_singleton (i : α) : ((default : ({i} : Finset α)) : α) = i := rfl end Singleton /-! ### cons -/ section Cons variable {s t : Finset α} {a b : α} /-- `cons a s h` is the set `{a} ∪ s` containing `a` and the elements of `s`. It is the same as `insert a s` when it is defined, but unlike `insert a s` it does not require `DecidableEq α`, and the union is guaranteed to be disjoint. -/ def cons (a : α) (s : Finset α) (h : a ∉ s) : Finset α := ⟨a ::ₘ s.1, nodup_cons.2 ⟨h, s.2⟩⟩ @[simp] theorem mem_cons {h} : b ∈ s.cons a h ↔ b = a ∨ b ∈ s := Multiset.mem_cons theorem mem_cons_of_mem {a b : α} {s : Finset α} {hb : b ∉ s} (ha : a ∈ s) : a ∈ cons b s hb := Multiset.mem_cons_of_mem ha -- Porting note (#10618): @[simp] can prove this theorem mem_cons_self (a : α) (s : Finset α) {h} : a ∈ cons a s h := Multiset.mem_cons_self _ _ @[simp] theorem cons_val (h : a ∉ s) : (cons a s h).1 = a ::ₘ s.1 := rfl theorem forall_mem_cons (h : a ∉ s) (p : α → Prop) : (∀ x, x ∈ cons a s h → p x) ↔ p a ∧ ∀ x, x ∈ s → p x := by simp only [mem_cons, or_imp, forall_and, forall_eq] /-- Useful in proofs by induction. -/ theorem forall_of_forall_cons {p : α → Prop} {h : a ∉ s} (H : ∀ x, x ∈ cons a s h → p x) (x) (h : x ∈ s) : p x := H _ <| mem_cons.2 <| Or.inr h @[simp] theorem mk_cons {s : Multiset α} (h : (a ::ₘ s).Nodup) : (⟨a ::ₘ s, h⟩ : Finset α) = cons a ⟨s, (nodup_cons.1 h).2⟩ (nodup_cons.1 h).1 := rfl @[simp] theorem cons_empty (a : α) : cons a ∅ (not_mem_empty _) = {a} := rfl @[simp, aesop safe apply (rule_sets := [finsetNonempty])] theorem nonempty_cons (h : a ∉ s) : (cons a s h).Nonempty := ⟨a, mem_cons.2 <| Or.inl rfl⟩ @[simp] theorem nonempty_mk {m : Multiset α} {hm} : (⟨m, hm⟩ : Finset α).Nonempty ↔ m ≠ 0 := by induction m using Multiset.induction_on <;> simp @[simp] theorem coe_cons {a s h} : (@cons α a s h : Set α) = insert a (s : Set α) := by ext simp theorem subset_cons (h : a ∉ s) : s ⊆ s.cons a h := Multiset.subset_cons _ _ theorem ssubset_cons (h : a ∉ s) : s ⊂ s.cons a h := Multiset.ssubset_cons h theorem cons_subset {h : a ∉ s} : s.cons a h ⊆ t ↔ a ∈ t ∧ s ⊆ t := Multiset.cons_subset @[simp] theorem cons_subset_cons {hs ht} : s.cons a hs ⊆ t.cons a ht ↔ s ⊆ t := by rwa [← coe_subset, coe_cons, coe_cons, Set.insert_subset_insert_iff, coe_subset] theorem ssubset_iff_exists_cons_subset : s ⊂ t ↔ ∃ (a : _) (h : a ∉ s), s.cons a h ⊆ t := by refine ⟨fun h => ?_, fun ⟨a, ha, h⟩ => ssubset_of_ssubset_of_subset (ssubset_cons _) h⟩ obtain ⟨a, hs, ht⟩ := not_subset.1 h.2 exact ⟨a, ht, cons_subset.2 ⟨hs, h.subset⟩⟩ end Cons /-! ### disjoint -/ section Disjoint variable {f : α → β} {s t u : Finset α} {a b : α} theorem disjoint_left : Disjoint s t ↔ ∀ ⦃a⦄, a ∈ s → a ∉ t := ⟨fun h a hs ht => not_mem_empty a <| singleton_subset_iff.mp (h (singleton_subset_iff.mpr hs) (singleton_subset_iff.mpr ht)), fun h _ hs ht _ ha => (h (hs ha) (ht ha)).elim⟩ theorem disjoint_right : Disjoint s t ↔ ∀ ⦃a⦄, a ∈ t → a ∉ s := by rw [_root_.disjoint_comm, disjoint_left] theorem disjoint_iff_ne : Disjoint s t ↔ ∀ a ∈ s, ∀ b ∈ t, a ≠ b := by simp only [disjoint_left, imp_not_comm, forall_eq'] @[simp] theorem disjoint_val : s.1.Disjoint t.1 ↔ Disjoint s t := disjoint_left.symm theorem _root_.Disjoint.forall_ne_finset (h : Disjoint s t) (ha : a ∈ s) (hb : b ∈ t) : a ≠ b := disjoint_iff_ne.1 h _ ha _ hb theorem not_disjoint_iff : ¬Disjoint s t ↔ ∃ a, a ∈ s ∧ a ∈ t := disjoint_left.not.trans <| not_forall.trans <| exists_congr fun _ => by rw [Classical.not_imp, not_not] theorem disjoint_of_subset_left (h : s ⊆ u) (d : Disjoint u t) : Disjoint s t := disjoint_left.2 fun _x m₁ => (disjoint_left.1 d) (h m₁) theorem disjoint_of_subset_right (h : t ⊆ u) (d : Disjoint s u) : Disjoint s t := disjoint_right.2 fun _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 disjoint_singleton_left : Disjoint (singleton a) s ↔ a ∉ s := by simp only [disjoint_left, mem_singleton, forall_eq] @[simp] theorem disjoint_singleton_right : Disjoint s (singleton a) ↔ a ∉ s := disjoint_comm.trans disjoint_singleton_left -- Porting note: Left-hand side simplifies @[simp] theorem disjoint_singleton : Disjoint ({a} : Finset α) {b} ↔ a ≠ b := by rw [disjoint_singleton_left, mem_singleton] theorem disjoint_self_iff_empty (s : Finset α) : Disjoint s s ↔ s = ∅ := disjoint_self @[simp, norm_cast] theorem disjoint_coe : Disjoint (s : Set α) t ↔ Disjoint s t := by simp only [Finset.disjoint_left, Set.disjoint_left, mem_coe] @[simp, norm_cast] theorem pairwiseDisjoint_coe {ι : Type*} {s : Set ι} {f : ι → Finset α} : s.PairwiseDisjoint (fun i => f i : ι → Set α) ↔ s.PairwiseDisjoint f := forall₅_congr fun _ _ _ _ _ => disjoint_coe end Disjoint /-! ### disjoint union -/ /-- `disjUnion s t h` is the set such that `a ∈ disjUnion s t h` iff `a ∈ s` or `a ∈ t`. It is the same as `s ∪ t`, but it does not require decidable equality on the type. The hypothesis ensures that the sets are disjoint. -/ def disjUnion (s t : Finset α) (h : Disjoint s t) : Finset α := ⟨s.1 + t.1, Multiset.nodup_add.2 ⟨s.2, t.2, disjoint_val.2 h⟩⟩ @[simp] theorem mem_disjUnion {α s t h a} : a ∈ @disjUnion α s t h ↔ a ∈ s ∨ a ∈ t := by rcases s with ⟨⟨s⟩⟩; rcases t with ⟨⟨t⟩⟩; apply List.mem_append @[simp, norm_cast] theorem coe_disjUnion {s t : Finset α} (h : Disjoint s t) : (disjUnion s t h : Set α) = (s : Set α) ∪ t := Set.ext <| by simp theorem disjUnion_comm (s t : Finset α) (h : Disjoint s t) : disjUnion s t h = disjUnion t s h.symm := eq_of_veq <| add_comm _ _ @[simp] theorem empty_disjUnion (t : Finset α) (h : Disjoint ∅ t := disjoint_bot_left) : disjUnion ∅ t h = t := eq_of_veq <| zero_add _ @[simp] theorem disjUnion_empty (s : Finset α) (h : Disjoint s ∅ := disjoint_bot_right) : disjUnion s ∅ h = s := eq_of_veq <| add_zero _ theorem singleton_disjUnion (a : α) (t : Finset α) (h : Disjoint {a} t) : disjUnion {a} t h = cons a t (disjoint_singleton_left.mp h) := eq_of_veq <| Multiset.singleton_add _ _ theorem disjUnion_singleton (s : Finset α) (a : α) (h : Disjoint s {a}) : disjUnion s {a} h = cons a s (disjoint_singleton_right.mp h) := by rw [disjUnion_comm, singleton_disjUnion] /-! ### insert -/ section Insert variable [DecidableEq α] {s t u v : Finset α} {a b : α} /-- `insert a s` is the set `{a} ∪ s` containing `a` and the elements of `s`. -/ instance : Insert α (Finset α) := ⟨fun a s => ⟨_, s.2.ndinsert a⟩⟩ theorem insert_def (a : α) (s : Finset α) : insert a s = ⟨_, s.2.ndinsert a⟩ := 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 = dedup (a ::ₘ s.1) := by rw [dedup_cons, dedup_eq_self]; rfl 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 ∈ 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 (h : a ∈ s) : a ∈ insert b s := mem_ndinsert_of_mem h theorem mem_of_mem_insert_of_ne (h : b ∈ insert a s) : b ≠ a → b ∈ s := (mem_insert.1 h).resolve_left theorem eq_of_not_mem_of_mem_insert (ha : b ∈ insert a s) (hb : b ∉ s) : b = a := (mem_insert.1 ha).resolve_right hb /-- A version of `LawfulSingleton.insert_emptyc_eq` that works with `dsimp`. -/ @[simp] lemma insert_empty : insert a (∅ : Finset α) = {a} := rfl @[simp] theorem cons_eq_insert (a s h) : @cons α a s h = insert a s := ext fun a => by simp @[simp, norm_cast] theorem coe_insert (a : α) (s : Finset α) : ↑(insert a s) = (insert a s : Set α) := Set.ext fun x => by simp only [mem_coe, mem_insert, Set.mem_insert_iff] theorem mem_insert_coe {s : Finset α} {x y : α} : x ∈ insert y s ↔ x ∈ insert y (s : Set α) := by simp instance : LawfulSingleton α (Finset α) := ⟨fun a => by ext; simp⟩ @[simp] theorem insert_eq_of_mem (h : a ∈ s) : insert a s = s := eq_of_veq <| ndinsert_of_mem h @[simp] theorem insert_eq_self : insert a s = s ↔ a ∈ s := ⟨fun h => h ▸ mem_insert_self _ _, insert_eq_of_mem⟩ theorem insert_ne_self : insert a s ≠ s ↔ a ∉ s := insert_eq_self.not -- Porting note (#10618): @[simp] can prove this theorem pair_eq_singleton (a : α) : ({a, a} : Finset α) = {a} := insert_eq_of_mem <| mem_singleton_self _ theorem Insert.comm (a b : α) (s : Finset α) : insert a (insert b s) = insert b (insert a s) := ext fun x => by simp only [mem_insert, or_left_comm] -- Porting note (#10618): @[simp] can prove this @[norm_cast] theorem coe_pair {a b : α} : (({a, b} : Finset α) : Set α) = {a, b} := by ext simp @[simp, norm_cast] theorem coe_eq_pair {s : Finset α} {a b : α} : (s : Set α) = {a, b} ↔ s = {a, b} := by rw [← coe_pair, coe_inj] theorem pair_comm (a b : α) : ({a, b} : Finset α) = {b, a} := Insert.comm a b ∅ -- Porting note (#10618): @[simp] can prove this theorem insert_idem (a : α) (s : Finset α) : insert a (insert a s) = insert a s := ext fun x => by simp only [mem_insert, ← or_assoc, or_self_iff] @[simp, aesop safe apply (rule_sets := [finsetNonempty])] theorem insert_nonempty (a : α) (s : Finset α) : (insert a s).Nonempty := ⟨a, mem_insert_self a s⟩ @[simp] theorem insert_ne_empty (a : α) (s : Finset α) : insert a s ≠ ∅ := (insert_nonempty a s).ne_empty -- Porting note: explicit universe annotation is no longer required. instance (i : α) (s : Finset α) : Nonempty ((insert i s : Finset α) : Set α) := (Finset.coe_nonempty.mpr (s.insert_nonempty i)).to_subtype theorem ne_insert_of_not_mem (s t : Finset α) {a : α} (h : a ∉ s) : s ≠ insert a t := by contrapose! h simp [h] theorem insert_subset_iff : insert a s ⊆ t ↔ a ∈ t ∧ s ⊆ t := by simp only [subset_iff, mem_insert, forall_eq, or_imp, forall_and] theorem insert_subset (ha : a ∈ t) (hs : s ⊆ t) : insert a s ⊆ t := insert_subset_iff.mpr ⟨ha,hs⟩ @[simp] theorem subset_insert (a : α) (s : Finset α) : s ⊆ insert a s := fun _b => mem_insert_of_mem @[gcongr] theorem insert_subset_insert (a : α) {s t : Finset α} (h : s ⊆ t) : insert a s ⊆ insert a t := insert_subset_iff.2 ⟨mem_insert_self _ _, Subset.trans h (subset_insert _ _)⟩ @[simp] lemma insert_subset_insert_iff (ha : a ∉ s) : insert a s ⊆ insert a t ↔ s ⊆ t := by simp_rw [← coe_subset]; simp [-coe_subset, ha] theorem insert_inj (ha : a ∉ s) : insert a s = insert b s ↔ a = b := ⟨fun h => eq_of_not_mem_of_mem_insert (h.subst <| mem_insert_self _ _) ha, congr_arg (insert · s)⟩ theorem insert_inj_on (s : Finset α) : Set.InjOn (fun a => insert a s) sᶜ := fun _ h _ _ => (insert_inj h).1 theorem ssubset_iff : s ⊂ t ↔ ∃ a ∉ s, insert a s ⊆ t := mod_cast @Set.ssubset_iff_insert α s t theorem ssubset_insert (h : a ∉ s) : s ⊂ insert a s := ssubset_iff.mpr ⟨a, h, Subset.rfl⟩ @[elab_as_elim] theorem cons_induction {α : Type*} {p : Finset α → Prop} (empty : p ∅) (cons : ∀ (a : α) (s : Finset α) (h : a ∉ s), p s → p (cons a s h)) : ∀ s, p s | ⟨s, nd⟩ => by induction s using Multiset.induction with | empty => exact empty | cons a s IH => rw [mk_cons nd] exact cons a _ _ (IH _) @[elab_as_elim] theorem cons_induction_on {α : Type*} {p : Finset α → Prop} (s : Finset α) (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : Finset α} (h : a ∉ s), p s → p (cons a s h)) : p s := cons_induction h₁ h₂ s @[elab_as_elim] protected theorem induction {α : Type*} {p : Finset α → Prop} [DecidableEq α] (empty : p ∅) (insert : ∀ ⦃a : α⦄ {s : Finset α}, a ∉ s → p s → p (insert a s)) : ∀ s, p s := cons_induction empty fun a s ha => (s.cons_eq_insert a ha).symm ▸ insert ha /-- 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_elim] protected theorem induction_on {α : Type*} {p : Finset α → Prop} [DecidableEq α] (s : Finset α) (empty : p ∅) (insert : ∀ ⦃a : α⦄ {s : Finset α}, a ∉ s → p s → p (insert a s)) : p s := Finset.induction empty insert s /-- To prove a proposition about `S : Finset α`, it suffices to prove it for the empty `Finset`, and to show that if it holds for some `Finset α ⊆ S`, then it holds for the `Finset` obtained by inserting a new element of `S`. -/ @[elab_as_elim] theorem induction_on' {α : Type*} {p : Finset α → Prop} [DecidableEq α] (S : Finset α) (h₁ : p ∅) (h₂ : ∀ {a s}, a ∈ S → s ⊆ S → a ∉ s → p s → p (insert a s)) : p S := @Finset.induction_on α (fun T => T ⊆ S → p T) _ S (fun _ => h₁) (fun _ _ has hqs hs => let ⟨hS, sS⟩ := Finset.insert_subset_iff.1 hs h₂ hS sS has (hqs sS)) (Finset.Subset.refl S) /-- To prove a proposition about a nonempty `s : Finset α`, it suffices to show it holds for all singletons and that if it holds for nonempty `t : Finset α`, then it also holds for the `Finset` obtained by inserting an element in `t`. -/ @[elab_as_elim] theorem Nonempty.cons_induction {α : Type*} {p : ∀ s : Finset α, s.Nonempty → Prop} (singleton : ∀ a, p {a} (singleton_nonempty _)) (cons : ∀ a s (h : a ∉ s) (hs), p s hs → p (Finset.cons a s h) (nonempty_cons h)) {s : Finset α} (hs : s.Nonempty) : p s hs := by induction s using Finset.cons_induction with | empty => exact (not_nonempty_empty hs).elim | cons a t ha h => obtain rfl | ht := t.eq_empty_or_nonempty · exact singleton a · exact cons a t ha ht (h ht) -- We use a fresh `α` here to exclude the unneeded `DecidableEq α` instance from the section. lemma Nonempty.exists_cons_eq {α} {s : Finset α} (hs : s.Nonempty) : ∃ t a ha, cons a t ha = s := hs.cons_induction (fun a ↦ ⟨∅, a, _, cons_empty _⟩) fun _ _ _ _ _ ↦ ⟨_, _, _, rfl⟩ /-- Inserting an element to a finite set is equivalent to the option type. -/ def subtypeInsertEquivOption {t : Finset α} {x : α} (h : x ∉ t) : { i // i ∈ insert x t } ≃ Option { i // i ∈ t } where toFun y := if h : ↑y = x then none else some ⟨y, (mem_insert.mp y.2).resolve_left h⟩ invFun y := (y.elim ⟨x, mem_insert_self _ _⟩) fun z => ⟨z, mem_insert_of_mem z.2⟩ left_inv y := by by_cases h : ↑y = x · simp only [Subtype.ext_iff, h, Option.elim, dif_pos, Subtype.coe_mk] · simp only [h, Option.elim, dif_neg, not_false_iff, Subtype.coe_eta, Subtype.coe_mk] right_inv := by rintro (_ | y) · simp only [Option.elim, dif_pos] · have : ↑y ≠ x := by rintro ⟨⟩ exact h y.2 simp only [this, Option.elim, Subtype.eta, dif_neg, not_false_iff, Subtype.coe_mk] @[simp] theorem disjoint_insert_left : Disjoint (insert a s) t ↔ a ∉ t ∧ Disjoint s t := by simp only [disjoint_left, mem_insert, or_imp, forall_and, forall_eq] @[simp] theorem disjoint_insert_right : Disjoint s (insert a t) ↔ a ∉ s ∧ Disjoint s t := disjoint_comm.trans <| by rw [disjoint_insert_left, _root_.disjoint_comm] end Insert /-! ### Lattice structure -/ section Lattice variable [DecidableEq α] {s s₁ s₂ t t₁ t₂ u v : Finset α} {a b : α} /-- `s ∪ t` is the set such that `a ∈ s ∪ t` iff `a ∈ s` or `a ∈ t`. -/ instance : Union (Finset α) := ⟨fun s t => ⟨_, t.2.ndunion s.1⟩⟩ /-- `s ∩ t` is the set such that `a ∈ s ∩ t` iff `a ∈ s` and `a ∈ t`. -/ instance : Inter (Finset α) := ⟨fun s t => ⟨_, s.2.ndinter t.1⟩⟩ instance : Lattice (Finset α) := { Finset.partialOrder with sup := (· ∪ ·) sup_le := fun _ _ _ hs ht _ ha => (mem_ndunion.1 ha).elim (fun h => hs h) fun h => ht h le_sup_left := fun _ _ _ h => mem_ndunion.2 <| Or.inl h le_sup_right := fun _ _ _ h => mem_ndunion.2 <| Or.inr h inf := (· ∩ ·) le_inf := fun _ _ _ ht hu _ h => mem_ndinter.2 ⟨ht h, hu h⟩ inf_le_left := fun _ _ _ h => (mem_ndinter.1 h).1 inf_le_right := fun _ _ _ h => (mem_ndinter.1 h).2 } @[simp] theorem sup_eq_union : (Sup.sup : Finset α → Finset α → Finset α) = Union.union := rfl @[simp] theorem inf_eq_inter : (Inf.inf : Finset α → Finset α → Finset α) = Inter.inter := rfl theorem disjoint_iff_inter_eq_empty : Disjoint s t ↔ s ∩ t = ∅ := disjoint_iff instance decidableDisjoint (U V : Finset α) : Decidable (Disjoint U V) := decidable_of_iff _ disjoint_left.symm /-! #### union -/ theorem union_val_nd (s t : Finset α) : (s ∪ t).1 = ndunion s.1 t.1 := rfl @[simp] theorem union_val (s t : Finset α) : (s ∪ t).1 = s.1 ∪ t.1 := ndunion_eq_union s.2 @[simp] theorem mem_union : a ∈ s ∪ t ↔ a ∈ s ∨ a ∈ t := mem_ndunion @[simp] theorem disjUnion_eq_union (s t h) : @disjUnion α s t h = s ∪ t := ext fun a => by simp theorem mem_union_left (t : Finset α) (h : a ∈ s) : a ∈ s ∪ t := mem_union.2 <| Or.inl h theorem mem_union_right (s : Finset α) (h : a ∈ t) : a ∈ s ∪ t := mem_union.2 <| Or.inr h theorem forall_mem_union {p : α → Prop} : (∀ a ∈ s ∪ t, p a) ↔ (∀ a ∈ s, p a) ∧ ∀ a ∈ t, p a := ⟨fun h => ⟨fun a => h a ∘ mem_union_left _, fun b => h b ∘ mem_union_right _⟩, fun h _ab hab => (mem_union.mp hab).elim (h.1 _) (h.2 _)⟩ theorem not_mem_union : a ∉ s ∪ t ↔ a ∉ s ∧ a ∉ t := by rw [mem_union, not_or] @[simp, norm_cast] theorem coe_union (s₁ s₂ : Finset α) : ↑(s₁ ∪ s₂) = (s₁ ∪ s₂ : Set α) := Set.ext fun _ => mem_union theorem union_subset (hs : s ⊆ u) : t ⊆ u → s ∪ t ⊆ u := sup_le <| le_iff_subset.2 hs theorem subset_union_left {s₁ s₂ : Finset α} : s₁ ⊆ s₁ ∪ s₂ := fun _x => mem_union_left _ theorem subset_union_right {s₁ s₂ : Finset α} : s₂ ⊆ s₁ ∪ s₂ := fun _x => mem_union_right _ @[gcongr] theorem union_subset_union (hsu : s ⊆ u) (htv : t ⊆ v) : s ∪ t ⊆ u ∪ v := sup_le_sup (le_iff_subset.2 hsu) htv @[gcongr] theorem union_subset_union_left (h : s₁ ⊆ s₂) : s₁ ∪ t ⊆ s₂ ∪ t := union_subset_union h Subset.rfl @[gcongr] theorem union_subset_union_right (h : t₁ ⊆ t₂) : s ∪ t₁ ⊆ s ∪ t₂ := union_subset_union Subset.rfl h theorem union_comm (s₁ s₂ : Finset α) : s₁ ∪ s₂ = s₂ ∪ s₁ := sup_comm _ _ instance : Std.Commutative (α := Finset α) (· ∪ ·) := ⟨union_comm⟩ @[simp] theorem union_assoc (s₁ s₂ s₃ : Finset α) : s₁ ∪ s₂ ∪ s₃ = s₁ ∪ (s₂ ∪ s₃) := sup_assoc _ _ _ instance : Std.Associative (α := Finset α) (· ∪ ·) := ⟨union_assoc⟩ @[simp] theorem union_idempotent (s : Finset α) : s ∪ s = s := sup_idem _ instance : Std.IdempotentOp (α := Finset α) (· ∪ ·) := ⟨union_idempotent⟩ theorem union_subset_left (h : s ∪ t ⊆ u) : s ⊆ u := subset_union_left.trans h theorem union_subset_right {s t u : Finset α} (h : s ∪ t ⊆ u) : t ⊆ u := Subset.trans subset_union_right h theorem union_left_comm (s t u : Finset α) : s ∪ (t ∪ u) = t ∪ (s ∪ u) := ext fun _ => by simp only [mem_union, or_left_comm] theorem union_right_comm (s t u : Finset α) : s ∪ t ∪ u = s ∪ u ∪ t := ext fun x => by simp only [mem_union, or_assoc, @or_comm (x ∈ t)] theorem union_self (s : Finset α) : s ∪ s = s := union_idempotent s @[simp] theorem union_empty (s : Finset α) : s ∪ ∅ = s := ext fun x => mem_union.trans <| by simp @[simp] theorem empty_union (s : Finset α) : ∅ ∪ s = s := ext fun x => mem_union.trans <| by simp @[aesop unsafe apply (rule_sets := [finsetNonempty])] theorem Nonempty.inl {s t : Finset α} (h : s.Nonempty) : (s ∪ t).Nonempty := h.mono subset_union_left @[aesop unsafe apply (rule_sets := [finsetNonempty])] theorem Nonempty.inr {s t : Finset α} (h : t.Nonempty) : (s ∪ t).Nonempty := h.mono subset_union_right 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 : s ∪ t = s ↔ t ⊆ s := sup_eq_left @[simp] lemma left_eq_union : s = s ∪ t ↔ t ⊆ s := by rw [eq_comm, union_eq_left] @[simp] lemma union_eq_right : s ∪ t = t ↔ s ⊆ t := sup_eq_right @[simp] lemma right_eq_union : s = t ∪ s ↔ t ⊆ s := by rw [eq_comm, union_eq_right] -- Porting note: replaced `⊔` in RHS theorem union_congr_left (ht : t ⊆ s ∪ u) (hu : u ⊆ s ∪ t) : s ∪ t = s ∪ u := sup_congr_left ht hu theorem union_congr_right (hs : s ⊆ t ∪ u) (ht : t ⊆ s ∪ u) : s ∪ u = t ∪ u := sup_congr_right hs ht theorem union_eq_union_iff_left : s ∪ t = s ∪ u ↔ t ⊆ s ∪ u ∧ u ⊆ s ∪ t := sup_eq_sup_iff_left theorem union_eq_union_iff_right : s ∪ u = t ∪ u ↔ s ⊆ t ∪ u ∧ t ⊆ s ∪ u := sup_eq_sup_iff_right @[simp] theorem disjoint_union_left : Disjoint (s ∪ t) u ↔ Disjoint s u ∧ Disjoint t u := by simp only [disjoint_left, mem_union, or_imp, forall_and] @[simp] theorem disjoint_union_right : Disjoint s (t ∪ u) ↔ Disjoint s t ∧ Disjoint s u := by simp only [disjoint_right, mem_union, or_imp, forall_and] /-- To prove a relation on pairs of `Finset X`, it suffices to show that it is * symmetric, * it holds when one of the `Finset`s is empty, * it holds for pairs of singletons, * if it holds for `[a, c]` and for `[b, c]`, then it holds for `[a ∪ b, c]`. -/ theorem induction_on_union (P : Finset α → Finset α → Prop) (symm : ∀ {a b}, P a b → P b a) (empty_right : ∀ {a}, P a ∅) (singletons : ∀ {a b}, P {a} {b}) (union_of : ∀ {a b c}, P a c → P b c → P (a ∪ b) c) : ∀ a b, P a b := by intro a b refine Finset.induction_on b empty_right fun x s _xs hi => symm ?_ rw [Finset.insert_eq] apply union_of _ (symm hi) refine Finset.induction_on a empty_right fun a t _ta hi => symm ?_ rw [Finset.insert_eq] exact union_of singletons (symm hi) /-! #### inter -/ 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₁ := fun _a => mem_of_mem_inter_left theorem inter_subset_right {s₁ s₂ : Finset α} : s₁ ∩ s₂ ⊆ s₂ := fun _a => mem_of_mem_inter_right theorem subset_inter {s₁ s₂ u : Finset α} : s₁ ⊆ s₂ → s₁ ⊆ u → s₁ ⊆ s₂ ∩ u := by simp (config := { contextual := true }) [subset_iff, mem_inter] @[simp, norm_cast] theorem coe_inter (s₁ s₂ : Finset α) : ↑(s₁ ∩ s₂) = (s₁ ∩ s₂ : Set α) := Set.ext fun _ => 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 fun _ => by simp only [mem_inter, and_comm] @[simp] theorem inter_assoc (s₁ s₂ s₃ : Finset α) : s₁ ∩ s₂ ∩ s₃ = s₁ ∩ (s₂ ∩ s₃) := ext fun _ => by simp only [mem_inter, and_assoc] theorem inter_left_comm (s₁ s₂ s₃ : Finset α) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := ext fun _ => by simp only [mem_inter, and_left_comm] theorem inter_right_comm (s₁ s₂ s₃ : Finset α) : s₁ ∩ s₂ ∩ s₃ = s₁ ∩ s₃ ∩ s₂ := ext fun _ => by simp only [mem_inter, and_right_comm] @[simp] theorem inter_self (s : Finset α) : s ∩ s = s := ext fun _ => mem_inter.trans <| and_self_iff @[simp] theorem inter_empty (s : Finset α) : s ∩ ∅ = ∅ := ext fun _ => mem_inter.trans <| by simp @[simp] theorem empty_inter (s : Finset α) : ∅ ∩ s = ∅ := ext fun _ => mem_inter.trans <| by simp @[simp] theorem inter_union_self (s t : Finset α) : s ∩ (t ∪ s) = s := by rw [inter_comm, union_inter_cancel_right] @[simp] theorem insert_inter_of_mem {s₁ s₂ : Finset α} {a : α} (h : a ∈ s₂) : insert a s₁ ∩ s₂ = insert a (s₁ ∩ s₂) := ext fun x => by have : x = a ∨ x ∈ s₂ ↔ x ∈ s₂ := or_iff_right_of_imp <| by rintro rfl; exact h simp only [mem_inter, mem_insert, or_and_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 fun x => by have : ¬(x = a ∧ x ∈ s₂) := by rintro ⟨rfl, H⟩; exact h H simp only [mem_inter, mem_insert, or_and_right, this, false_or_iff] @[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, gcongr] theorem inter_subset_inter {x y s t : Finset α} (h : x ⊆ y) (h' : s ⊆ t) : x ∩ s ⊆ y ∩ t := by intro a a_in rw [Finset.mem_inter] at a_in ⊢ exact ⟨h a_in.1, h' a_in.2⟩ @[gcongr] theorem inter_subset_inter_left (h : t ⊆ u) : s ∩ t ⊆ s ∩ u := inter_subset_inter Subset.rfl h @[gcongr] theorem inter_subset_inter_right (h : s ⊆ t) : s ∩ u ⊆ t ∩ u := inter_subset_inter h Subset.rfl theorem inter_subset_union : s ∩ t ⊆ s ∪ t := le_iff_subset.1 inf_le_sup instance : DistribLattice (Finset α) := { le_sup_inf := fun a b c => by simp (config := { contextual := true }) only [sup_eq_union, inf_eq_inter, le_eq_subset, subset_iff, mem_inter, mem_union, and_imp, or_imp, true_or_iff, imp_true_iff, true_and_iff, or_true_iff] } @[simp] theorem union_left_idem (s t : Finset α) : s ∪ (s ∪ t) = s ∪ t := sup_left_idem _ _ -- Porting note (#10618): @[simp] can prove this theorem union_right_idem (s t : Finset α) : s ∪ t ∪ t = s ∪ t := sup_right_idem _ _ @[simp] theorem inter_left_idem (s t : Finset α) : s ∩ (s ∩ t) = s ∩ t := inf_left_idem _ _ -- Porting note (#10618): @[simp] can prove this theorem inter_right_idem (s t : Finset α) : s ∩ t ∩ t = s ∩ t := inf_right_idem _ _ theorem inter_union_distrib_left (s t u : Finset α) : s ∩ (t ∪ u) = s ∩ t ∪ s ∩ u := inf_sup_left _ _ _ theorem union_inter_distrib_right (s t u : Finset α) : (s ∪ t) ∩ u = s ∩ u ∪ t ∩ u := inf_sup_right _ _ _ theorem union_inter_distrib_left (s t u : Finset α) : s ∪ t ∩ u = (s ∪ t) ∩ (s ∪ u) := sup_inf_left _ _ _ theorem inter_union_distrib_right (s t u : Finset α) : s ∩ t ∪ u = (s ∪ u) ∩ (t ∪ u) := sup_inf_right _ _ _ @[deprecated (since := "2024-03-22")] alias inter_distrib_left := inter_union_distrib_left @[deprecated (since := "2024-03-22")] alias inter_distrib_right := union_inter_distrib_right @[deprecated (since := "2024-03-22")] alias union_distrib_left := union_inter_distrib_left @[deprecated (since := "2024-03-22")] alias union_distrib_right := inter_union_distrib_right theorem union_union_distrib_left (s t u : Finset α) : s ∪ (t ∪ u) = s ∪ t ∪ (s ∪ u) := sup_sup_distrib_left _ _ _ theorem union_union_distrib_right (s t u : Finset α) : s ∪ t ∪ u = s ∪ u ∪ (t ∪ u) := sup_sup_distrib_right _ _ _ theorem inter_inter_distrib_left (s t u : Finset α) : s ∩ (t ∩ u) = s ∩ t ∩ (s ∩ u) := inf_inf_distrib_left _ _ _ theorem inter_inter_distrib_right (s t u : Finset α) : s ∩ t ∩ u = s ∩ u ∩ (t ∩ u) := inf_inf_distrib_right _ _ _ theorem union_union_union_comm (s t u v : Finset α) : s ∪ t ∪ (u ∪ v) = s ∪ u ∪ (t ∪ v) := sup_sup_sup_comm _ _ _ _ theorem inter_inter_inter_comm (s t u v : Finset α) : s ∩ t ∩ (u ∩ v) = s ∩ u ∩ (t ∩ v) := inf_inf_inf_comm _ _ _ _ lemma union_eq_empty : s ∪ t = ∅ ↔ s = ∅ ∧ t = ∅ := sup_eq_bot_iff theorem union_subset_iff : s ∪ t ⊆ u ↔ s ⊆ u ∧ t ⊆ u := (sup_le_iff : s ⊔ t ≤ u ↔ s ≤ u ∧ t ≤ u) theorem subset_inter_iff : s ⊆ t ∩ u ↔ s ⊆ t ∧ s ⊆ u := (le_inf_iff : s ≤ t ⊓ u ↔ s ≤ t ∧ s ≤ u) @[simp] lemma inter_eq_left : s ∩ t = s ↔ s ⊆ t := inf_eq_left @[simp] lemma inter_eq_right : t ∩ s = s ↔ s ⊆ t := inf_eq_right theorem inter_congr_left (ht : s ∩ u ⊆ t) (hu : s ∩ t ⊆ u) : s ∩ t = s ∩ u := inf_congr_left ht hu theorem inter_congr_right (hs : t ∩ u ⊆ s) (ht : s ∩ u ⊆ t) : s ∩ u = t ∩ u := inf_congr_right hs ht theorem inter_eq_inter_iff_left : s ∩ t = s ∩ u ↔ s ∩ u ⊆ t ∧ s ∩ t ⊆ u := inf_eq_inf_iff_left theorem inter_eq_inter_iff_right : s ∩ u = t ∩ u ↔ t ∩ u ⊆ s ∧ s ∩ u ⊆ t := inf_eq_inf_iff_right theorem ite_subset_union (s s' : Finset α) (P : Prop) [Decidable P] : ite P s s' ⊆ s ∪ s' := ite_le_sup s s' P theorem inter_subset_ite (s s' : Finset α) (P : Prop) [Decidable P] : s ∩ s' ⊆ ite P s s' := inf_le_ite s s' P theorem not_disjoint_iff_nonempty_inter : ¬Disjoint s t ↔ (s ∩ t).Nonempty := not_disjoint_iff.trans <| by simp [Finset.Nonempty] alias ⟨_, Nonempty.not_disjoint⟩ := not_disjoint_iff_nonempty_inter theorem disjoint_or_nonempty_inter (s t : Finset α) : Disjoint s t ∨ (s ∩ t).Nonempty := by rw [← not_disjoint_iff_nonempty_inter] exact em _ end Lattice instance isDirected_le : IsDirected (Finset α) (· ≤ ·) := by classical infer_instance instance isDirected_subset : IsDirected (Finset α) (· ⊆ ·) := isDirected_le /-! ### erase -/ section Erase variable [DecidableEq α] {s t u v : Finset α} {a b : α} /-- `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 α := ⟨_, s.2.erase a⟩ @[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 := s.2.mem_erase_iff theorem not_mem_erase (a : α) (s : Finset α) : a ∉ erase s a := s.2.not_mem_erase @[simp] theorem erase_empty (a : α) : erase ∅ a = ∅ := rfl protected lemma Nontrivial.erase_nonempty (hs : s.Nontrivial) : (s.erase a).Nonempty := (hs.exists_ne a).imp $ by aesop @[simp] lemma erase_nonempty (ha : a ∈ s) : (s.erase a).Nonempty ↔ s.Nontrivial := by simp only [Finset.Nonempty, mem_erase, and_comm (b := _ ∈ _)] refine ⟨?_, fun hs ↦ hs.exists_ne a⟩ rintro ⟨b, hb, hba⟩ exact ⟨_, hb, _, ha, hba⟩ @[simp] theorem erase_singleton (a : α) : ({a} : Finset α).erase a = ∅ := by ext x simp theorem ne_of_mem_erase : b ∈ erase s a → b ≠ a := fun h => (mem_erase.1 h).1 theorem mem_of_mem_erase : b ∈ erase s a → b ∈ s := Multiset.mem_of_mem_erase theorem mem_erase_of_ne_of_mem : a ≠ b → a ∈ s → a ∈ erase s b := by simp only [mem_erase]; exact And.intro /-- An element of `s` that is not an element of `erase s a` must be`a`. -/ theorem eq_of_mem_of_not_mem_erase (hs : b ∈ s) (hsa : b ∉ s.erase a) : b = a := by rw [mem_erase, not_and] at hsa exact not_imp_not.mp hsa hs @[simp] theorem erase_eq_of_not_mem {a : α} {s : Finset α} (h : a ∉ s) : erase s a = s := eq_of_veq <| erase_of_not_mem h @[simp] theorem erase_eq_self : s.erase a = s ↔ a ∉ s := ⟨fun h => h ▸ not_mem_erase _ _, erase_eq_of_not_mem⟩ @[simp] theorem erase_insert_eq_erase (s : Finset α) (a : α) : (insert a s).erase a = s.erase a := ext fun x => by simp (config := { contextual := true }) only [mem_erase, mem_insert, and_congr_right_iff, false_or_iff, iff_self_iff, imp_true_iff] theorem erase_insert {a : α} {s : Finset α} (h : a ∉ s) : erase (insert a s) a = s := by rw [erase_insert_eq_erase, erase_eq_of_not_mem h] theorem erase_insert_of_ne {a b : α} {s : Finset α} (h : a ≠ b) : erase (insert a s) b = insert a (erase s b) := ext fun x => by have : x ≠ b ∧ x = a ↔ x = a := and_iff_right_of_imp fun hx => hx.symm ▸ h simp only [mem_erase, mem_insert, and_or_left, this] theorem erase_cons_of_ne {a b : α} {s : Finset α} (ha : a ∉ s) (hb : a ≠ b) : erase (cons a s ha) b = cons a (erase s b) fun h => ha <| erase_subset _ _ h := by simp only [cons_eq_insert, erase_insert_of_ne hb] @[simp] theorem insert_erase (h : a ∈ s) : insert a (erase s a) = s := ext fun x => by simp only [mem_insert, mem_erase, or_and_left, dec_em, true_and_iff] apply or_iff_right_of_imp rintro rfl exact h lemma erase_eq_iff_eq_insert (hs : a ∈ s) (ht : a ∉ t) : erase s a = t ↔ s = insert a t := by aesop lemma insert_erase_invOn : Set.InvOn (insert a) (fun s ↦ erase s a) {s : Finset α | a ∈ s} {s : Finset α | a ∉ s} := ⟨fun _s ↦ insert_erase, fun _s ↦ erase_insert⟩ 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 := Multiset.erase_subset _ _ theorem subset_erase {a : α} {s t : Finset α} : s ⊆ t.erase a ↔ s ⊆ t ∧ a ∉ s := ⟨fun h => ⟨h.trans (erase_subset _ _), fun ha => not_mem_erase _ _ (h ha)⟩, fun h _b hb => mem_erase.2 ⟨ne_of_mem_of_not_mem hb h.2, h.1 hb⟩⟩ @[simp, norm_cast] theorem coe_erase (a : α) (s : Finset α) : ↑(erase s a) = (s \ {a} : Set α) := Set.ext fun _ => mem_erase.trans <| by rw [and_comm, Set.mem_diff, Set.mem_singleton_iff, mem_coe] theorem 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 ssubset_iff_exists_subset_erase {s t : Finset α} : s ⊂ t ↔ ∃ a ∈ t, s ⊆ t.erase a := by refine ⟨fun h => ?_, fun ⟨a, ha, h⟩ => ssubset_of_subset_of_ssubset h <| erase_ssubset ha⟩ obtain ⟨a, ht, hs⟩ := not_subset.1 h.2 exact ⟨a, ht, subset_erase.2 ⟨h.1, hs⟩⟩ theorem erase_ssubset_insert (s : Finset α) (a : α) : s.erase a ⊂ insert a s := ssubset_iff_exists_subset_erase.2 ⟨a, mem_insert_self _ _, erase_subset_erase _ <| subset_insert _ _⟩ theorem erase_ne_self : s.erase a ≠ s ↔ a ∈ s := erase_eq_self.not_left theorem erase_cons {s : Finset α} {a : α} (h : a ∉ s) : (s.cons a h).erase a = s := by rw [cons_eq_insert, erase_insert_eq_erase, erase_eq_of_not_mem h] theorem erase_idem {a : α} {s : Finset α} : erase (erase s a) a = erase s a := by simp theorem erase_right_comm {a b : α} {s : Finset α} : erase (erase s a) b = erase (erase s b) a := by ext x simp only [mem_erase, ← and_assoc] rw [@and_comm (x ≠ a)] 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' fun x => forall_swap theorem erase_insert_subset (a : α) (s : Finset α) : erase (insert a s) a ⊆ s := subset_insert_iff.1 <| Subset.rfl theorem insert_erase_subset (a : α) (s : Finset α) : s ⊆ insert a (erase s a) := subset_insert_iff.2 <| Subset.rfl theorem subset_insert_iff_of_not_mem (h : a ∉ s) : s ⊆ insert a t ↔ s ⊆ t := by rw [subset_insert_iff, erase_eq_of_not_mem h] theorem erase_subset_iff_of_mem (h : a ∈ t) : s.erase a ⊆ t ↔ s ⊆ t := by rw [← subset_insert_iff, insert_eq_of_mem h] theorem erase_inj {x y : α} (s : Finset α) (hx : x ∈ s) : s.erase x = s.erase y ↔ x = y := by refine ⟨fun h => eq_of_mem_of_not_mem_erase hx ?_, congr_arg _⟩ rw [← h] simp theorem erase_injOn (s : Finset α) : Set.InjOn s.erase s := fun _ _ _ _ => (erase_inj s ‹_›).mp theorem erase_injOn' (a : α) : { s : Finset α | a ∈ s }.InjOn fun s => erase s a := fun s hs t ht (h : s.erase a = _) => by rw [← insert_erase hs, ← insert_erase ht, h] end Erase lemma Nontrivial.exists_cons_eq {s : Finset α} (hs : s.Nontrivial) : ∃ t a ha b hb hab, (cons b t hb).cons a (mem_cons.not.2 <| not_or_intro hab ha) = s := by classical obtain ⟨a, ha, b, hb, hab⟩ := hs have : b ∈ s.erase a := mem_erase.2 ⟨hab.symm, hb⟩ refine ⟨(s.erase a).erase b, a, ?_, b, ?_, ?_, ?_⟩ <;> simp [insert_erase this, insert_erase ha, *] /-! ### sdiff -/ section Sdiff variable [DecidableEq α] {s t u v : Finset α} {a b : α} /-- `s \ t` is the set consisting of the elements of `s` that are not in `t`. -/ instance : SDiff (Finset α) := ⟨fun s₁ s₂ => ⟨s₁.1 - s₂.1, nodup_of_le tsub_le_self s₁.2⟩⟩ @[simp] theorem sdiff_val (s₁ s₂ : Finset α) : (s₁ \ s₂).val = s₁.val - s₂.val := rfl @[simp] theorem mem_sdiff : a ∈ s \ t ↔ a ∈ s ∧ a ∉ t := mem_sub_of_nodup s.2 @[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 instance : GeneralizedBooleanAlgebra (Finset α) := { sup_inf_sdiff := fun x y => by simp only [ext_iff, mem_union, mem_sdiff, inf_eq_inter, sup_eq_union, mem_inter, ← and_or_left, em, and_true, implies_true] inf_inf_sdiff := fun x y => by simp only [ext_iff, inter_sdiff_self, inter_empty, inter_assoc, false_iff_iff, inf_eq_inter, not_mem_empty, bot_eq_empty, not_false_iff, implies_true] } theorem not_mem_sdiff_of_mem_right (h : a ∈ t) : a ∉ s \ t := by simp only [mem_sdiff, h, not_true, not_false_iff, and_false_iff] theorem not_mem_sdiff_of_not_mem_left (h : a ∉ s) : a ∉ s \ t := by simp [h] theorem union_sdiff_of_subset (h : s ⊆ t) : s ∪ t \ s = t := sup_sdiff_cancel_right h theorem sdiff_union_of_subset {s₁ s₂ : Finset α} (h : s₁ ⊆ s₂) : s₂ \ s₁ ∪ s₁ = s₂ := (union_comm _ _).trans (union_sdiff_of_subset h) lemma inter_sdiff_assoc (s t u : Finset α) : (s ∩ t) \ u = s ∩ (t \ u) := by ext x; simp [and_assoc] @[deprecated inter_sdiff_assoc (since := "2024-05-01")] theorem inter_sdiff (s t u : Finset α) : s ∩ (t \ u) = (s ∩ t) \ u := (inter_sdiff_assoc _ _ _).symm @[simp] theorem sdiff_inter_self (s₁ s₂ : Finset α) : s₂ \ s₁ ∩ s₁ = ∅ := inf_sdiff_self_left -- Porting note (#10618): @[simp] can prove this protected theorem sdiff_self (s₁ : Finset α) : s₁ \ s₁ = ∅ := _root_.sdiff_self theorem sdiff_inter_distrib_right (s t u : Finset α) : s \ (t ∩ u) = s \ t ∪ s \ u := sdiff_inf @[simp] theorem sdiff_inter_self_left (s t : Finset α) : s \ (s ∩ t) = s \ t := sdiff_inf_self_left _ _ @[simp] theorem sdiff_inter_self_right (s t : Finset α) : s \ (t ∩ s) = s \ t := sdiff_inf_self_right _ _ @[simp] theorem sdiff_empty : s \ ∅ = s := sdiff_bot @[mono, gcongr] theorem sdiff_subset_sdiff (hst : s ⊆ t) (hvu : v ⊆ u) : s \ u ⊆ t \ v := sdiff_le_sdiff hst hvu @[simp, norm_cast] theorem coe_sdiff (s₁ s₂ : Finset α) : ↑(s₁ \ s₂) = (s₁ \ s₂ : Set α) := Set.ext fun _ => mem_sdiff @[simp] theorem union_sdiff_self_eq_union : s ∪ t \ s = s ∪ t := sup_sdiff_self_right _ _ @[simp] theorem sdiff_union_self_eq_union : s \ t ∪ t = s ∪ t := sup_sdiff_self_left _ _ theorem union_sdiff_left (s t : Finset α) : (s ∪ t) \ s = t \ s := sup_sdiff_left_self theorem union_sdiff_right (s t : Finset α) : (s ∪ t) \ t = s \ t := sup_sdiff_right_self theorem union_sdiff_cancel_left (h : Disjoint s t) : (s ∪ t) \ s = t := h.sup_sdiff_cancel_left theorem union_sdiff_cancel_right (h : Disjoint s t) : (s ∪ t) \ t = s := h.sup_sdiff_cancel_right theorem union_sdiff_symm : s ∪ t \ s = t ∪ s \ t := by simp [union_comm] theorem sdiff_union_inter (s t : Finset α) : s \ t ∪ s ∩ t = s := sup_sdiff_inf _ _ -- Porting note (#10618): @[simp] can prove this theorem sdiff_idem (s t : Finset α) : (s \ t) \ t = s \ t := _root_.sdiff_idem theorem subset_sdiff : s ⊆ t \ u ↔ s ⊆ t ∧ Disjoint s u := le_iff_subset.symm.trans le_sdiff @[simp] theorem sdiff_eq_empty_iff_subset : s \ t = ∅ ↔ s ⊆ t := sdiff_eq_bot_iff theorem sdiff_nonempty : (s \ t).Nonempty ↔ ¬s ⊆ t := nonempty_iff_ne_empty.trans sdiff_eq_empty_iff_subset.not @[simp] theorem empty_sdiff (s : Finset α) : ∅ \ s = ∅ := bot_sdiff theorem insert_sdiff_of_not_mem (s : Finset α) {t : Finset α} {x : α} (h : x ∉ t) : insert x s \ t = insert x (s \ t) := by rw [← coe_inj, coe_insert, coe_sdiff, coe_sdiff, coe_insert] exact Set.insert_diff_of_not_mem _ h theorem insert_sdiff_of_mem (s : Finset α) {x : α} (h : x ∈ t) : insert x s \ t = s \ t := by rw [← coe_inj, coe_sdiff, coe_sdiff, coe_insert] exact Set.insert_diff_of_mem _ h @[simp] lemma insert_sdiff_cancel (ha : a ∉ s) : insert a s \ s = {a} := by rw [insert_sdiff_of_not_mem _ ha, Finset.sdiff_self, insert_emptyc_eq] @[simp] theorem insert_sdiff_insert (s t : Finset α) (x : α) : insert x s \ insert x t = s \ insert x t := insert_sdiff_of_mem _ (mem_insert_self _ _) lemma insert_sdiff_insert' (hab : a ≠ b) (ha : a ∉ s) : insert a s \ insert b s = {a} := by ext; aesop lemma erase_sdiff_erase (hab : a ≠ b) (hb : b ∈ s) : s.erase a \ s.erase b = {b} := by ext; aesop lemma cons_sdiff_cons (hab : a ≠ b) (ha hb) : s.cons a ha \ s.cons b hb = {a} := by rw [cons_eq_insert, cons_eq_insert, insert_sdiff_insert' hab ha] theorem sdiff_insert_of_not_mem {x : α} (h : x ∉ s) (t : Finset α) : s \ insert x t = s \ t := by refine Subset.antisymm (sdiff_subset_sdiff (Subset.refl _) (subset_insert _ _)) fun y hy => ?_ simp only [mem_sdiff, mem_insert, not_or] at hy ⊢ exact ⟨hy.1, fun hxy => h <| hxy ▸ hy.1, hy.2⟩ @[simp] theorem sdiff_subset {s t : Finset α} : s \ t ⊆ s := le_iff_subset.mp sdiff_le theorem sdiff_ssubset (h : t ⊆ s) (ht : t.Nonempty) : s \ t ⊂ s := sdiff_lt (le_iff_subset.mpr h) ht.ne_empty theorem union_sdiff_distrib (s₁ s₂ t : Finset α) : (s₁ ∪ s₂) \ t = s₁ \ t ∪ s₂ \ t := sup_sdiff theorem sdiff_union_distrib (s t₁ t₂ : Finset α) : s \ (t₁ ∪ t₂) = s \ t₁ ∩ (s \ t₂) := sdiff_sup theorem union_sdiff_self (s t : Finset α) : (s ∪ t) \ t = s \ t := sup_sdiff_right_self -- TODO: Do we want to delete this lemma and `Finset.disjUnion_singleton`, -- or instead add `Finset.union_singleton`/`Finset.singleton_union`? theorem sdiff_singleton_eq_erase (a : α) (s : Finset α) : s \ singleton a = erase s a := by ext rw [mem_erase, mem_sdiff, mem_singleton, and_comm] -- This lemma matches `Finset.insert_eq` in functionality. theorem erase_eq (s : Finset α) (a : α) : s.erase a = s \ {a} := (sdiff_singleton_eq_erase _ _).symm theorem disjoint_erase_comm : Disjoint (s.erase a) t ↔ Disjoint s (t.erase a) := by simp_rw [erase_eq, disjoint_sdiff_comm] lemma disjoint_insert_erase (ha : a ∉ t) : Disjoint (s.erase a) (insert a t) ↔ Disjoint s t := by rw [disjoint_erase_comm, erase_insert ha] lemma disjoint_erase_insert (ha : a ∉ s) : Disjoint (insert a s) (t.erase a) ↔ Disjoint s t := by rw [← disjoint_erase_comm, erase_insert ha] theorem disjoint_of_erase_left (ha : a ∉ t) (hst : Disjoint (s.erase a) t) : Disjoint s t := by rw [← erase_insert ha, ← disjoint_erase_comm, disjoint_insert_right] exact ⟨not_mem_erase _ _, hst⟩ theorem disjoint_of_erase_right (ha : a ∉ s) (hst : Disjoint s (t.erase a)) : Disjoint s t := by rw [← erase_insert ha, disjoint_erase_comm, disjoint_insert_left] exact ⟨not_mem_erase _ _, hst⟩ theorem inter_erase (a : α) (s t : Finset α) : s ∩ t.erase a = (s ∩ t).erase a := by simp only [erase_eq, inter_sdiff_assoc] @[simp] theorem erase_inter (a : α) (s t : Finset α) : s.erase a ∩ t = (s ∩ t).erase a := by simpa only [inter_comm t] using inter_erase a t s theorem erase_sdiff_comm (s t : Finset α) (a : α) : s.erase a \ t = (s \ t).erase a := by simp_rw [erase_eq, sdiff_right_comm] theorem insert_union_comm (s t : Finset α) (a : α) : insert a s ∪ t = s ∪ insert a t := by rw [insert_union, union_insert] theorem erase_inter_comm (s t : Finset α) (a : α) : s.erase a ∩ t = s ∩ t.erase a := by rw [erase_inter, inter_erase] theorem erase_union_distrib (s t : Finset α) (a : α) : (s ∪ t).erase a = s.erase a ∪ t.erase a := by simp_rw [erase_eq, union_sdiff_distrib] theorem insert_inter_distrib (s t : Finset α) (a : α) : insert a (s ∩ t) = insert a s ∩ insert a t := by simp_rw [insert_eq, union_inter_distrib_left] theorem erase_sdiff_distrib (s t : Finset α) (a : α) : (s \ t).erase a = s.erase a \ t.erase a := by simp_rw [erase_eq, sdiff_sdiff, sup_sdiff_eq_sup le_rfl, sup_comm] theorem erase_union_of_mem (ha : a ∈ t) (s : Finset α) : s.erase a ∪ t = s ∪ t := by rw [← insert_erase (mem_union_right s ha), erase_union_distrib, ← union_insert, insert_erase ha] theorem union_erase_of_mem (ha : a ∈ s) (t : Finset α) : s ∪ t.erase a = s ∪ t := by rw [← insert_erase (mem_union_left t ha), erase_union_distrib, ← insert_union, insert_erase ha] @[simp] theorem sdiff_singleton_eq_self (ha : a ∉ s) : s \ {a} = s := sdiff_eq_self_iff_disjoint.2 <| by simp [ha] theorem Nontrivial.sdiff_singleton_nonempty {c : α} {s : Finset α} (hS : s.Nontrivial) : (s \ {c}).Nonempty := by rw [Finset.sdiff_nonempty, Finset.subset_singleton_iff] push_neg exact ⟨by rintro rfl; exact Finset.not_nontrivial_empty hS, hS.ne_singleton⟩ theorem sdiff_sdiff_left' (s t u : Finset α) : (s \ t) \ u = s \ t ∩ (s \ u) := _root_.sdiff_sdiff_left' theorem sdiff_union_sdiff_cancel (hts : t ⊆ s) (hut : u ⊆ t) : s \ t ∪ t \ u = s \ u := sdiff_sup_sdiff_cancel hts hut theorem sdiff_union_erase_cancel (hts : t ⊆ s) (ha : a ∈ t) : s \ t ∪ t.erase a = s.erase a := by simp_rw [erase_eq, sdiff_union_sdiff_cancel hts (singleton_subset_iff.2 ha)] theorem sdiff_sdiff_eq_sdiff_union (h : u ⊆ s) : s \ (t \ u) = s \ t ∪ u := sdiff_sdiff_eq_sdiff_sup h theorem sdiff_insert (s t : Finset α) (x : α) : s \ insert x t = (s \ t).erase x := by simp_rw [← sdiff_singleton_eq_erase, insert_eq, sdiff_sdiff_left', sdiff_union_distrib, inter_comm] theorem sdiff_insert_insert_of_mem_of_not_mem {s t : Finset α} {x : α} (hxs : x ∈ s) (hxt : x ∉ t) : insert x (s \ insert x t) = s \ t := by rw [sdiff_insert, insert_erase (mem_sdiff.mpr ⟨hxs, hxt⟩)] theorem sdiff_erase (h : a ∈ s) : s \ t.erase a = insert a (s \ t) := by rw [← sdiff_singleton_eq_erase, sdiff_sdiff_eq_sdiff_union (singleton_subset_iff.2 h), insert_eq, union_comm] theorem sdiff_erase_self (ha : a ∈ s) : s \ s.erase a = {a} := by rw [sdiff_erase ha, Finset.sdiff_self, insert_emptyc_eq] theorem sdiff_sdiff_self_left (s t : Finset α) : s \ (s \ t) = s ∩ t := sdiff_sdiff_right_self theorem sdiff_sdiff_eq_self (h : t ⊆ s) : s \ (s \ t) = t := _root_.sdiff_sdiff_eq_self h theorem sdiff_eq_sdiff_iff_inter_eq_inter {s t₁ t₂ : Finset α} : s \ t₁ = s \ t₂ ↔ s ∩ t₁ = s ∩ t₂ := sdiff_eq_sdiff_iff_inf_eq_inf theorem union_eq_sdiff_union_sdiff_union_inter (s t : Finset α) : s ∪ t = s \ t ∪ t \ s ∪ s ∩ t := sup_eq_sdiff_sup_sdiff_sup_inf theorem erase_eq_empty_iff (s : Finset α) (a : α) : s.erase a = ∅ ↔ s = ∅ ∨ s = {a} := by rw [← sdiff_singleton_eq_erase, sdiff_eq_empty_iff_subset, subset_singleton_iff] --TODO@Yaël: Kill lemmas duplicate with `BooleanAlgebra` theorem sdiff_disjoint : Disjoint (t \ s) s := disjoint_left.2 fun _a ha => (mem_sdiff.1 ha).2 theorem disjoint_sdiff : Disjoint s (t \ s) := sdiff_disjoint.symm theorem disjoint_sdiff_inter (s t : Finset α) : Disjoint (s \ t) (s ∩ t) := disjoint_of_subset_right inter_subset_right sdiff_disjoint theorem sdiff_eq_self_iff_disjoint : s \ t = s ↔ Disjoint s t := sdiff_eq_self_iff_disjoint' theorem sdiff_eq_self_of_disjoint (h : Disjoint s t) : s \ t = s := sdiff_eq_self_iff_disjoint.2 h end Sdiff /-! ### Symmetric difference -/ section SymmDiff open scoped symmDiff variable [DecidableEq α] {s t : Finset α} {a b : α} theorem mem_symmDiff : a ∈ s ∆ t ↔ a ∈ s ∧ a ∉ t ∨ a ∈ t ∧ a ∉ s := by simp_rw [symmDiff, sup_eq_union, mem_union, mem_sdiff] @[simp, norm_cast] theorem coe_symmDiff : (↑(s ∆ t) : Set α) = (s : Set α) ∆ t := Set.ext fun x => by simp [mem_symmDiff, Set.mem_symmDiff] @[simp] lemma symmDiff_eq_empty : s ∆ t = ∅ ↔ s = t := symmDiff_eq_bot @[simp] lemma symmDiff_nonempty : (s ∆ t).Nonempty ↔ s ≠ t := nonempty_iff_ne_empty.trans symmDiff_eq_empty.not end SymmDiff /-! ### 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 } := ⟨Multiset.attach s.1, nodup_attach.2 s.2⟩ theorem sizeOf_lt_sizeOf_of_mem [SizeOf α] {x : α} {s : Finset α} (hx : x ∈ s) : SizeOf.sizeOf x < SizeOf.sizeOf s := by cases s dsimp [SizeOf.sizeOf, SizeOf.sizeOf, Multiset.sizeOf] rw [add_comm] refine lt_trans ?_ (Nat.lt_succ_self _) exact Multiset.sizeOf_lt_sizeOf_of_mem hx @[simp] theorem attach_val (s : Finset α) : s.attach.1 = s.1.attach := rfl @[simp] theorem mem_attach (s : Finset α) : ∀ x, x ∈ s.attach := Multiset.mem_attach _ @[simp] theorem attach_empty : attach (∅ : Finset α) = ∅ := rfl @[simp, aesop safe apply (rule_sets := [finsetNonempty])] theorem attach_nonempty_iff {s : Finset α} : s.attach.Nonempty ↔ s.Nonempty := by simp [Finset.Nonempty] protected alias ⟨_, Nonempty.attach⟩ := attach_nonempty_iff @[simp] theorem attach_eq_empty_iff {s : Finset α} : s.attach = ∅ ↔ s = ∅ := by simp [eq_empty_iff_forall_not_mem] section DecidablePiExists variable {s : Finset α} instance decidableDforallFinset {p : ∀ a ∈ s, Prop} [_hp : ∀ (a) (h : a ∈ s), Decidable (p a h)] : Decidable (∀ (a) (h : a ∈ s), p a h) := Multiset.decidableDforallMultiset -- Porting note: In lean3, `decidableDforallFinset` was picked up when decidability of `s ⊆ t` was -- needed. In lean4 it seems this is not the case. instance instDecidableRelSubset [DecidableEq α] : @DecidableRel (Finset α) (· ⊆ ·) := fun _ _ ↦ decidableDforallFinset instance instDecidableRelSSubset [DecidableEq α] : @DecidableRel (Finset α) (· ⊂ ·) := fun _ _ ↦ instDecidableAnd instance instDecidableLE [DecidableEq α] : @DecidableRel (Finset α) (· ≤ ·) := instDecidableRelSubset instance instDecidableLT [DecidableEq α] : @DecidableRel (Finset α) (· < ·) := instDecidableRelSSubset instance decidableDExistsFinset {p : ∀ a ∈ s, Prop} [_hp : ∀ (a) (h : a ∈ s), Decidable (p a h)] : Decidable (∃ (a : _) (h : a ∈ s), p a h) := Multiset.decidableDexistsMultiset instance decidableExistsAndFinset {p : α → Prop} [_hp : ∀ (a), Decidable (p a)] : Decidable (∃ a ∈ s, p a) := decidable_of_iff (∃ (a : _) (_ : a ∈ s), p a) (by simp) instance decidableExistsAndFinsetCoe {p : α → Prop} [DecidablePred p] : Decidable (∃ a ∈ (s : Set α), p a) := decidableExistsAndFinset /-- decidable equality for functions whose domain is bounded by finsets -/ instance decidableEqPiFinset {β : α → Type*} [_h : ∀ a, DecidableEq (β a)] : DecidableEq (∀ a ∈ s, β a) := Multiset.decidableEqPiMultiset end DecidablePiExists /-! ### filter -/ section Filter variable (p q : α → Prop) [DecidablePred p] [DecidablePred q] {s t : Finset α} /-- `Finset.filter p s` is the set of elements of `s` that satisfy `p`. For example, one can use `s.filter (· ∈ t)` to get the intersection of `s` with `t : Set α` as a `Finset α` (when a `DecidablePred (· ∈ t)` instance is available). -/ def filter (s : Finset α) : Finset α := ⟨_, s.2.filter p⟩ @[simp] theorem filter_val (s : Finset α) : (filter p s).1 = s.1.filter p := rfl @[simp] theorem filter_subset (s : Finset α) : s.filter p ⊆ s := Multiset.filter_subset _ _ variable {p} @[simp] theorem mem_filter {s : Finset α} {a : α} : a ∈ s.filter p ↔ a ∈ s ∧ p a := Multiset.mem_filter theorem mem_of_mem_filter {s : Finset α} (x : α) (h : x ∈ s.filter p) : x ∈ s := Multiset.mem_of_mem_filter h theorem filter_ssubset {s : Finset α} : s.filter p ⊂ s ↔ ∃ x ∈ s, ¬p x := ⟨fun h => let ⟨x, hs, hp⟩ := Set.exists_of_ssubset h ⟨x, hs, mt (fun hp => mem_filter.2 ⟨hs, hp⟩) hp⟩, fun ⟨_, hs, hp⟩ => ⟨s.filter_subset _, fun h => hp (mem_filter.1 (h hs)).2⟩⟩ variable (p) theorem filter_filter (s : Finset α) : (s.filter p).filter q = s.filter fun a => p a ∧ q a := ext fun a => by simp only [mem_filter, and_assoc, Bool.decide_and, Bool.decide_coe, Bool.and_eq_true] theorem filter_comm (s : Finset α) : (s.filter p).filter q = (s.filter q).filter p := by simp_rw [filter_filter, and_comm] -- We can replace an application of filter where the decidability is inferred in "the wrong way". theorem filter_congr_decidable (s : Finset α) (p : α → Prop) (h : DecidablePred p) [DecidablePred p] : @filter α p h s = s.filter p := by congr @[simp] theorem filter_True {h} (s : Finset α) : @filter _ (fun _ => True) h s = s := by ext; simp @[simp] theorem filter_False {h} (s : Finset α) : @filter _ (fun _ => False) h s = ∅ := by ext; simp variable {p q} lemma filter_eq_self : s.filter p = s ↔ ∀ x ∈ s, p x := by simp [Finset.ext_iff] theorem filter_eq_empty_iff : s.filter p = ∅ ↔ ∀ ⦃x⦄, x ∈ s → ¬p x := by simp [Finset.ext_iff] theorem filter_nonempty_iff : (s.filter p).Nonempty ↔ ∃ a ∈ s, p a := by simp only [nonempty_iff_ne_empty, Ne, filter_eq_empty_iff, Classical.not_not, not_forall, exists_prop] /-- If all elements of a `Finset` satisfy the predicate `p`, `s.filter p` is `s`. -/ theorem filter_true_of_mem (h : ∀ x ∈ s, p x) : s.filter p = s := filter_eq_self.2 h /-- If all elements of a `Finset` fail to satisfy the predicate `p`, `s.filter p` is `∅`. -/ theorem filter_false_of_mem (h : ∀ x ∈ s, ¬p x) : s.filter p = ∅ := filter_eq_empty_iff.2 h @[simp] theorem filter_const (p : Prop) [Decidable p] (s : Finset α) : (s.filter fun _a => p) = if p then s else ∅ := by split_ifs <;> simp [*] theorem filter_congr {s : Finset α} (H : ∀ x ∈ s, p x ↔ q x) : filter p s = filter q s := eq_of_veq <| Multiset.filter_congr H variable (p q) @[simp] theorem filter_empty : filter p ∅ = ∅ := subset_empty.1 <| filter_subset _ _ @[gcongr] theorem filter_subset_filter {s t : Finset α} (h : s ⊆ t) : s.filter p ⊆ t.filter p := fun _a ha => mem_filter.2 ⟨h (mem_filter.1 ha).1, (mem_filter.1 ha).2⟩ theorem monotone_filter_left : Monotone (filter p) := fun _ _ => filter_subset_filter p @[gcongr] theorem monotone_filter_right (s : Finset α) ⦃p q : α → Prop⦄ [DecidablePred p] [DecidablePred q] (h : p ≤ q) : s.filter p ⊆ s.filter q := Multiset.subset_of_le (Multiset.monotone_filter_right s.val h) @[simp, norm_cast] theorem coe_filter (s : Finset α) : ↑(s.filter p) = ({ x ∈ ↑s | p x } : Set α) := Set.ext fun _ => mem_filter theorem subset_coe_filter_of_subset_forall (s : Finset α) {t : Set α} (h₁ : t ⊆ s) (h₂ : ∀ x ∈ t, p x) : t ⊆ s.filter p := fun x hx => (s.coe_filter p).symm ▸ ⟨h₁ hx, h₂ x hx⟩ theorem filter_singleton (a : α) : filter p {a} = if p a then {a} else ∅ := by classical ext x simp only [mem_singleton, forall_eq, mem_filter] split_ifs with h <;> by_cases h' : x = a <;> simp [h, h'] theorem filter_cons_of_pos (a : α) (s : Finset α) (ha : a ∉ s) (hp : p a) : filter p (cons a s ha) = cons a (filter p s) (mem_filter.not.mpr <| mt And.left ha) := eq_of_veq <| Multiset.filter_cons_of_pos s.val hp theorem filter_cons_of_neg (a : α) (s : Finset α) (ha : a ∉ s) (hp : ¬p a) : filter p (cons a s ha) = filter p s := eq_of_veq <| Multiset.filter_cons_of_neg s.val hp theorem disjoint_filter {s : Finset α} {p q : α → Prop} [DecidablePred p] [DecidablePred q] : Disjoint (s.filter p) (s.filter q) ↔ ∀ x ∈ s, p x → ¬q x := by constructor <;> simp (config := { contextual := true }) [disjoint_left] theorem disjoint_filter_filter {s t : Finset α} {p q : α → Prop} [DecidablePred p] [DecidablePred q] : Disjoint s t → Disjoint (s.filter p) (t.filter q) := Disjoint.mono (filter_subset _ _) (filter_subset _ _) theorem disjoint_filter_filter' (s t : Finset α) {p q : α → Prop} [DecidablePred p] [DecidablePred q] (h : Disjoint p q) : Disjoint (s.filter p) (t.filter q) := by simp_rw [disjoint_left, mem_filter] rintro a ⟨_, hp⟩ ⟨_, hq⟩ rw [Pi.disjoint_iff] at h simpa [hp, hq] using h a theorem disjoint_filter_filter_neg (s t : Finset α) (p : α → Prop) [DecidablePred p] [∀ x, Decidable (¬p x)] : Disjoint (s.filter p) (t.filter fun a => ¬p a) := disjoint_filter_filter' s t disjoint_compl_right theorem filter_disj_union (s : Finset α) (t : Finset α) (h : Disjoint s t) : filter p (disjUnion s t h) = (filter p s).disjUnion (filter p t) (disjoint_filter_filter h) := eq_of_veq <| Multiset.filter_add _ _ _ lemma _root_.Set.pairwiseDisjoint_filter [DecidableEq β] (f : α → β) (s : Set β) (t : Finset α) : s.PairwiseDisjoint fun x ↦ t.filter (f · = x) := by rintro i - j - h u hi hj x hx obtain ⟨-, rfl⟩ : x ∈ t ∧ f x = i := by simpa using hi hx obtain ⟨-, rfl⟩ : x ∈ t ∧ f x = j := by simpa using hj hx contradiction theorem filter_cons {a : α} (s : Finset α) (ha : a ∉ s) : filter p (cons a s ha) = (if p a then {a} else ∅ : Finset α).disjUnion (filter p s) (by split_ifs · rw [disjoint_singleton_left] exact mem_filter.not.mpr <| mt And.left ha · exact disjoint_empty_left _) := by split_ifs with h · rw [filter_cons_of_pos _ _ _ ha h, singleton_disjUnion] · rw [filter_cons_of_neg _ _ _ ha h, empty_disjUnion] section variable [DecidableEq α] theorem filter_union (s₁ s₂ : Finset α) : (s₁ ∪ s₂).filter p = s₁.filter p ∪ s₂.filter p := ext fun _ => by simp only [mem_filter, mem_union, or_and_right] theorem filter_union_right (s : Finset α) : s.filter p ∪ s.filter q = s.filter fun x => p x ∨ q x := ext fun x => by simp [mem_filter, mem_union, ← and_or_left] theorem filter_mem_eq_inter {s t : Finset α} [∀ i, Decidable (i ∈ t)] : (s.filter fun i => i ∈ t) = s ∩ t := ext fun i => by simp [mem_filter, mem_inter] theorem filter_inter_distrib (s t : Finset α) : (s ∩ t).filter p = s.filter p ∩ t.filter p := by ext simp [mem_filter, mem_inter, and_assoc] 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 split_ifs with h <;> by_cases h' : x = a <;> simp [h, h'] theorem filter_erase (a : α) (s : Finset α) : filter p (erase s a) = erase (filter p s) a := by ext x simp only [and_assoc, mem_filter, iff_self_iff, mem_erase] theorem filter_or (s : Finset α) : (s.filter fun a => p a ∨ q a) = s.filter p ∪ s.filter q := ext fun _ => by simp [mem_filter, mem_union, and_or_left] theorem filter_and (s : Finset α) : (s.filter fun a => p a ∧ q a) = s.filter p ∩ s.filter q := ext fun _ => by simp [mem_filter, mem_inter, and_comm, and_left_comm, and_self_iff, and_assoc] theorem filter_not (s : Finset α) : (s.filter fun a => ¬p a) = s \ s.filter p := ext fun a => by simp only [Bool.decide_coe, Bool.not_eq_true', mem_filter, and_comm, mem_sdiff, not_and_or, Bool.not_eq_true, and_or_left, and_not_self, or_false] lemma filter_and_not (s : Finset α) (p q : α → Prop) [DecidablePred p] [DecidablePred q] : s.filter (fun a ↦ p a ∧ ¬ q a) = s.filter p \ s.filter q := by rw [filter_and, filter_not, ← inter_sdiff_assoc, inter_eq_left.2 (filter_subset _ _)] theorem sdiff_eq_filter (s₁ s₂ : Finset α) : s₁ \ s₂ = filter (· ∉ s₂) s₁ := ext fun _ => by simp [mem_sdiff, mem_filter] theorem sdiff_eq_self (s₁ s₂ : Finset α) : s₁ \ s₂ = s₁ ↔ s₁ ∩ s₂ ⊆ ∅ := by simp [Subset.antisymm_iff, disjoint_iff_inter_eq_empty] theorem subset_union_elim {s : Finset α} {t₁ t₂ : Set α} (h : ↑s ⊆ t₁ ∪ t₂) : ∃ s₁ s₂ : Finset α, s₁ ∪ s₂ = s ∧ ↑s₁ ⊆ t₁ ∧ ↑s₂ ⊆ t₂ \ t₁ := by classical refine ⟨s.filter (· ∈ t₁), s.filter (· ∉ t₁), ?_, ?_, ?_⟩ · simp [filter_union_right, em] · intro x simp · intro x simp only [not_not, coe_filter, Set.mem_setOf_eq, Set.mem_diff, and_imp] intro hx hx₂ exact ⟨Or.resolve_left (h hx) hx₂, hx₂⟩ section Classical open scoped Classical -- Porting note: The notation `{ x ∈ s | p x }` in Lean 4 is hardcoded to be about `Set`. -- So at the moment the whole `Sep`-class is useless, as it doesn't have notation. -- /-- The following instance allows us to write `{x ∈ s | p x}` for `Finset.filter p s`. -- We don't want to redo all lemmas of `Finset.filter` for `Sep.sep`, so we make sure that `simp` -- unfolds the notation `{x ∈ s | p x}` to `Finset.filter p s`. -- -/ -- noncomputable instance {α : Type*} : Sep α (Finset α) := -- ⟨fun p x => x.filter p⟩ -- -- @[simp] -- Porting note: not a simp-lemma until `Sep`-notation is fixed. -- theorem sep_def {α : Type*} (s : Finset α) (p : α → Prop) : { x ∈ s | p x } = s.filter p := by -- ext -- simp end Classical -- This is not a good simp lemma, as it would prevent `Finset.mem_filter` from firing -- on, e.g. `x ∈ s.filter (Eq b)`. /-- 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. -/ theorem filter_eq [DecidableEq β] (s : Finset β) (b : β) : s.filter (Eq b) = ite (b ∈ s) {b} ∅ := by split_ifs with h · ext simp only [mem_filter, mem_singleton, decide_eq_true_eq] refine ⟨fun h => h.2.symm, ?_⟩ rintro rfl exact ⟨h, rfl⟩ · ext simp only [mem_filter, not_and, iff_false_iff, not_mem_empty, decide_eq_true_eq] rintro m rfl exact h m /-- 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. -/ theorem filter_eq' [DecidableEq β] (s : Finset β) (b : β) : (s.filter fun a => a = b) = ite (b ∈ s) {b} ∅ := _root_.trans (filter_congr fun _ _ => by simp_rw [@eq_comm _ b]) (filter_eq s b) theorem filter_ne [DecidableEq β] (s : Finset β) (b : β) : (s.filter fun a => b ≠ a) = s.erase b := by ext simp only [mem_filter, mem_erase, Ne, decide_not, Bool.not_eq_true', decide_eq_false_iff_not] tauto theorem filter_ne' [DecidableEq β] (s : Finset β) (b : β) : (s.filter fun a => a ≠ b) = s.erase b := _root_.trans (filter_congr fun _ _ => by simp_rw [@ne_comm _ b]) (filter_ne s b) theorem filter_inter_filter_neg_eq (s t : Finset α) : (s.filter p ∩ t.filter fun a => ¬p a) = ∅ := by simpa using (disjoint_filter_filter_neg s t p).eq_bot theorem filter_union_filter_of_codisjoint (s : Finset α) (h : Codisjoint p q) : s.filter p ∪ s.filter q = s := (filter_or _ _ _).symm.trans <| filter_true_of_mem fun x _ => h.top_le x trivial theorem filter_union_filter_neg_eq [∀ x, Decidable (¬p x)] (s : Finset α) : (s.filter p ∪ s.filter fun a => ¬p a) = s := filter_union_filter_of_codisjoint _ _ _ <| @codisjoint_hnot_right _ _ p end lemma filter_inj : s.filter p = t.filter p ↔ ∀ ⦃a⦄, p a → (a ∈ s ↔ a ∈ t) := by simp [ext_iff] lemma filter_inj' : s.filter p = s.filter q ↔ ∀ ⦃a⦄, a ∈ s → (p a ↔ q a) := by simp [ext_iff] end Filter /-! ### range -/ section Range variable {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 := Multiset.mem_range @[simp, norm_cast] theorem coe_range (n : ℕ) : (range n : Set ℕ) = Set.Iio n := Set.ext fun _ => 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 <| (Multiset.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 -- Porting note (#10618): @[simp] can prove this theorem not_mem_range_self : n ∉ range n := Multiset.not_mem_range_self -- Porting note (#10618): @[simp] can prove this theorem self_mem_range_succ (n : ℕ) : n ∈ range (n + 1) := Multiset.self_mem_range_succ n @[simp] theorem range_subset {n m} : range n ⊆ range m ↔ n ≤ m := Multiset.range_subset theorem range_mono : Monotone range := fun _ _ => range_subset.2 @[gcongr] alias ⟨_, _root_.GCongr.finset_range_subset_of_le⟩ := range_subset theorem mem_range_succ_iff {a b : ℕ} : a ∈ Finset.range b.succ ↔ a ≤ b := Finset.mem_range.trans Nat.lt_succ_iff theorem mem_range_le {n x : ℕ} (hx : x ∈ range n) : x ≤ n := (mem_range.1 hx).le theorem mem_range_sub_ne_zero {n x : ℕ} (hx : x ∈ range n) : n - x ≠ 0 := _root_.ne_of_gt <| Nat.sub_pos_of_lt <| mem_range.1 hx @[simp, aesop safe apply (rule_sets := [finsetNonempty])] theorem nonempty_range_iff : (range n).Nonempty ↔ n ≠ 0 := ⟨fun ⟨k, hk⟩ => (k.zero_le.trans_lt <| mem_range.1 hk).ne', fun h => ⟨0, mem_range.2 <| Nat.pos_iff_ne_zero.2 h⟩⟩ @[simp] theorem range_eq_empty_iff : range n = ∅ ↔ n = 0 := by rw [← not_nonempty_iff_eq_empty, nonempty_range_iff, not_not] theorem nonempty_range_succ : (range <| n + 1).Nonempty := nonempty_range_iff.2 n.succ_ne_zero @[simp] theorem range_filter_eq {n m : ℕ} : (range n).filter (· = m) = if m < n then {m} else ∅ := by convert filter_eq (range n) m using 2 · ext rw [eq_comm] · simp lemma range_nontrivial {n : ℕ} (hn : 1 < n) : (Finset.range n).Nontrivial := by rw [Finset.Nontrivial, Finset.coe_range] exact ⟨0, Nat.zero_lt_one.trans hn, 1, hn, zero_ne_one⟩ 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_iff, exists_false] theorem exists_mem_insert [DecidableEq α] (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_right, exists_or, exists_eq_left] theorem forall_mem_empty_iff (p : α → Prop) : (∀ x, x ∈ (∅ : Finset α) → p x) ↔ True := iff_true_intro fun _ h => False.elim <| not_mem_empty _ h theorem forall_mem_insert [DecidableEq α] (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, forall_and, forall_eq] /-- Useful in proofs by induction. -/ theorem forall_of_forall_insert [DecidableEq α] {p : α → Prop} {a : α} {s : Finset α} (H : ∀ x, x ∈ insert a s → p x) (x) (h : x ∈ s) : p x := H _ <| mem_insert_of_mem h end Finset /-- Equivalence between the set of natural numbers which are `≥ k` and `ℕ`, given by `n → n - k`. -/ def notMemRangeEquiv (k : ℕ) : { n // n ∉ range k } ≃ ℕ where toFun i := i.1 - k invFun j := ⟨j + k, by simp⟩ left_inv j := by rw [Subtype.ext_iff_val] apply Nat.sub_add_cancel simpa using j.2 right_inv j := Nat.add_sub_cancel_right _ _ @[simp] theorem coe_notMemRangeEquiv (k : ℕ) : (notMemRangeEquiv k : { n // n ∉ range k } → ℕ) = fun (i : { n // n ∉ range k }) => i - k := rfl @[simp] theorem coe_notMemRangeEquiv_symm (k : ℕ) : ((notMemRangeEquiv k).symm : ℕ → { n // n ∉ range k }) = fun j => ⟨j + k, by simp⟩ := rfl /-! ### dedup on list and multiset -/ namespace Multiset variable [DecidableEq α] {s t : Multiset α} /-- `toFinset s` removes duplicates from the multiset `s` to produce a finset. -/ def toFinset (s : Multiset α) : Finset α := ⟨_, nodup_dedup s⟩ @[simp] theorem toFinset_val (s : Multiset α) : s.toFinset.1 = s.dedup := rfl theorem toFinset_eq {s : Multiset α} (n : Nodup s) : Finset.mk s n = s.toFinset := Finset.val_inj.1 n.dedup.symm theorem Nodup.toFinset_inj {l l' : Multiset α} (hl : Nodup l) (hl' : Nodup l') (h : l.toFinset = l'.toFinset) : l = l' := by simpa [← toFinset_eq hl, ← toFinset_eq hl'] using h @[simp] theorem mem_toFinset {a : α} {s : Multiset α} : a ∈ s.toFinset ↔ a ∈ s := mem_dedup @[simp] theorem toFinset_zero : toFinset (0 : Multiset α) = ∅ := rfl @[simp] theorem toFinset_cons (a : α) (s : Multiset α) : toFinset (a ::ₘ s) = insert a (toFinset s) := Finset.eq_of_veq dedup_cons @[simp] theorem toFinset_singleton (a : α) : toFinset ({a} : Multiset α) = {a} := by rw [← cons_zero, toFinset_cons, toFinset_zero, LawfulSingleton.insert_emptyc_eq] @[simp] theorem toFinset_add (s t : Multiset α) : toFinset (s + t) = toFinset s ∪ toFinset t := Finset.ext <| by simp @[simp] theorem toFinset_nsmul (s : Multiset α) : ∀ n ≠ 0, (n • s).toFinset = s.toFinset | 0, h => by contradiction | n + 1, _ => by by_cases h : n = 0 · rw [h, zero_add, one_nsmul] · rw [add_nsmul, toFinset_add, one_nsmul, toFinset_nsmul s n h, Finset.union_idempotent] theorem toFinset_eq_singleton_iff (s : Multiset α) (a : α) : s.toFinset = {a} ↔ card s ≠ 0 ∧ s = card s • {a} := by refine ⟨fun H ↦ ⟨fun h ↦ ?_, ext' fun x ↦ ?_⟩, fun H ↦ ?_⟩ · rw [card_eq_zero.1 h, toFinset_zero] at H exact Finset.singleton_ne_empty _ H.symm · rw [count_nsmul, count_singleton] by_cases hx : x = a · simp_rw [hx, ite_true, mul_one, count_eq_card] intro y hy rw [← mem_toFinset, H, Finset.mem_singleton] at hy exact hy.symm have hx' : x ∉ s := fun h' ↦ hx <| by rwa [← mem_toFinset, H, Finset.mem_singleton] at h' simp_rw [count_eq_zero_of_not_mem hx', hx, ite_false, Nat.mul_zero] simpa only [toFinset_nsmul _ _ H.1, toFinset_singleton] using congr($(H.2).toFinset) @[simp] theorem toFinset_inter (s t : Multiset α) : toFinset (s ∩ t) = toFinset s ∩ toFinset t := Finset.ext <| by simp @[simp] theorem toFinset_union (s t : Multiset α) : (s ∪ t).toFinset = s.toFinset ∪ t.toFinset := by ext; simp @[simp] theorem toFinset_eq_empty {m : Multiset α} : m.toFinset = ∅ ↔ m = 0 := Finset.val_inj.symm.trans Multiset.dedup_eq_zero @[simp, aesop safe apply (rule_sets := [finsetNonempty])] theorem toFinset_nonempty : s.toFinset.Nonempty ↔ s ≠ 0 := by simp only [toFinset_eq_empty, Ne, Finset.nonempty_iff_ne_empty] @[simp] theorem toFinset_subset : s.toFinset ⊆ t.toFinset ↔ s ⊆ t := by simp only [Finset.subset_iff, Multiset.subset_iff, Multiset.mem_toFinset] @[simp] theorem toFinset_ssubset : s.toFinset ⊂ t.toFinset ↔ s ⊂ t := by simp_rw [Finset.ssubset_def, toFinset_subset] rfl @[simp] theorem toFinset_dedup (m : Multiset α) : m.dedup.toFinset = m.toFinset := by simp_rw [toFinset, dedup_idem] -- @[simp] -- theorem toFinset_bind_dedup [DecidableEq β] (m : Multiset α) (f : α → Multiset β) : -- (m.dedup.bind f).toFinset = (m.bind f).toFinset := by simp_rw [toFinset, dedup_bind_dedup] @[simp] theorem toFinset_filter (s : Multiset α) (p : α → Prop) [DecidablePred p] : Multiset.toFinset (s.filter p) = s.toFinset.filter p := by ext; simp instance isWellFounded_ssubset : IsWellFounded (Multiset β) (· ⊂ ·) := by classical exact Subrelation.isWellFounded (InvImage _ toFinset) toFinset_ssubset.2 end Multiset namespace Finset @[simp] theorem val_toFinset [DecidableEq α] (s : Finset α) : s.val.toFinset = s := by ext rw [Multiset.mem_toFinset, ← mem_def] theorem val_le_iff_val_subset {a : Finset α} {b : Multiset α} : a.val ≤ b ↔ a.val ⊆ b := Multiset.le_iff_subset a.nodup end Finset namespace List variable [DecidableEq α] {l l' : List α} {a : α} /-- `toFinset l` removes duplicates from the list `l` to produce a finset. -/ def toFinset (l : List α) : Finset α := Multiset.toFinset l @[simp] theorem toFinset_val (l : List α) : l.toFinset.1 = (l.dedup : Multiset α) := rfl @[simp] theorem toFinset_coe (l : List α) : (l : Multiset α).toFinset = l.toFinset := rfl theorem toFinset_eq (n : Nodup l) : @Finset.mk α l n = l.toFinset := Multiset.toFinset_eq <| by rwa [Multiset.coe_nodup] @[simp] theorem mem_toFinset : a ∈ l.toFinset ↔ a ∈ l := mem_dedup @[simp, norm_cast] theorem coe_toFinset (l : List α) : (l.toFinset : Set α) = { a | a ∈ l } := Set.ext fun _ => List.mem_toFinset @[simp] theorem toFinset_nil : toFinset (@nil α) = ∅ := rfl @[simp] theorem toFinset_cons : toFinset (a :: l) = insert a (toFinset l) := Finset.eq_of_veq <| by by_cases h : a ∈ l <;> simp [Finset.insert_val', Multiset.dedup_cons, h] theorem toFinset_surj_on : Set.SurjOn toFinset { l : List α | l.Nodup } Set.univ := by rintro ⟨⟨l⟩, hl⟩ _ exact ⟨l, hl, (toFinset_eq hl).symm⟩ theorem toFinset_surjective : Surjective (toFinset : List α → Finset α) := fun s => let ⟨l, _, hls⟩ := toFinset_surj_on (Set.mem_univ s) ⟨l, hls⟩ theorem toFinset_eq_iff_perm_dedup : l.toFinset = l'.toFinset ↔ l.dedup ~ l'.dedup := by simp [Finset.ext_iff, perm_ext_iff_of_nodup (nodup_dedup _) (nodup_dedup _)] theorem toFinset.ext_iff {a b : List α} : a.toFinset = b.toFinset ↔ ∀ x, x ∈ a ↔ x ∈ b := by simp only [Finset.ext_iff, mem_toFinset] theorem toFinset.ext : (∀ x, x ∈ l ↔ x ∈ l') → l.toFinset = l'.toFinset := toFinset.ext_iff.mpr theorem toFinset_eq_of_perm (l l' : List α) (h : l ~ l') : l.toFinset = l'.toFinset := toFinset_eq_iff_perm_dedup.mpr h.dedup theorem perm_of_nodup_nodup_toFinset_eq (hl : Nodup l) (hl' : Nodup l') (h : l.toFinset = l'.toFinset) : l ~ l' := by rw [← Multiset.coe_eq_coe] exact Multiset.Nodup.toFinset_inj hl hl' h @[simp] theorem toFinset_append : toFinset (l ++ l') = l.toFinset ∪ l'.toFinset := by induction' l with hd tl hl · simp · simp [hl] @[simp] theorem toFinset_reverse {l : List α} : toFinset l.reverse = l.toFinset := toFinset_eq_of_perm _ _ (reverse_perm l) theorem toFinset_replicate_of_ne_zero {n : ℕ} (hn : n ≠ 0) : (List.replicate n a).toFinset = {a} := by ext x simp [hn, List.mem_replicate] @[simp] theorem toFinset_union (l l' : List α) : (l ∪ l').toFinset = l.toFinset ∪ l'.toFinset := by ext simp @[simp] theorem toFinset_inter (l l' : List α) : (l ∩ l').toFinset = l.toFinset ∩ l'.toFinset := by ext simp @[simp] theorem toFinset_eq_empty_iff (l : List α) : l.toFinset = ∅ ↔ l = nil := by cases l <;> simp @[simp, aesop safe apply (rule_sets := [finsetNonempty])] theorem toFinset_nonempty_iff (l : List α) : l.toFinset.Nonempty ↔ l ≠ [] := by simp [Finset.nonempty_iff_ne_empty] @[simp] theorem toFinset_filter (s : List α) (p : α → Bool) : (s.filter p).toFinset = s.toFinset.filter (p ·) := by ext; simp [List.mem_filter] end List namespace Finset section ToList /-- Produce a list of the elements in the finite set using choice. -/ noncomputable def toList (s : Finset α) : List α := s.1.toList theorem nodup_toList (s : Finset α) : s.toList.Nodup := by rw [toList, ← Multiset.coe_nodup, Multiset.coe_toList] exact s.nodup @[simp] theorem mem_toList {a : α} {s : Finset α} : a ∈ s.toList ↔ a ∈ s := Multiset.mem_toList @[simp] theorem toList_eq_nil {s : Finset α} : s.toList = [] ↔ s = ∅ := Multiset.toList_eq_nil.trans val_eq_zero theorem empty_toList {s : Finset α} : s.toList.isEmpty ↔ s = ∅ := by simp @[simp] theorem toList_empty : (∅ : Finset α).toList = [] := toList_eq_nil.mpr rfl theorem Nonempty.toList_ne_nil {s : Finset α} (hs : s.Nonempty) : s.toList ≠ [] := mt toList_eq_nil.mp hs.ne_empty theorem Nonempty.not_empty_toList {s : Finset α} (hs : s.Nonempty) : ¬s.toList.isEmpty := mt empty_toList.mp hs.ne_empty @[simp, norm_cast] theorem coe_toList (s : Finset α) : (s.toList : Multiset α) = s.val := s.val.coe_toList @[simp] theorem toList_toFinset [DecidableEq α] (s : Finset α) : s.toList.toFinset = s := by ext simp @[simp] theorem toList_eq_singleton_iff {a : α} {s : Finset α} : s.toList = [a] ↔ s = {a} := by rw [toList, Multiset.toList_eq_singleton_iff, val_eq_singleton_iff] @[simp] theorem toList_singleton : ∀ a, ({a} : Finset α).toList = [a] := Multiset.toList_singleton theorem exists_list_nodup_eq [DecidableEq α] (s : Finset α) : ∃ l : List α, l.Nodup ∧ l.toFinset = s := ⟨s.toList, s.nodup_toList, s.toList_toFinset⟩ open scoped List in theorem toList_cons {a : α} {s : Finset α} (h : a ∉ s) : (cons a s h).toList ~ a :: s.toList := (List.perm_ext_iff_of_nodup (nodup_toList _) (by simp [h, nodup_toList s])).2 fun x => by simp only [List.mem_cons, Finset.mem_toList, Finset.mem_cons] open scoped List in theorem toList_insert [DecidableEq α] {a : α} {s : Finset α} (h : a ∉ s) : (insert a s).toList ~ a :: s.toList := cons_eq_insert _ _ h ▸ toList_cons _ end ToList /-! ### choose -/ section Choose variable (p : α → Prop) [DecidablePred 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 chooseX (hp : ∃! a, a ∈ l ∧ p a) : { a // a ∈ l ∧ p a } := Multiset.chooseX 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) : α := chooseX p l hp theorem choose_spec (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) := (chooseX p l hp).property theorem choose_mem (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1 theorem choose_property (hp : ∃! a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2 end Choose section Pairwise variable {s : Finset α} theorem pairwise_subtype_iff_pairwise_finset' (r : β → β → Prop) (f : α → β) : Pairwise (r on fun x : s => f x) ↔ (s : Set α).Pairwise (r on f) := pairwise_subtype_iff_pairwise_set (s : Set α) (r on f) theorem pairwise_subtype_iff_pairwise_finset (r : α → α → Prop) : Pairwise (r on fun x : s => x) ↔ (s : Set α).Pairwise r := pairwise_subtype_iff_pairwise_finset' r id theorem pairwise_cons' {a : α} (ha : a ∉ s) (r : β → β → Prop) (f : α → β) : Pairwise (r on fun a : s.cons a ha => f a) ↔ Pairwise (r on fun a : s => f a) ∧ ∀ b ∈ s, r (f a) (f b) ∧ r (f b) (f a) := by simp only [pairwise_subtype_iff_pairwise_finset', Finset.coe_cons, Set.pairwise_insert, Finset.mem_coe, and_congr_right_iff] exact fun _ => ⟨fun h b hb => h b hb <| by rintro rfl contradiction, fun h b hb _ => h b hb⟩ theorem pairwise_cons {a : α} (ha : a ∉ s) (r : α → α → Prop) : Pairwise (r on fun a : s.cons a ha => a) ↔ Pairwise (r on fun a : s => a) ∧ ∀ b ∈ s, r a b ∧ r b a := pairwise_cons' ha r id end Pairwise end Finset namespace Equiv variable [DecidableEq α] {s t : Finset α} open Finset /-- The disjoint union of finsets is a sum -/ def Finset.union (s t : Finset α) (h : Disjoint s t) : s ⊕ t ≃ (s ∪ t : Finset α) := Equiv.Set.ofEq (coe_union _ _) |>.trans (Equiv.Set.union (disjoint_coe.mpr h).le_bot) |>.symm @[simp] theorem Finset.union_symm_inl (h : Disjoint s t) (x : s) : Equiv.Finset.union s t h (Sum.inl x) = ⟨x, Finset.mem_union.mpr <| Or.inl x.2⟩ := rfl @[simp] theorem Finset.union_symm_inr (h : Disjoint s t) (y : t) : Equiv.Finset.union s t h (Sum.inr y) = ⟨y, Finset.mem_union.mpr <| Or.inr y.2⟩ := rfl /-- The type of dependent functions on the disjoint union of finsets `s ∪ t` is equivalent to the type of pairs of functions on `s` and on `t`. This is similar to `Equiv.sumPiEquivProdPi`. -/ def piFinsetUnion {ι} [DecidableEq ι] (α : ι → Type*) {s t : Finset ι} (h : Disjoint s t) : ((∀ i : s, α i) × ∀ i : t, α i) ≃ ∀ i : (s ∪ t : Finset ι), α i := let e := Equiv.Finset.union s t h sumPiEquivProdPi (fun b ↦ α (e b)) |>.symm.trans (.piCongrLeft (fun i : ↥(s ∪ t) ↦ α i) e) end Equiv namespace Multiset variable [DecidableEq α] theorem disjoint_toFinset {m1 m2 : Multiset α} : _root_.Disjoint m1.toFinset m2.toFinset ↔ m1.Disjoint m2 := by rw [Finset.disjoint_iff_ne] refine ⟨fun h a ha1 ha2 => ?_, ?_⟩ · rw [← Multiset.mem_toFinset] at ha1 ha2 exact h _ ha1 _ ha2 rfl · rintro h a ha b hb rfl rw [Multiset.mem_toFinset] at ha hb exact h ha hb end Multiset namespace List variable [DecidableEq α] {l l' : List α} theorem disjoint_toFinset_iff_disjoint : _root_.Disjoint l.toFinset l'.toFinset ↔ l.Disjoint l' := Multiset.disjoint_toFinset end List namespace Mathlib.Meta open Qq Lean Meta Finset /-- Attempt to prove that a finset is nonempty using the `finsetNonempty` aesop rule-set. You can add lemmas to the rule-set by tagging them with either: * `aesop safe apply (rule_sets := [finsetNonempty])` if they are always a good idea to follow or * `aesop unsafe apply (rule_sets := [finsetNonempty])` if they risk directing the search to a blind alley. -/ def proveFinsetNonempty {u : Level} {α : Q(Type u)} (s : Q(Finset $α)) : MetaM (Option Q(Finset.Nonempty $s)) := do -- Aesop expects to operate on goals, so we're going to make a new goal. let goal ← Lean.Meta.mkFreshExprMVar q(Finset.Nonempty $s) let mvar := goal.mvarId! -- We want this to be fast, so use only the basic and `Finset.Nonempty`-specific rules. let rulesets ← Aesop.Frontend.getGlobalRuleSets #[`builtin, `finsetNonempty] let options : Aesop.Options' := { terminal := true -- Fail if the new goal is not closed. generateScript := false useDefaultSimpSet := false -- Avoiding the whole simp set to speed up the tactic. warnOnNonterminal := false -- Don't show a warning on failure, simply return `none`. forwardMaxDepth? := none } let rules ← Aesop.mkLocalRuleSet rulesets options let (remainingGoals, _) ← try Aesop.search (options := options.toOptions) mvar (.some rules) catch _ => return none -- Fail if there are open goals remaining, this serves as an extra check for the -- Aesop configuration option `terminal := true`. if remainingGoals.size > 0 then return none Lean.getExprMVarAssignment? mvar end Mathlib.Meta
Data\Finset\Card.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, Jeremy Avigad -/ import Mathlib.Data.Finset.Image /-! # Cardinality of a finite set This defines the cardinality of a `Finset` and provides induction principles for finsets. ## Main declarations * `Finset.card`: `s.card : ℕ` returns the cardinality of `s : Finset α`. ### Induction principles * `Finset.strongInduction`: Strong induction * `Finset.strongInductionOn` * `Finset.strongDownwardInduction` * `Finset.strongDownwardInductionOn` * `Finset.case_strong_induction_on` * `Finset.Nonempty.strong_induction` -/ assert_not_exists MonoidWithZero -- TODO: After a lot more work, -- assert_not_exists OrderedCommMonoid open Function Multiset Nat variable {α β R : Type*} namespace Finset variable {s t : Finset α} {a b : α} /-- `s.card` is the number of elements of `s`, aka its cardinality. -/ def card (s : Finset α) : ℕ := Multiset.card s.1 theorem card_def (s : Finset α) : s.card = Multiset.card s.1 := rfl @[simp] lemma card_val (s : Finset α) : Multiset.card s.1 = s.card := rfl @[simp] theorem card_mk {m nodup} : (⟨m, nodup⟩ : Finset α).card = Multiset.card m := rfl @[simp] theorem card_empty : card (∅ : Finset α) = 0 := rfl @[gcongr] theorem card_le_card : s ⊆ t → s.card ≤ t.card := Multiset.card_le_card ∘ val_le_iff.mpr @[mono] theorem card_mono : Monotone (@card α) := by apply card_le_card @[simp] lemma card_eq_zero : s.card = 0 ↔ s = ∅ := Multiset.card_eq_zero.trans val_eq_zero lemma card_ne_zero : s.card ≠ 0 ↔ s.Nonempty := card_eq_zero.ne.trans nonempty_iff_ne_empty.symm @[simp] lemma card_pos : 0 < s.card ↔ s.Nonempty := Nat.pos_iff_ne_zero.trans card_ne_zero @[simp] lemma one_le_card : 1 ≤ s.card ↔ s.Nonempty := card_pos alias ⟨_, Nonempty.card_pos⟩ := card_pos alias ⟨_, Nonempty.card_ne_zero⟩ := card_ne_zero theorem card_ne_zero_of_mem (h : a ∈ s) : s.card ≠ 0 := (not_congr card_eq_zero).2 <| ne_empty_of_mem h @[simp] theorem card_singleton (a : α) : card ({a} : Finset α) = 1 := Multiset.card_singleton _ theorem card_singleton_inter [DecidableEq α] : ({a} ∩ s).card ≤ 1 := by cases' Finset.decidableMem a s with h h · simp [Finset.singleton_inter_of_not_mem h] · simp [Finset.singleton_inter_of_mem h] @[simp] theorem card_cons (h : a ∉ s) : (s.cons a h).card = s.card + 1 := Multiset.card_cons _ _ section InsertErase variable [DecidableEq α] @[simp] theorem card_insert_of_not_mem (h : a ∉ s) : (insert a s).card = s.card + 1 := by rw [← cons_eq_insert _ _ h, card_cons] theorem card_insert_of_mem (h : a ∈ s) : card (insert a s) = s.card := by rw [insert_eq_of_mem h] theorem card_insert_le (a : α) (s : Finset α) : card (insert a s) ≤ s.card + 1 := by by_cases h : a ∈ s · rw [insert_eq_of_mem h] exact Nat.le_succ _ · rw [card_insert_of_not_mem h] section variable {a b c d e f : α} theorem card_le_two : card {a, b} ≤ 2 := card_insert_le _ _ theorem card_le_three : card {a, b, c} ≤ 3 := (card_insert_le _ _).trans (Nat.succ_le_succ card_le_two) theorem card_le_four : card {a, b, c, d} ≤ 4 := (card_insert_le _ _).trans (Nat.succ_le_succ card_le_three) theorem card_le_five : card {a, b, c, d, e} ≤ 5 := (card_insert_le _ _).trans (Nat.succ_le_succ card_le_four) theorem card_le_six : card {a, b, c, d, e, f} ≤ 6 := (card_insert_le _ _).trans (Nat.succ_le_succ card_le_five) end /-- If `a ∈ s` is known, see also `Finset.card_insert_of_mem` and `Finset.card_insert_of_not_mem`. -/ theorem card_insert_eq_ite : card (insert a s) = if a ∈ s then s.card else s.card + 1 := by by_cases h : a ∈ s · rw [card_insert_of_mem h, if_pos h] · rw [card_insert_of_not_mem h, if_neg h] @[simp] theorem card_pair_eq_one_or_two : ({a,b} : Finset α).card = 1 ∨ ({a,b} : Finset α).card = 2 := by simp [card_insert_eq_ite] tauto @[simp] theorem card_pair (h : a ≠ b) : ({a, b} : Finset α).card = 2 := by rw [card_insert_of_not_mem (not_mem_singleton.2 h), card_singleton] @[deprecated (since := "2024-01-04")] alias card_doubleton := Finset.card_pair /-- $\#(s \setminus \{a\}) = \#s - 1$ if $a \in s$. -/ @[simp] theorem card_erase_of_mem : a ∈ s → (s.erase a).card = s.card - 1 := Multiset.card_erase_of_mem /-- $\#(s \setminus \{a\}) = \#s - 1$ if $a \in s$. This result is casted to any additive group with 1, so that we don't have to work with `ℕ`-subtraction. -/ @[simp] theorem cast_card_erase_of_mem {R} [AddGroupWithOne R] {s : Finset α} (hs : a ∈ s) : ((s.erase a).card : R) = s.card - 1 := by rw [card_erase_of_mem hs, Nat.cast_sub, Nat.cast_one] rw [Nat.add_one_le_iff, Finset.card_pos] exact ⟨a, hs⟩ @[simp] theorem card_erase_add_one : a ∈ s → (s.erase a).card + 1 = s.card := Multiset.card_erase_add_one theorem card_erase_lt_of_mem : a ∈ s → (s.erase a).card < s.card := Multiset.card_erase_lt_of_mem theorem card_erase_le : (s.erase a).card ≤ s.card := Multiset.card_erase_le theorem pred_card_le_card_erase : s.card - 1 ≤ (s.erase a).card := by by_cases h : a ∈ s · exact (card_erase_of_mem h).ge · rw [erase_eq_of_not_mem h] exact Nat.sub_le _ _ /-- If `a ∈ s` is known, see also `Finset.card_erase_of_mem` and `Finset.erase_eq_of_not_mem`. -/ theorem card_erase_eq_ite : (s.erase a).card = if a ∈ s then s.card - 1 else s.card := Multiset.card_erase_eq_ite end InsertErase @[simp] theorem card_range (n : ℕ) : (range n).card = n := Multiset.card_range n @[simp] theorem card_attach : s.attach.card = s.card := Multiset.card_attach end Finset section ToMLListultiset variable [DecidableEq α] (m : Multiset α) (l : List α) theorem Multiset.card_toFinset : m.toFinset.card = Multiset.card m.dedup := rfl theorem Multiset.toFinset_card_le : m.toFinset.card ≤ Multiset.card m := card_le_card <| dedup_le _ theorem Multiset.toFinset_card_of_nodup {m : Multiset α} (h : m.Nodup) : m.toFinset.card = Multiset.card m := congr_arg card <| Multiset.dedup_eq_self.mpr h theorem Multiset.dedup_card_eq_card_iff_nodup {m : Multiset α} : card m.dedup = card m ↔ m.Nodup := .trans ⟨fun h ↦ eq_of_le_of_card_le (dedup_le m) h.ge, congr_arg _⟩ dedup_eq_self theorem Multiset.toFinset_card_eq_card_iff_nodup {m : Multiset α} : m.toFinset.card = card m ↔ m.Nodup := dedup_card_eq_card_iff_nodup theorem List.card_toFinset : l.toFinset.card = l.dedup.length := rfl theorem List.toFinset_card_le : l.toFinset.card ≤ l.length := Multiset.toFinset_card_le ⟦l⟧ theorem List.toFinset_card_of_nodup {l : List α} (h : l.Nodup) : l.toFinset.card = l.length := Multiset.toFinset_card_of_nodup h end ToMLListultiset namespace Finset variable {s t u : Finset α} {f : α → β} {n : ℕ} @[simp] theorem length_toList (s : Finset α) : s.toList.length = s.card := by rw [toList, ← Multiset.coe_card, Multiset.coe_toList, card_def] theorem card_image_le [DecidableEq β] : (s.image f).card ≤ s.card := by simpa only [card_map] using (s.1.map f).toFinset_card_le theorem card_image_of_injOn [DecidableEq β] (H : Set.InjOn f s) : (s.image f).card = s.card := by simp only [card, image_val_of_injOn H, card_map] theorem injOn_of_card_image_eq [DecidableEq β] (H : (s.image f).card = s.card) : Set.InjOn f s := by rw [card_def, card_def, image, toFinset] at H dsimp only at H have : (s.1.map f).dedup = s.1.map f := by refine Multiset.eq_of_le_of_card_le (Multiset.dedup_le _) ?_ simp only [H, Multiset.card_map, le_rfl] rw [Multiset.dedup_eq_self] at this exact inj_on_of_nodup_map this theorem card_image_iff [DecidableEq β] : (s.image f).card = s.card ↔ Set.InjOn f s := ⟨injOn_of_card_image_eq, card_image_of_injOn⟩ theorem card_image_of_injective [DecidableEq β] (s : Finset α) (H : Injective f) : (s.image f).card = s.card := card_image_of_injOn fun _ _ _ _ h => H h theorem fiber_card_ne_zero_iff_mem_image (s : Finset α) (f : α → β) [DecidableEq β] (y : β) : (s.filter fun x => f x = y).card ≠ 0 ↔ y ∈ s.image f := by rw [← Nat.pos_iff_ne_zero, card_pos, fiber_nonempty_iff_mem_image] lemma card_filter_le_iff (s : Finset α) (P : α → Prop) [DecidablePred P] (n : ℕ) : (s.filter P).card ≤ n ↔ ∀ s' ⊆ s, n < s'.card → ∃ a ∈ s', ¬ P a := (s.1.card_filter_le_iff P n).trans ⟨fun H s' hs' h ↦ H s'.1 (by aesop) h, fun H s' hs' h ↦ H ⟨s', nodup_of_le hs' s.2⟩ (fun x hx ↦ subset_of_le hs' hx) h⟩ @[simp] theorem card_map (f : α ↪ β) : (s.map f).card = s.card := Multiset.card_map _ _ @[simp] theorem card_subtype (p : α → Prop) [DecidablePred p] (s : Finset α) : (s.subtype p).card = (s.filter p).card := by simp [Finset.subtype] theorem card_filter_le (s : Finset α) (p : α → Prop) [DecidablePred p] : (s.filter p).card ≤ s.card := card_le_card <| filter_subset _ _ theorem eq_of_subset_of_card_le {s t : Finset α} (h : s ⊆ t) (h₂ : t.card ≤ s.card) : s = t := eq_of_veq <| Multiset.eq_of_le_of_card_le (val_le_iff.mpr h) h₂ theorem eq_of_superset_of_card_ge (hst : s ⊆ t) (hts : t.card ≤ s.card) : t = s := (eq_of_subset_of_card_le hst hts).symm theorem subset_iff_eq_of_card_le (h : t.card ≤ s.card) : s ⊆ t ↔ s = t := ⟨fun hst => eq_of_subset_of_card_le hst h, Eq.subset'⟩ theorem map_eq_of_subset {f : α ↪ α} (hs : s.map f ⊆ s) : s.map f = s := eq_of_subset_of_card_le hs (card_map _).ge theorem filter_card_eq {p : α → Prop} [DecidablePred p] (h : (s.filter p).card = s.card) (x : α) (hx : x ∈ s) : p x := by rw [← eq_of_subset_of_card_le (s.filter_subset p) h.ge, mem_filter] at hx exact hx.2 nonrec lemma card_lt_card (h : s ⊂ t) : s.card < t.card := card_lt_card <| val_lt_iff.2 h lemma card_strictMono : StrictMono (card : Finset α → ℕ) := fun _ _ ↦ card_lt_card theorem card_eq_of_bijective (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) : s.card = n := by classical have : s = (range n).attach.image fun i => f i.1 (mem_range.1 i.2) := by ext a suffices _ : a ∈ s ↔ ∃ (i : _) (hi : i ∈ range n), f i (mem_range.1 hi) = a by simpa only [mem_image, mem_attach, true_and_iff, Subtype.exists] constructor · intro ha; obtain ⟨i, hi, rfl⟩ := hf a ha; use i, mem_range.2 hi · rintro ⟨i, hi, rfl⟩; apply hf' calc s.card = ((range n).attach.image fun i => f i.1 (mem_range.1 i.2)).card := by rw [this] _ = (range n).attach.card := ?_ _ = (range n).card := card_attach _ = n := card_range n apply card_image_of_injective intro ⟨i, hi⟩ ⟨j, hj⟩ eq exact Subtype.eq <| f_inj i j (mem_range.1 hi) (mem_range.1 hj) eq section bij variable {t : Finset β} /-- Reorder a finset. The difference with `Finset.card_bij'` is that the bijection is specified as a surjective injection, rather than by an inverse function. The difference with `Finset.card_nbij` is that the bijection is allowed to use membership of the domain, rather than being a non-dependent function. -/ lemma card_bij (i : ∀ a ∈ s, β) (hi : ∀ a ha, i a ha ∈ t) (i_inj : ∀ a₁ ha₁ a₂ ha₂, i a₁ ha₁ = i a₂ ha₂ → a₁ = a₂) (i_surj : ∀ b ∈ t, ∃ a ha, i a ha = b) : s.card = t.card := by classical calc s.card = s.attach.card := card_attach.symm _ = (s.attach.image fun a : { a // a ∈ s } => i a.1 a.2).card := Eq.symm ?_ _ = t.card := ?_ · apply card_image_of_injective intro ⟨_, _⟩ ⟨_, _⟩ h simpa using i_inj _ _ _ _ h · congr 1 ext b constructor <;> intro h · obtain ⟨_, _, rfl⟩ := mem_image.1 h; apply hi · obtain ⟨a, ha, rfl⟩ := i_surj b h; exact mem_image.2 ⟨⟨a, ha⟩, by simp⟩ @[deprecated (since := "2024-05-04")] alias card_congr := card_bij /-- Reorder a finset. The difference with `Finset.card_bij` is that the bijection is specified with an inverse, rather than as a surjective injection. The difference with `Finset.card_nbij'` is that the bijection and its inverse are allowed to use membership of the domains, rather than being non-dependent functions. -/ lemma card_bij' (i : ∀ a ∈ s, β) (j : ∀ a ∈ t, α) (hi : ∀ a ha, i a ha ∈ t) (hj : ∀ a ha, j a ha ∈ s) (left_inv : ∀ a ha, j (i a ha) (hi a ha) = a) (right_inv : ∀ a ha, i (j a ha) (hj a ha) = a) : s.card = t.card := by refine card_bij i hi (fun a1 h1 a2 h2 eq ↦ ?_) (fun b hb ↦ ⟨_, hj b hb, right_inv b hb⟩) rw [← left_inv a1 h1, ← left_inv a2 h2] simp only [eq] /-- Reorder a finset. The difference with `Finset.card_nbij'` is that the bijection is specified as a surjective injection, rather than by an inverse function. The difference with `Finset.card_bij` is that the bijection is a non-dependent function, rather than being allowed to use membership of the domain. -/ lemma card_nbij (i : α → β) (hi : ∀ a ∈ s, i a ∈ t) (i_inj : (s : Set α).InjOn i) (i_surj : (s : Set α).SurjOn i t) : s.card = t.card := card_bij (fun a _ ↦ i a) hi i_inj (by simpa using i_surj) /-- Reorder a finset. The difference with `Finset.card_nbij` is that the bijection is specified with an inverse, rather than as a surjective injection. The difference with `Finset.card_bij'` is that the bijection and its inverse are non-dependent functions, rather than being allowed to use membership of the domains. The difference with `Finset.card_equiv` is that bijectivity is only required to hold on the domains, rather than on the entire types. -/ lemma card_nbij' (i : α → β) (j : β → α) (hi : ∀ a ∈ s, i a ∈ t) (hj : ∀ a ∈ t, j a ∈ s) (left_inv : ∀ a ∈ s, j (i a) = a) (right_inv : ∀ a ∈ t, i (j a) = a) : s.card = t.card := card_bij' (fun a _ ↦ i a) (fun b _ ↦ j b) hi hj left_inv right_inv /-- Specialization of `Finset.card_nbij'` that automatically fills in most arguments. See `Fintype.card_equiv` for the version where `s` and `t` are `univ`. -/ lemma card_equiv (e : α ≃ β) (hst : ∀ i, i ∈ s ↔ e i ∈ t) : s.card = t.card := by refine card_nbij' e e.symm ?_ ?_ ?_ ?_ <;> simp [hst] /-- Specialization of `Finset.card_nbij` that automatically fills in most arguments. See `Fintype.card_bijective` for the version where `s` and `t` are `univ`. -/ lemma card_bijective (e : α → β) (he : e.Bijective) (hst : ∀ i, i ∈ s ↔ e i ∈ t) : s.card = t.card := card_equiv (.ofBijective e he) hst lemma card_le_card_of_injOn (f : α → β) (hf : ∀ a ∈ s, f a ∈ t) (f_inj : (s : Set α).InjOn f) : s.card ≤ t.card := by classical calc s.card = (s.image f).card := (card_image_of_injOn f_inj).symm _ ≤ t.card := card_le_card <| image_subset_iff.2 hf @[deprecated (since := "2024-06-01")] alias card_le_card_of_inj_on := card_le_card_of_injOn lemma card_le_card_of_surjOn (f : α → β) (hf : Set.SurjOn f s t) : t.card ≤ s.card := by classical unfold Set.SurjOn at hf; exact (card_le_card (mod_cast hf)).trans card_image_le /-- If there are more pigeons than pigeonholes, then there are two pigeons in the same pigeonhole. -/ theorem exists_ne_map_eq_of_card_lt_of_maps_to {t : Finset β} (hc : t.card < s.card) {f : α → β} (hf : ∀ a ∈ s, f a ∈ t) : ∃ x ∈ s, ∃ y ∈ s, x ≠ y ∧ f x = f y := by classical by_contra! hz refine hc.not_le (card_le_card_of_injOn f hf ?_) intro x hx y hy contrapose exact hz x hx y hy lemma le_card_of_inj_on_range (f : ℕ → α) (hf : ∀ i < n, f i ∈ s) (f_inj : ∀ i < n, ∀ j < n, f i = f j → i = j) : n ≤ s.card := calc n = card (range n) := (card_range n).symm _ ≤ s.card := card_le_card_of_injOn f (by simpa only [mem_range]) (by simpa) lemma surj_on_of_inj_on_of_card_le (f : ∀ a ∈ s, β) (hf : ∀ a ha, f a ha ∈ t) (hinj : ∀ a₁ a₂ ha₁ ha₂, f a₁ ha₁ = f a₂ ha₂ → a₁ = a₂) (hst : t.card ≤ s.card) : ∀ b ∈ t, ∃ a ha, b = f a ha := by classical have h : (s.attach.image fun a : { a // a ∈ s } => f a a.prop).card = s.card := by rw [← @card_attach _ s, card_image_of_injective] intro ⟨_, _⟩ ⟨_, _⟩ h exact Subtype.eq <| hinj _ _ _ _ h obtain rfl : image (fun a : { a // a ∈ s } => f a a.prop) s.attach = t := eq_of_subset_of_card_le (image_subset_iff.2 $ by simpa) (by simp [hst, h]) simp only [mem_image, mem_attach, true_and, Subtype.exists, forall_exists_index] exact fun b a ha hb ↦ ⟨a, ha, hb.symm⟩ theorem inj_on_of_surj_on_of_card_le (f : ∀ a ∈ s, β) (hf : ∀ a ha, f a ha ∈ t) (hsurj : ∀ b ∈ t, ∃ a ha, f a ha = b) (hst : s.card ≤ t.card) ⦃a₁⦄ (ha₁ : a₁ ∈ s) ⦃a₂⦄ (ha₂ : a₂ ∈ s) (ha₁a₂ : f a₁ ha₁ = f a₂ ha₂) : a₁ = a₂ := haveI : Inhabited { x // x ∈ s } := ⟨⟨a₁, ha₁⟩⟩ let f' : { x // x ∈ s } → { x // x ∈ t } := fun x => ⟨f x.1 x.2, hf x.1 x.2⟩ let g : { x // x ∈ t } → { x // x ∈ s } := @surjInv _ _ f' fun x => let ⟨y, hy₁, hy₂⟩ := hsurj x.1 x.2 ⟨⟨y, hy₁⟩, Subtype.eq hy₂⟩ have hg : Injective g := injective_surjInv _ have hsg : Surjective g := fun x => let ⟨y, hy⟩ := surj_on_of_inj_on_of_card_le (fun (x : { x // x ∈ t }) (_ : x ∈ t.attach) => g x) (fun x _ => show g x ∈ s.attach from mem_attach _ _) (fun x y _ _ hxy => hg hxy) (by simpa) x (mem_attach _ _) ⟨y, hy.snd.symm⟩ have hif : Injective f' := (leftInverse_of_surjective_of_rightInverse hsg (rightInverse_surjInv _)).injective Subtype.ext_iff_val.1 (@hif ⟨a₁, ha₁⟩ ⟨a₂, ha₂⟩ (Subtype.eq ha₁a₂)) end bij @[simp] theorem card_disjUnion (s t : Finset α) (h) : (s.disjUnion t h).card = s.card + t.card := Multiset.card_add _ _ /-! ### Lattice structure -/ section Lattice variable [DecidableEq α] theorem card_union_add_card_inter (s t : Finset α) : (s ∪ t).card + (s ∩ t).card = s.card + t.card := Finset.induction_on t (by simp) fun a r har h => by by_cases a ∈ s <;> simp [*, ← add_assoc, add_right_comm _ 1] theorem card_inter_add_card_union (s t : Finset α) : (s ∩ t).card + (s ∪ t).card = s.card + t.card := by rw [add_comm, card_union_add_card_inter] lemma card_union (s t : Finset α) : (s ∪ t).card = s.card + t.card - (s ∩ t).card := by rw [← card_union_add_card_inter, Nat.add_sub_cancel] lemma card_inter (s t : Finset α) : (s ∩ t).card = s.card + t.card - (s ∪ t).card := by rw [← card_inter_add_card_union, Nat.add_sub_cancel] theorem card_union_le (s t : Finset α) : (s ∪ t).card ≤ s.card + t.card := card_union_add_card_inter s t ▸ Nat.le_add_right _ _ lemma card_union_eq_card_add_card : (s ∪ t).card = s.card + t.card ↔ Disjoint s t := by rw [← card_union_add_card_inter]; simp [disjoint_iff_inter_eq_empty] @[simp] alias ⟨_, card_union_of_disjoint⟩ := card_union_eq_card_add_card @[deprecated (since := "2024-02-09")] alias card_union_eq := card_union_of_disjoint @[deprecated (since := "2024-02-09")] alias card_disjoint_union := card_union_of_disjoint lemma cast_card_inter [AddGroupWithOne R] : ((s ∩ t).card : R) = s.card + t.card - (s ∪ t).card := by rw [eq_sub_iff_add_eq, ← cast_add, card_inter_add_card_union, cast_add] lemma cast_card_union [AddGroupWithOne R] : ((s ∪ t).card : R) = s.card + t.card - (s ∩ t).card := by rw [eq_sub_iff_add_eq, ← cast_add, card_union_add_card_inter, cast_add] theorem card_sdiff (h : s ⊆ t) : card (t \ s) = t.card - s.card := by suffices card (t \ s) = card (t \ s ∪ s) - s.card by rwa [sdiff_union_of_subset h] at this rw [card_union_of_disjoint sdiff_disjoint, Nat.add_sub_cancel_right] lemma cast_card_sdiff [AddGroupWithOne R] (h : s ⊆ t) : ((t \ s).card : R) = t.card - s.card := by rw [card_sdiff h, Nat.cast_sub (card_mono h)] theorem card_sdiff_add_card_eq_card {s t : Finset α} (h : s ⊆ t) : card (t \ s) + card s = card t := ((Nat.sub_eq_iff_eq_add (card_le_card h)).mp (card_sdiff h).symm).symm theorem le_card_sdiff (s t : Finset α) : t.card - s.card ≤ card (t \ s) := calc card t - card s ≤ card t - card (s ∩ t) := Nat.sub_le_sub_left (card_le_card inter_subset_left) _ _ = card (t \ (s ∩ t)) := (card_sdiff inter_subset_right).symm _ ≤ card (t \ s) := by rw [sdiff_inter_self_right t s] theorem card_le_card_sdiff_add_card : s.card ≤ (s \ t).card + t.card := Nat.sub_le_iff_le_add.1 <| le_card_sdiff _ _ theorem card_sdiff_add_card (s t : Finset α) : (s \ t).card + t.card = (s ∪ t).card := by rw [← card_union_of_disjoint sdiff_disjoint, sdiff_union_self_eq_union] lemma card_sdiff_comm (h : s.card = t.card) : (s \ t).card = (t \ s).card := add_left_injective t.card <| by simp_rw [card_sdiff_add_card, ← h, card_sdiff_add_card, union_comm] @[simp] lemma card_sdiff_add_card_inter (s t : Finset α) : (s \ t).card + (s ∩ t).card = s.card := by rw [← card_union_of_disjoint (disjoint_sdiff_inter _ _), sdiff_union_inter] @[simp] lemma card_inter_add_card_sdiff (s t : Finset α) : (s ∩ t).card + (s \ t).card = s.card := by rw [add_comm, card_sdiff_add_card_inter] /-- **Pigeonhole principle** for two finsets inside an ambient finset. -/ theorem inter_nonempty_of_card_lt_card_add_card (hts : t ⊆ s) (hus : u ⊆ s) (hstu : s.card < t.card + u.card) : (t ∩ u).Nonempty := by contrapose! hstu calc _ = (t ∪ u).card := by simp [← card_union_add_card_inter, not_nonempty_iff_eq_empty.1 hstu] _ ≤ s.card := by gcongr; exact union_subset hts hus end Lattice theorem filter_card_add_filter_neg_card_eq_card (p : α → Prop) [DecidablePred p] [∀ x, Decidable (¬p x)] : (s.filter p).card + (s.filter (fun a => ¬ p a)).card = s.card := by classical rw [← card_union_of_disjoint (disjoint_filter_filter_neg _ _ _), filter_union_filter_neg_eq] /-- Given a subset `s` of a set `t`, of sizes at most and at least `n` respectively, there exists a set `u` of size `n` which is both a superset of `s` and a subset of `t`. -/ lemma exists_subsuperset_card_eq (hst : s ⊆ t) (hsn : s.card ≤ n) (hnt : n ≤ t.card) : ∃ u, s ⊆ u ∧ u ⊆ t ∧ card u = n := by classical refine Nat.decreasingInduction' ?_ hnt ⟨t, by simp [hst]⟩ intro k _ hnk ⟨u, hu₁, hu₂, hu₃⟩ obtain ⟨a, ha⟩ : (u \ s).Nonempty := by rw [← card_pos, card_sdiff hu₁]; omega simp only [mem_sdiff] at ha exact ⟨u.erase a, by simp [subset_erase, erase_subset_iff_of_mem (hu₂ _), *]⟩ /-- We can shrink a set to any smaller size. -/ lemma exists_subset_card_eq (hns : n ≤ s.card) : ∃ t ⊆ s, t.card = n := by simpa using exists_subsuperset_card_eq s.empty_subset (by simp) hns /-- Given a set `A` and a set `B` inside it, we can shrink `A` to any appropriate size, and keep `B` inside it. -/ @[deprecated exists_subsuperset_card_eq (since := "2024-06-23")] theorem exists_intermediate_set {A B : Finset α} (i : ℕ) (h₁ : i + card B ≤ card A) (h₂ : B ⊆ A) : ∃ C : Finset α, B ⊆ C ∧ C ⊆ A ∧ card C = i + card B := exists_subsuperset_card_eq h₂ (Nat.le_add_left ..) h₁ /-- We can shrink `A` to any smaller size. -/ @[deprecated exists_subset_card_eq (since := "2024-06-23")] theorem exists_smaller_set (A : Finset α) (i : ℕ) (h₁ : i ≤ card A) : ∃ B : Finset α, B ⊆ A ∧ card B = i := exists_subset_card_eq h₁ theorem le_card_iff_exists_subset_card : n ≤ s.card ↔ ∃ t ⊆ s, t.card = n := by refine ⟨fun h => ?_, fun ⟨t, hst, ht⟩ => ht ▸ card_le_card hst⟩ exact exists_subset_card_eq h theorem exists_subset_or_subset_of_two_mul_lt_card [DecidableEq α] {X Y : Finset α} {n : ℕ} (hXY : 2 * n < (X ∪ Y).card) : ∃ C : Finset α, n < C.card ∧ (C ⊆ X ∨ C ⊆ Y) := by have h₁ : (X ∩ (Y \ X)).card = 0 := Finset.card_eq_zero.mpr (Finset.inter_sdiff_self X Y) have h₂ : (X ∪ Y).card = X.card + (Y \ X).card := by rw [← card_union_add_card_inter X (Y \ X), Finset.union_sdiff_self_eq_union, h₁, add_zero] rw [h₂, Nat.two_mul] at hXY obtain h | h : n < X.card ∨ n < (Y \ X).card := by contrapose! hXY; omega · exact ⟨X, h, Or.inl (Finset.Subset.refl X)⟩ · exact ⟨Y \ X, h, Or.inr sdiff_subset⟩ /-! ### Explicit description of a finset from its card -/ theorem card_eq_one : s.card = 1 ↔ ∃ a, s = {a} := by cases s simp only [Multiset.card_eq_one, Finset.card, ← val_inj, singleton_val] theorem _root_.Multiset.toFinset_card_eq_one_iff [DecidableEq α] (s : Multiset α) : s.toFinset.card = 1 ↔ Multiset.card s ≠ 0 ∧ ∃ a : α, s = Multiset.card s • {a} := by simp_rw [card_eq_one, Multiset.toFinset_eq_singleton_iff, exists_and_left] theorem exists_eq_insert_iff [DecidableEq α] {s t : Finset α} : (∃ a ∉ s, insert a s = t) ↔ s ⊆ t ∧ s.card + 1 = t.card := by constructor · rintro ⟨a, ha, rfl⟩ exact ⟨subset_insert _ _, (card_insert_of_not_mem ha).symm⟩ · rintro ⟨hst, h⟩ obtain ⟨a, ha⟩ : ∃ a, t \ s = {a} := card_eq_one.1 (by rw [card_sdiff hst, ← h, Nat.add_sub_cancel_left]) refine ⟨a, fun hs => (?_ : a ∉ {a}) <| mem_singleton_self _, by rw [insert_eq, ← ha, sdiff_union_of_subset hst]⟩ rw [← ha] exact not_mem_sdiff_of_mem_right hs theorem card_le_one : s.card ≤ 1 ↔ ∀ a ∈ s, ∀ b ∈ s, a = b := by obtain rfl | ⟨x, hx⟩ := s.eq_empty_or_nonempty · simp refine (Nat.succ_le_of_lt (card_pos.2 ⟨x, hx⟩)).le_iff_eq.trans (card_eq_one.trans ⟨?_, ?_⟩) · rintro ⟨y, rfl⟩ simp · exact fun h => ⟨x, eq_singleton_iff_unique_mem.2 ⟨hx, fun y hy => h _ hy _ hx⟩⟩ theorem card_le_one_iff : s.card ≤ 1 ↔ ∀ {a b}, a ∈ s → b ∈ s → a = b := by rw [card_le_one] tauto theorem card_le_one_iff_subsingleton_coe : s.card ≤ 1 ↔ Subsingleton (s : Type _) := card_le_one.trans (s : Set α).subsingleton_coe.symm theorem card_le_one_iff_subset_singleton [Nonempty α] : s.card ≤ 1 ↔ ∃ x : α, s ⊆ {x} := by refine ⟨fun H => ?_, ?_⟩ · obtain rfl | ⟨x, hx⟩ := s.eq_empty_or_nonempty · exact ⟨Classical.arbitrary α, empty_subset _⟩ · exact ⟨x, fun y hy => by rw [card_le_one.1 H y hy x hx, mem_singleton]⟩ · rintro ⟨x, hx⟩ rw [← card_singleton x] exact card_le_card hx lemma exists_mem_ne (hs : 1 < s.card) (a : α) : ∃ b ∈ s, b ≠ a := by have : Nonempty α := ⟨a⟩ by_contra! exact hs.not_le (card_le_one_iff_subset_singleton.2 ⟨a, subset_singleton_iff'.2 this⟩) /-- A `Finset` of a subsingleton type has cardinality at most one. -/ theorem card_le_one_of_subsingleton [Subsingleton α] (s : Finset α) : s.card ≤ 1 := Finset.card_le_one_iff.2 fun {_ _ _ _} => Subsingleton.elim _ _ theorem one_lt_card : 1 < s.card ↔ ∃ a ∈ s, ∃ b ∈ s, a ≠ b := by rw [← not_iff_not] push_neg exact card_le_one theorem one_lt_card_iff : 1 < s.card ↔ ∃ a b, a ∈ s ∧ b ∈ s ∧ a ≠ b := by rw [one_lt_card] simp only [exists_prop, exists_and_left] theorem one_lt_card_iff_nontrivial : 1 < s.card ↔ s.Nontrivial := by rw [← not_iff_not, not_lt, Finset.Nontrivial, ← Set.nontrivial_coe_sort, not_nontrivial_iff_subsingleton, card_le_one_iff_subsingleton_coe, coe_sort_coe] @[deprecated (since := "2024-02-05")] alias one_lt_card_iff_nontrivial_coe := one_lt_card_iff_nontrivial theorem exists_ne_of_one_lt_card (hs : 1 < s.card) (a : α) : ∃ b, b ∈ s ∧ b ≠ a := by obtain ⟨x, hx, y, hy, hxy⟩ := Finset.one_lt_card.mp hs by_cases ha : y = a · exact ⟨x, hx, ne_of_ne_of_eq hxy ha⟩ · exact ⟨y, hy, ha⟩ /-- If a Finset in a Pi type is nontrivial (has at least two elements), then its projection to some factor is nontrivial, and the fibers of the projection are proper subsets. -/ lemma exists_of_one_lt_card_pi {ι : Type*} {α : ι → Type*} [∀ i, DecidableEq (α i)] {s : Finset (∀ i, α i)} (h : 1 < s.card) : ∃ i, 1 < (s.image (· i)).card ∧ ∀ ai, s.filter (· i = ai) ⊂ s := by simp_rw [one_lt_card_iff, Function.ne_iff] at h ⊢ obtain ⟨a1, a2, h1, h2, i, hne⟩ := h refine ⟨i, ⟨_, _, mem_image_of_mem _ h1, mem_image_of_mem _ h2, hne⟩, fun ai => ?_⟩ rw [filter_ssubset] obtain rfl | hne := eq_or_ne (a2 i) ai exacts [⟨a1, h1, hne⟩, ⟨a2, h2, hne⟩] section DecidableEq variable [DecidableEq α] theorem card_eq_succ : s.card = n + 1 ↔ ∃ a t, a ∉ t ∧ insert a t = s ∧ t.card = n := ⟨fun h => let ⟨a, has⟩ := card_pos.mp (h.symm ▸ Nat.zero_lt_succ _ : 0 < s.card) ⟨a, s.erase a, s.not_mem_erase a, insert_erase has, by simp only [h, card_erase_of_mem has, Nat.add_sub_cancel_right]⟩, fun ⟨a, t, hat, s_eq, n_eq⟩ => s_eq ▸ n_eq ▸ card_insert_of_not_mem hat⟩ theorem card_eq_two : s.card = 2 ↔ ∃ x y, x ≠ y ∧ s = {x, y} := by constructor · rw [card_eq_succ] simp_rw [card_eq_one] rintro ⟨a, _, hab, rfl, b, rfl⟩ exact ⟨a, b, not_mem_singleton.1 hab, rfl⟩ · rintro ⟨x, y, h, rfl⟩ exact card_pair h theorem card_eq_three : s.card = 3 ↔ ∃ x y z, x ≠ y ∧ x ≠ z ∧ y ≠ z ∧ s = {x, y, z} := by constructor · rw [card_eq_succ] simp_rw [card_eq_two] rintro ⟨a, _, abc, rfl, b, c, bc, rfl⟩ rw [mem_insert, mem_singleton, not_or] at abc exact ⟨a, b, c, abc.1, abc.2, bc, rfl⟩ · rintro ⟨x, y, z, xy, xz, yz, rfl⟩ simp only [xy, xz, yz, mem_insert, card_insert_of_not_mem, not_false_iff, mem_singleton, or_self_iff, card_singleton] end DecidableEq theorem two_lt_card_iff : 2 < s.card ↔ ∃ a b c, a ∈ s ∧ b ∈ s ∧ c ∈ s ∧ a ≠ b ∧ a ≠ c ∧ b ≠ c := by classical simp_rw [lt_iff_add_one_le, le_card_iff_exists_subset_card, reduceAdd, card_eq_three, ← exists_and_left, exists_comm (α := Finset α)] constructor · rintro ⟨a, b, c, t, hsub, hab, hac, hbc, rfl⟩ exact ⟨a, b, c, by simp_all [insert_subset_iff]⟩ · rintro ⟨a, b, c, ha, hb, hc, hab, hac, hbc⟩ exact ⟨a, b, c, {a, b, c}, by simp_all [insert_subset_iff]⟩ theorem two_lt_card : 2 < s.card ↔ ∃ a ∈ s, ∃ b ∈ s, ∃ c ∈ s, a ≠ b ∧ a ≠ c ∧ b ≠ c := by simp_rw [two_lt_card_iff, exists_and_left] /-! ### Inductions -/ /-- 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. -/ def strongInduction {p : Finset α → Sort*} (H : ∀ s, (∀ t ⊂ s, p t) → p s) : ∀ s : Finset α, p s | s => H s fun t h => have : t.card < s.card := card_lt_card h strongInduction H t termination_by s => Finset.card s @[nolint unusedHavesSuffices] -- Porting note: false positive theorem strongInduction_eq {p : Finset α → Sort*} (H : ∀ s, (∀ t ⊂ s, p t) → p s) (s : Finset α) : strongInduction H s = H s fun t _ => strongInduction H t := by rw [strongInduction] /-- Analogue of `strongInduction` with order of arguments swapped. -/ @[elab_as_elim] def strongInductionOn {p : Finset α → Sort*} (s : Finset α) : (∀ s, (∀ t ⊂ s, p t) → p s) → p s := fun H => strongInduction H s @[nolint unusedHavesSuffices] -- Porting note: false positive theorem strongInductionOn_eq {p : Finset α → Sort*} (s : Finset α) (H : ∀ s, (∀ t ⊂ s, p t) → p s) : s.strongInductionOn H = H s fun t _ => t.strongInductionOn H := by dsimp only [strongInductionOn] rw [strongInduction] @[elab_as_elim] theorem case_strong_induction_on [DecidableEq α] {p : Finset α → Prop} (s : Finset α) (h₀ : p ∅) (h₁ : ∀ a s, a ∉ s → (∀ t ⊆ s, p t) → p (insert a s)) : p s := Finset.strongInductionOn s fun s => Finset.induction_on s (fun _ => h₀) fun a s n _ ih => (h₁ a s n) fun t ss => ih _ (lt_of_le_of_lt ss (ssubset_insert n) : t < _) /-- Suppose that, given objects defined on all nonempty strict subsets of any nontrivial finset `s`, one knows how to define an object on `s`. Then one can inductively define an object on all finsets, starting from singletons and iterating. TODO: Currently this can only be used to prove properties. Replace `Finset.Nonempty.exists_eq_singleton_or_nontrivial` with computational content in order to let `p` be `Sort`-valued. -/ @[elab_as_elim] protected lemma Nonempty.strong_induction {p : ∀ s, s.Nonempty → Prop} (h₀ : ∀ a, p {a} (singleton_nonempty _)) (h₁ : ∀ ⦃s⦄ (hs : s.Nontrivial), (∀ t ht, t ⊂ s → p t ht) → p s hs.nonempty) : ∀ ⦃s : Finset α⦄ (hs), p s hs | s, hs => by obtain ⟨a, rfl⟩ | hs := hs.exists_eq_singleton_or_nontrivial · exact h₀ _ · refine h₁ hs fun t ht hts ↦ ?_ have := card_lt_card hts exact ht.strong_induction h₀ h₁ termination_by s => Finset.card s /-- Suppose that, given that `p t` can be defined on all supersets of `s` of cardinality less than `n`, one knows how to define `p s`. Then one can inductively define `p s` for all finsets `s` of cardinality less than `n`, starting from finsets of card `n` and iterating. This can be used either to define data, or to prove properties. -/ def strongDownwardInduction {p : Finset α → Sort*} {n : ℕ} (H : ∀ t₁, (∀ {t₂ : Finset α}, t₂.card ≤ n → t₁ ⊂ t₂ → p t₂) → t₁.card ≤ n → p t₁) : ∀ s : Finset α, s.card ≤ n → p s | s => H s fun {t} ht h => have := Finset.card_lt_card h have : n - t.card < n - s.card := by omega strongDownwardInduction H t ht termination_by s => n - s.card @[nolint unusedHavesSuffices] -- Porting note: false positive theorem strongDownwardInduction_eq {p : Finset α → Sort*} (H : ∀ t₁, (∀ {t₂ : Finset α}, t₂.card ≤ n → t₁ ⊂ t₂ → p t₂) → t₁.card ≤ n → p t₁) (s : Finset α) : strongDownwardInduction H s = H s fun {t} ht _ => strongDownwardInduction H t ht := by rw [strongDownwardInduction] /-- Analogue of `strongDownwardInduction` with order of arguments swapped. -/ @[elab_as_elim] def strongDownwardInductionOn {p : Finset α → Sort*} (s : Finset α) (H : ∀ t₁, (∀ {t₂ : Finset α}, t₂.card ≤ n → t₁ ⊂ t₂ → p t₂) → t₁.card ≤ n → p t₁) : s.card ≤ n → p s := strongDownwardInduction H s @[nolint unusedHavesSuffices] -- Porting note: false positive theorem strongDownwardInductionOn_eq {p : Finset α → Sort*} (s : Finset α) (H : ∀ t₁, (∀ {t₂ : Finset α}, t₂.card ≤ n → t₁ ⊂ t₂ → p t₂) → t₁.card ≤ n → p t₁) : s.strongDownwardInductionOn H = H s fun {t} ht _ => t.strongDownwardInductionOn H ht := by dsimp only [strongDownwardInductionOn] rw [strongDownwardInduction] theorem lt_wf {α} : WellFounded (@LT.lt (Finset α) _) := have H : Subrelation (@LT.lt (Finset α) _) (InvImage (· < ·) card) := fun {_ _} hxy => card_lt_card hxy Subrelation.wf H <| InvImage.wf _ <| (Nat.lt_wfRel).2 @[deprecated (since := "2023-12-27")] alias card_le_of_subset := card_le_card end Finset
Data\Finset\Density.lean
/- Copyright (c) 2023 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import Mathlib.Algebra.Order.Field.Basic import Mathlib.Algebra.Order.Field.Rat import Mathlib.Data.Fintype.Card /-! # Density of a finite set This defines the density of a `Finset` and provides induction principles for finsets. ## Main declarations * `Finset.dens s`: Density of `s : Finset α` in `α` as a nonnegative rational number. ## Implementation notes There are many other ways to talk about the density of a finset and provide its API: 1. Use the uniform measure 2. Define finitely additive functions and generalise the `Finset.card` API to it. This could either be done with a. A structure `FinitelyAdditiveFun` b. A typeclass `IsFinitelyAdditiveFun` Solution 1 would mean importing measure theory in simple files (not necessarily bad, but not amazing), and every single API lemma would require the user to prove that all the sets they are talking about are measurable in the trivial sigma-algebra (quite terrible user experience). Solution 2 would mean that some API lemmas about density don't contain `dens` in their name because they are general results about finitely additive functions. But not all lemmas would be like that either since some really are `dens`-specific. Hence the user would need to think about whether the lemma they are looking for is generally true for finitely additive measure or whether it is `dens`-specific. On top of this, solution 2.a would break dot notation on `Finset.dens` (possibly fixable by introducing notation for `⇑Finset.dens`) and solution 2.b would run the risk of being bad performance-wise. These considerations more generally apply to `Finset.card` and `Finset.sum` and demonstrate that overengineering basic definitions is likely to hinder user experience. -/ -- TODO -- assert_not_exists Ring open Function Multiset Nat variable {𝕜 α β : Type*} [Fintype α] namespace Finset variable {s t : Finset α} {a b : α} /-- Density of a finset. `dens s` is the number of elements of `s` divided by the size of the ambient type `α`. -/ def dens (s : Finset α) : ℚ≥0 := s.card / Fintype.card α lemma dens_eq_card_div_card (s : Finset α) : dens s = s.card / Fintype.card α := rfl @[simp] lemma dens_empty : dens (∅ : Finset α) = 0 := by simp [dens] @[simp] lemma dens_singleton (a : α) : dens ({a} : Finset α) = (Fintype.card α : ℚ≥0)⁻¹ := by simp [dens] @[simp] lemma dens_cons (h : a ∉ s) : (s.cons a h).dens = dens s + (Fintype.card α : ℚ≥0)⁻¹ := by simp [dens, add_div] @[simp] lemma dens_disjUnion (s t : Finset α) (h) : dens (s.disjUnion t h) = dens s + dens t := by simp_rw [dens, card_disjUnion, Nat.cast_add, add_div] @[simp] lemma dens_eq_zero : dens s = 0 ↔ s = ∅ := by simp (config := { contextual := true }) [dens, Fintype.card_eq_zero_iff, eq_empty_of_isEmpty] lemma dens_ne_zero : dens s ≠ 0 ↔ s.Nonempty := dens_eq_zero.not.trans nonempty_iff_ne_empty.symm @[simp] lemma dens_pos : 0 < dens s ↔ s.Nonempty := pos_iff_ne_zero.trans dens_ne_zero protected alias ⟨_, Nonempty.dens_pos⟩ := dens_pos protected alias ⟨_, Nonempty.dens_ne_zero⟩ := dens_ne_zero lemma dens_le_dens (h : s ⊆ t) : dens s ≤ dens t := div_le_div_of_nonneg_right (mod_cast card_mono h) $ by positivity lemma dens_lt_dens (h : s ⊂ t) : dens s < dens t := div_lt_div_of_pos_right (mod_cast card_strictMono h) $ by cases isEmpty_or_nonempty α · simp [Subsingleton.elim s t, ssubset_irrfl] at h · exact mod_cast Fintype.card_pos @[mono] lemma dens_mono : Monotone (dens : Finset α → ℚ≥0) := fun _ _ ↦ dens_le_dens @[mono] lemma dens_strictMono : StrictMono (dens : Finset α → ℚ≥0) := fun _ _ ↦ dens_lt_dens lemma dens_map_le [Fintype β] (f : α ↪ β) : dens (s.map f) ≤ dens s := by cases isEmpty_or_nonempty α · simp [Subsingleton.elim s ∅] simp_rw [dens, card_map] gcongr · positivity · exact mod_cast Fintype.card_pos · exact Fintype.card_le_of_injective _ f.2 section Nonempty variable [Nonempty α] @[simp] lemma dens_univ : dens (univ : Finset α) = 1 := by simp [dens, card_univ] @[simp] lemma dens_eq_one : dens s = 1 ↔ s = univ := by simp [dens, div_eq_one_iff_eq, card_eq_iff_eq_univ] lemma dens_ne_one : dens s ≠ 1 ↔ s ≠ univ := dens_eq_one.not end Nonempty section Lattice variable [DecidableEq α] lemma dens_union_add_dens_inter (s t : Finset α) : dens (s ∪ t) + dens (s ∩ t) = dens s + dens t := by simp_rw [dens, ← add_div, ← Nat.cast_add, card_union_add_card_inter] lemma dens_inter_add_dens_union (s t : Finset α) : dens (s ∩ t) + dens (s ∪ t) = dens s + dens t := by rw [add_comm, dens_union_add_dens_inter] @[simp] lemma dens_union_of_disjoint (h : Disjoint s t) : dens (s ∪ t) = dens s + dens t := by rw [← disjUnion_eq_union s t h, dens_disjUnion _ _ _] lemma dens_sdiff_add_dens_eq_dens (h : s ⊆ t) : dens (t \ s) + dens s = dens t := by simp [dens, ← card_sdiff_add_card_eq_card h, add_div] lemma dens_sdiff_add_dens (s t : Finset α) : dens (s \ t) + dens t = (s ∪ t).dens := by rw [← dens_union_of_disjoint sdiff_disjoint, sdiff_union_self_eq_union] lemma dens_sdiff_comm (h : card s = card t) : dens (s \ t) = dens (t \ s) := add_left_injective (dens t) $ by simp_rw [dens_sdiff_add_dens, union_comm s, ← dens_sdiff_add_dens, dens, h] @[simp] lemma dens_sdiff_add_dens_inter (s t : Finset α) : dens (s \ t) + dens (s ∩ t) = dens s := by rw [← dens_union_of_disjoint (disjoint_sdiff_inter _ _), sdiff_union_inter] @[simp] lemma dens_inter_add_dens_sdiff (s t : Finset α) : dens (s ∩ t) + dens (s \ t) = dens s := by rw [add_comm, dens_sdiff_add_dens_inter] lemma dens_filter_add_dens_filter_not_eq_dens {α : Type*} [Fintype α] {s : Finset α} (p : α → Prop) [DecidablePred p] [∀ x, Decidable (¬p x)] : dens (s.filter p) + dens (s.filter fun a ↦ ¬ p a) = dens s := by classical rw [← dens_union_of_disjoint (disjoint_filter_filter_neg ..), filter_union_filter_neg_eq] lemma dens_union_le (s t : Finset α) : dens (s ∪ t) ≤ dens s + dens t := dens_union_add_dens_inter s t ▸ le_add_of_nonneg_right zero_le' lemma dens_le_dens_sdiff_add_dens : dens s ≤ dens (s \ t) + dens t := dens_sdiff_add_dens s _ ▸ dens_le_dens subset_union_left lemma dens_sdiff (h : s ⊆ t) : dens (t \ s) = dens t - dens s := eq_tsub_of_add_eq (dens_sdiff_add_dens_eq_dens h) lemma le_dens_sdiff (s t : Finset α) : dens t - dens s ≤ dens (t \ s) := tsub_le_iff_right.2 dens_le_dens_sdiff_add_dens end Lattice end Finset
Data\Finset\Fin.lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Scott Morrison, Johan Commelin -/ import Mathlib.Data.Finset.Card /-! # Finsets in `Fin n` A few constructions for Finsets in `Fin n`. ## Main declarations * `Finset.attachFin`: Turns a Finset of naturals strictly less than `n` into a `Finset (Fin n)`. -/ variable {n : ℕ} namespace Finset /-- Given a Finset `s` of `ℕ` contained in `{0,..., n-1}`, the corresponding Finset in `Fin n` is `s.attachFin h` where `h` is a proof that all elements of `s` are less than `n`. -/ def attachFin (s : Finset ℕ) {n : ℕ} (h : ∀ m ∈ s, m < n) : Finset (Fin n) := ⟨s.1.pmap (fun a ha ↦ ⟨a, ha⟩) h, s.nodup.pmap fun _ _ _ _ ↦ Fin.val_eq_of_eq⟩ @[simp] theorem mem_attachFin {n : ℕ} {s : Finset ℕ} (h : ∀ m ∈ s, m < n) {a : Fin n} : a ∈ s.attachFin h ↔ (a : ℕ) ∈ s := ⟨fun h ↦ let ⟨_, hb₁, hb₂⟩ := Multiset.mem_pmap.1 h hb₂ ▸ hb₁, fun h ↦ Multiset.mem_pmap.2 ⟨a, h, Fin.eta _ _⟩⟩ @[simp] theorem card_attachFin {n : ℕ} (s : Finset ℕ) (h : ∀ m ∈ s, m < n) : (s.attachFin h).card = s.card := Multiset.card_pmap _ _ _ end Finset
Data\Finset\Finsupp.lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import Mathlib.Algebra.BigOperators.Finsupp import Mathlib.Data.Finset.Pointwise import Mathlib.Data.Finsupp.Indicator import Mathlib.Data.Fintype.BigOperators /-! # Finitely supported product of finsets This file defines the finitely supported product of finsets as a `Finset (ι →₀ α)`. ## Main declarations * `Finset.finsupp`: Finitely supported product of finsets. `s.finset t` is the product of the `t i` over all `i ∈ s`. * `Finsupp.pi`: `f.pi` is the finset of `Finsupp`s whose `i`-th value lies in `f i`. This is the special case of `Finset.finsupp` where we take the product of the `f i` over the support of `f`. ## Implementation notes We make heavy use of the fact that `0 : Finset α` is `{0}`. This scalar actions convention turns out to be precisely what we want here too. -/ noncomputable section open Finsupp open scoped Classical open Pointwise variable {ι α : Type*} [Zero α] {s : Finset ι} {f : ι →₀ α} namespace Finset /-- Finitely supported product of finsets. -/ protected def finsupp (s : Finset ι) (t : ι → Finset α) : Finset (ι →₀ α) := (s.pi t).map ⟨indicator s, indicator_injective s⟩ theorem mem_finsupp_iff {t : ι → Finset α} : f ∈ s.finsupp t ↔ f.support ⊆ s ∧ ∀ i ∈ s, f i ∈ t i := by refine mem_map.trans ⟨?_, ?_⟩ · rintro ⟨f, hf, rfl⟩ refine ⟨support_indicator_subset _ _, fun i hi => ?_⟩ convert mem_pi.1 hf i hi exact indicator_of_mem hi _ · refine fun h => ⟨fun i _ => f i, mem_pi.2 h.2, ?_⟩ ext i exact ite_eq_left_iff.2 fun hi => (not_mem_support_iff.1 fun H => hi <| h.1 H).symm /-- When `t` is supported on `s`, `f ∈ s.finsupp t` precisely means that `f` is pointwise in `t`. -/ @[simp] theorem mem_finsupp_iff_of_support_subset {t : ι →₀ Finset α} (ht : t.support ⊆ s) : f ∈ s.finsupp t ↔ ∀ i, f i ∈ t i := by refine mem_finsupp_iff.trans (forall_and.symm.trans <| forall_congr' fun i => ⟨fun h => ?_, fun h => ⟨fun hi => ht <| mem_support_iff.2 fun H => mem_support_iff.1 hi ?_, fun _ => h⟩⟩) · by_cases hi : i ∈ s · exact h.2 hi · rw [not_mem_support_iff.1 (mt h.1 hi), not_mem_support_iff.1 fun H => hi <| ht H] exact zero_mem_zero · rwa [H, mem_zero] at h @[simp] theorem card_finsupp (s : Finset ι) (t : ι → Finset α) : (s.finsupp t).card = ∏ i ∈ s, (t i).card := (card_map _).trans <| card_pi _ _ end Finset open Finset namespace Finsupp /-- Given a finitely supported function `f : ι →₀ Finset α`, one can define the finset `f.pi` of all finitely supported functions whose value at `i` is in `f i` for all `i`. -/ def pi (f : ι →₀ Finset α) : Finset (ι →₀ α) := f.support.finsupp f @[simp] theorem mem_pi {f : ι →₀ Finset α} {g : ι →₀ α} : g ∈ f.pi ↔ ∀ i, g i ∈ f i := mem_finsupp_iff_of_support_subset <| Subset.refl _ @[simp] theorem card_pi (f : ι →₀ Finset α) : f.pi.card = f.prod fun i => (f i).card := by rw [pi, card_finsupp] exact Finset.prod_congr rfl fun i _ => by simp only [Pi.natCast_apply, Nat.cast_id] end Finsupp
Data\Finset\Fold.lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Algebra.Order.Monoid.Unbundled.MinMax import Mathlib.Data.Finset.Image import Mathlib.Data.Multiset.Fold import Mathlib.Algebra.Order.Monoid.Unbundled.WithTop /-! # The fold operation for a commutative associative operation over a finset. -/ -- TODO: -- assert_not_exists OrderedCommMonoid assert_not_exists MonoidWithZero namespace Finset open Multiset variable {α β γ : Type*} /-! ### fold -/ section Fold variable (op : β → β → β) [hc : Std.Commutative op] [ha : Std.Associative op] local notation a " * " b => op a b /-- `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 variable {op} {f : α → β} {b : β} {s : Finset α} {a : α} @[simp] theorem fold_empty : (∅ : Finset α).fold op b f = b := rfl @[simp] theorem fold_cons (h : a ∉ s) : (cons a s h).fold op b f = f a * s.fold op b f := by dsimp only [fold] rw [cons_val, Multiset.map_cons, fold_cons_left] @[simp] theorem fold_insert [DecidableEq α] (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, Multiset.map_cons, fold_cons_left] @[simp] theorem fold_singleton : ({a} : Finset α).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 [DecidableEq α] {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_injOn 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 rfl H] theorem fold_op_distrib {f g : α → β} {b₁ b₂ : β} : (s.fold op (b₁ * b₂) fun x => f x * g x) = s.fold op b₁ f * s.fold op b₂ g := by simp only [fold, fold_distrib] theorem fold_const [hd : Decidable (s = ∅)] (c : β) (h : op c (op b c) = op b c) : Finset.fold op b (fun _ => c) s = if s = ∅ then b else op b c := by classical induction' s using Finset.induction_on with x s hx IH generalizing hd · simp · simp only [Finset.fold_insert hx, IH, if_false, Finset.insert_ne_empty] split_ifs · rw [hc.comm] · exact h theorem fold_hom {op' : γ → γ → γ} [Std.Commutative op'] [Std.Associative op'] {m : β → γ} (hm : ∀ x y, m (op x y) = op' (m x) (m y)) : (s.fold op' (m b) fun x => m (f x)) = m (s.fold op b f) := by rw [fold, fold, ← Multiset.fold_hom op hm, Multiset.map_map] simp only [Function.comp_apply] theorem fold_disjUnion {s₁ s₂ : Finset α} {b₁ b₂ : β} (h) : (s₁.disjUnion s₂ h).fold op (b₁ * b₂) f = s₁.fold op b₁ f * s₂.fold op b₂ f := (congr_arg _ <| Multiset.map_add _ _ _).trans (Multiset.fold_add _ _ _ _ _) theorem fold_disjiUnion {ι : Type*} {s : Finset ι} {t : ι → Finset α} {b : ι → β} {b₀ : β} (h) : (s.disjiUnion t h).fold op (s.fold op b₀ b) f = s.fold op b₀ fun i => (t i).fold op (b i) f := (congr_arg _ <| Multiset.map_bind _ _ _).trans (Multiset.fold_bind _ _ _ _ _) theorem fold_union_inter [DecidableEq α] {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, ← Multiset.map_add, union_val, inter_val, union_add_inter, Multiset.map_add, hc.comm, fold_add] @[simp] theorem fold_insert_idem [DecidableEq α] [hi : Std.IdempotentOp op] : (insert a s).fold op b f = f a * s.fold op b f := by by_cases h : a ∈ s · rw [← insert_erase h] simp [← ha.assoc, hi.idempotent] · apply fold_insert h theorem fold_image_idem [DecidableEq α] {g : γ → α} {s : Finset γ} [hi : Std.IdempotentOp op] : (image g s).fold op b f = s.fold op b (f ∘ g) := by induction' s using Finset.cons_induction with x xs hx ih · rw [fold_empty, image_empty, fold_empty] · haveI := Classical.decEq γ rw [fold_cons, cons_eq_insert, image_insert, fold_insert_idem, ih] simp only [Function.comp_apply] /-- A stronger version of `Finset.fold_ite`, but relies on an explicit proof of idempotency on the seed element, rather than relying on typeclass idempotency over the whole type. -/ theorem fold_ite' {g : α → β} (hb : op b b = b) (p : α → Prop) [DecidablePred p] : Finset.fold op b (fun i => ite (p i) (f i) (g i)) s = op (Finset.fold op b f (s.filter p)) (Finset.fold op b g (s.filter fun i => ¬p i)) := by classical induction' s using Finset.induction_on with x s hx IH · simp [hb] · simp only [Finset.fold_insert hx] split_ifs with h · have : x ∉ Finset.filter p s := by simp [hx] simp [Finset.filter_insert, h, Finset.fold_insert this, ha.assoc, IH] · have : x ∉ Finset.filter (fun i => ¬ p i) s := by simp [hx] simp [Finset.filter_insert, h, Finset.fold_insert this, IH, ← ha.assoc, hc.comm] /-- A weaker version of `Finset.fold_ite'`, relying on typeclass idempotency over the whole type, instead of solely on the seed element. However, this is easier to use because it does not generate side goals. -/ theorem fold_ite [Std.IdempotentOp op] {g : α → β} (p : α → Prop) [DecidablePred p] : Finset.fold op b (fun i => ite (p i) (f i) (g i)) s = op (Finset.fold op b f (s.filter p)) (Finset.fold op b g (s.filter fun i => ¬p i)) := fold_ite' (Std.IdempotentOp.idempotent _) _ theorem fold_op_rel_iff_and {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) := by classical induction' s using Finset.induction_on with a s ha IH · simp rw [Finset.fold_insert ha, hr, IH, ← and_assoc, @and_comm (r c (f a)), and_assoc] apply and_congr Iff.rfl constructor · rintro ⟨h₁, h₂⟩ intro b hb rw [Finset.mem_insert] at hb rcases hb with (rfl | hb) <;> solve_by_elim · intro h constructor · exact h a (Finset.mem_insert_self _ _) · exact fun b hb => h b <| Finset.mem_insert_of_mem hb theorem fold_op_rel_iff_or {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) := by classical induction' s using Finset.induction_on with a s ha IH · simp rw [Finset.fold_insert ha, hr, IH, ← or_assoc, @or_comm (r c (f a)), or_assoc] apply or_congr Iff.rfl constructor · rintro (h₁ | ⟨x, hx, h₂⟩) · use a simp [h₁] · refine ⟨x, by simp [hx], h₂⟩ · rintro ⟨x, hx, h⟩ exact (mem_insert.mp hx).imp (fun hx => by rwa [hx] at h) (fun hx => ⟨x, hx, h⟩) @[simp] theorem fold_union_empty_singleton [DecidableEq α] (s : Finset α) : Finset.fold (· ∪ ·) ∅ singleton s = s := by induction' s using Finset.induction_on with a s has ih · simp only [fold_empty] · rw [fold_insert has, ih, insert_eq] theorem fold_sup_bot_singleton [DecidableEq α] (s : Finset α) : Finset.fold (· ⊔ ·) ⊥ singleton s = s := fold_union_empty_singleton s section Order variable [LinearOrder β] (c : β) theorem le_fold_min : c ≤ s.fold min b f ↔ c ≤ b ∧ ∀ x ∈ s, c ≤ f x := fold_op_rel_iff_and le_min_iff theorem fold_min_le : s.fold min b f ≤ c ↔ b ≤ c ∨ ∃ x ∈ s, f x ≤ c := by show _ ≥ _ ↔ _ apply fold_op_rel_iff_or intro x y z show _ ≤ _ ↔ _ exact min_le_iff theorem lt_fold_min : c < s.fold min b f ↔ c < b ∧ ∀ x ∈ s, c < f x := fold_op_rel_iff_and lt_min_iff theorem fold_min_lt : s.fold min b f < c ↔ b < c ∨ ∃ x ∈ s, f x < c := by show _ > _ ↔ _ apply fold_op_rel_iff_or intro x y z show _ < _ ↔ _ exact min_lt_iff theorem fold_max_le : s.fold max b f ≤ c ↔ b ≤ c ∧ ∀ x ∈ s, f x ≤ c := by show _ ≥ _ ↔ _ apply fold_op_rel_iff_and intro x y z show _ ≤ _ ↔ _ exact max_le_iff theorem le_fold_max : c ≤ s.fold max b f ↔ c ≤ b ∨ ∃ x ∈ s, c ≤ f x := fold_op_rel_iff_or le_max_iff theorem fold_max_lt : s.fold max b f < c ↔ b < c ∧ ∀ x ∈ s, f x < c := by show _ > _ ↔ _ apply fold_op_rel_iff_and intro x y z show _ < _ ↔ _ exact max_lt_iff theorem lt_fold_max : c < s.fold max b f ↔ c < b ∨ ∃ x ∈ s, c < f x := fold_op_rel_iff_or lt_max_iff theorem fold_max_add [Add β] [CovariantClass β β (Function.swap (· + ·)) (· ≤ ·)] (n : WithBot β) (s : Finset α) : (s.fold max ⊥ fun x : α => ↑(f x) + n) = s.fold max ⊥ ((↑) ∘ f) + n := by classical induction' s using Finset.induction_on with a s _ ih <;> simp [*, max_add_add_right] end Order end Fold end Finset