path
stringlengths
11
71
content
stringlengths
75
124k
Data\Finset\Functor.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, Scott Morrison -/ import Mathlib.Data.Finset.Lattice import Mathlib.Data.Finset.NAry import Mathlib.Data.Multiset.Functor /-! # Functoriality of `Finset` This file defines the functor structure of `Finset`. ## TODO Currently, all instances are classical because the functor classes want to run over all types. If instead we could state that a functor is lawful/applicative/traversable... between two given types, then we could provide the instances for types with decidable equality. -/ universe u open Function namespace Finset /-! ### Functor -/ section Functor variable {α β : Type u} [∀ P, Decidable P] /-- Because `Finset.image` requires a `DecidableEq` instance for the target type, we can only construct `Functor Finset` when working classically. -/ protected instance functor : Functor Finset where map f s := s.image f instance lawfulFunctor : LawfulFunctor Finset where id_map s := image_id comp_map f g s := image_image.symm map_const {α} {β} := by simp only [Functor.mapConst, Functor.map] @[simp] theorem fmap_def {s : Finset α} (f : α → β) : f <$> s = s.image f := rfl end Functor /-! ### Pure -/ protected instance pure : Pure Finset := ⟨fun x => {x}⟩ @[simp] theorem pure_def {α} : (pure : α → Finset α) = singleton := rfl /-! ### Applicative functor -/ section Applicative variable {α β : Type u} [∀ P, Decidable P] protected instance applicative : Applicative Finset := { Finset.functor, Finset.pure with seq := fun t s => t.sup fun f => (s ()).image f seqLeft := fun s t => if t () = ∅ then ∅ else s seqRight := fun s t => if s = ∅ then ∅ else t () } @[simp] theorem seq_def (s : Finset α) (t : Finset (α → β)) : t <*> s = t.sup fun f => s.image f := rfl @[simp] theorem seqLeft_def (s : Finset α) (t : Finset β) : s <* t = if t = ∅ then ∅ else s := rfl @[simp] theorem seqRight_def (s : Finset α) (t : Finset β) : s *> t = if s = ∅ then ∅ else t := rfl /-- `Finset.image₂` in terms of monadic operations. Note that this can't be taken as the definition because of the lack of universe polymorphism. -/ theorem image₂_def {α β γ : Type u} (f : α → β → γ) (s : Finset α) (t : Finset β) : image₂ f s t = f <$> s <*> t := by ext simp [mem_sup] instance lawfulApplicative : LawfulApplicative Finset := { Finset.lawfulFunctor with seqLeft_eq := fun s t => by rw [seq_def, fmap_def, seqLeft_def] obtain rfl | ht := t.eq_empty_or_nonempty · simp_rw [image_empty, if_true] exact (sup_bot _).symm · ext a rw [if_neg ht.ne_empty, mem_sup] refine ⟨fun ha => ⟨const _ a, mem_image_of_mem _ ha, mem_image_const_self.2 ht⟩, ?_⟩ rintro ⟨f, hf, ha⟩ rw [mem_image] at hf ha obtain ⟨b, hb, rfl⟩ := hf obtain ⟨_, _, rfl⟩ := ha exact hb seqRight_eq := fun s t => by rw [seq_def, fmap_def, seqRight_def] obtain rfl | hs := s.eq_empty_or_nonempty · rw [if_pos rfl, image_empty, sup_empty, bot_eq_empty] · ext a rw [if_neg hs.ne_empty, mem_sup] refine ⟨fun ha => ⟨id, mem_image_const_self.2 hs, by rwa [image_id]⟩, ?_⟩ rintro ⟨f, hf, ha⟩ rw [mem_image] at hf ha obtain ⟨b, hb, rfl⟩ := ha obtain ⟨_, _, rfl⟩ := hf exact hb pure_seq := fun f s => by simp only [pure_def, seq_def, sup_singleton, fmap_def] map_pure := fun f a => image_singleton _ _ seq_pure := fun s a => sup_singleton'' _ _ seq_assoc := fun s t u => by ext a simp_rw [seq_def, fmap_def] simp only [exists_prop, mem_sup, mem_image] constructor · rintro ⟨g, hg, b, ⟨f, hf, a, ha, rfl⟩, rfl⟩ exact ⟨g ∘ f, ⟨comp g, ⟨g, hg, rfl⟩, f, hf, rfl⟩, a, ha, rfl⟩ · rintro ⟨c, ⟨_, ⟨g, hg, rfl⟩, f, hf, rfl⟩, a, ha, rfl⟩ exact ⟨g, hg, f a, ⟨f, hf, a, ha, rfl⟩, rfl⟩ } instance commApplicative : CommApplicative Finset := { Finset.lawfulApplicative with commutative_prod := fun s t => by simp_rw [seq_def, fmap_def, sup_image, sup_eq_biUnion] change (s.biUnion fun a => t.image fun b => (a, b)) = t.biUnion fun b => s.image fun a => (a, b) trans s ×ˢ t <;> [rw [product_eq_biUnion]; rw [product_eq_biUnion_right]] } end Applicative /-! ### Monad -/ section Monad variable [∀ P, Decidable P] instance : Monad Finset := { Finset.applicative with bind := sup } @[simp] theorem bind_def {α β} : (· >>= ·) = sup (α := Finset α) (β := β) := rfl instance : LawfulMonad Finset := { Finset.lawfulApplicative with bind_pure_comp := fun f s => sup_singleton'' _ _ bind_map := fun t s => rfl pure_bind := fun t s => sup_singleton bind_assoc := fun s f g => by simp only [bind, ← sup_biUnion, sup_eq_biUnion, biUnion_biUnion] } end Monad /-! ### Alternative functor -/ section Alternative variable [∀ P, Decidable P] instance : Alternative Finset := { Finset.applicative with orElse := fun s t => (s ∪ t ()) failure := ∅ } end Alternative /-! ### Traversable functor -/ section Traversable variable {α β γ : Type u} {F G : Type u → Type u} [Applicative F] [Applicative G] [CommApplicative F] [CommApplicative G] /-- Traverse function for `Finset`. -/ def traverse [DecidableEq β] (f : α → F β) (s : Finset α) : F (Finset β) := Multiset.toFinset <$> Multiset.traverse f s.1 @[simp] theorem id_traverse [DecidableEq α] (s : Finset α) : traverse (pure : α → Id α) s = s := by rw [traverse, Multiset.id_traverse] exact s.val_toFinset open scoped Classical @[simp] theorem map_comp_coe (h : α → β) : Functor.map h ∘ Multiset.toFinset = Multiset.toFinset ∘ Functor.map h := funext fun _ => image_toFinset theorem map_traverse (g : α → G β) (h : β → γ) (s : Finset α) : Functor.map h <$> traverse g s = traverse (Functor.map h ∘ g) s := by unfold traverse simp only [map_comp_coe, functor_norm] rw [LawfulFunctor.comp_map, Multiset.map_traverse] end Traversable end Finset
Data\Finset\Grade.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.Data.Finset.Card import Mathlib.Data.Set.Finite import Mathlib.Order.Atoms import Mathlib.Order.Grade /-! # Finsets and multisets form a graded order This file characterises atoms, coatoms and the covering relation in finsets and multisets. It also proves that they form a `ℕ`-graded order. ## Main declarations * `Multiset.instGradeMinOrder_nat`: Multisets are `ℕ`-graded * `Finset.instGradeMinOrder_nat`: Finsets are `ℕ`-graded -/ open Order variable {α : Type*} namespace Multiset variable {s t : Multiset α} {a : α} @[simp] lemma covBy_cons (s : Multiset α) (a : α) : s ⋖ a ::ₘ s := ⟨lt_cons_self _ _, fun t hst hts ↦ (covBy_succ _).2 (card_lt_card hst) <| by simpa using card_lt_card hts⟩ lemma _root_.CovBy.exists_multiset_cons (h : s ⋖ t) : ∃ a, a ::ₘ s = t := (lt_iff_cons_le.1 h.lt).imp fun _a ha ↦ ha.eq_of_not_lt <| h.2 <| lt_cons_self _ _ lemma covBy_iff : s ⋖ t ↔ ∃ a, a ::ₘ s = t := ⟨CovBy.exists_multiset_cons, by rintro ⟨a, rfl⟩; exact covBy_cons _ _⟩ lemma _root_.CovBy.card_multiset (h : s ⋖ t) : card s ⋖ card t := by obtain ⟨a, rfl⟩ := h.exists_multiset_cons; rw [card_cons]; exact covBy_succ _ lemma isAtom_iff : IsAtom s ↔ ∃ a, s = {a} := by simp [← bot_covBy_iff, covBy_iff, eq_comm] @[simp] lemma isAtom_singleton (a : α) : IsAtom ({a} : Multiset α) := isAtom_iff.2 ⟨_, rfl⟩ instance instGradeMinOrder : GradeMinOrder ℕ (Multiset α) where grade := card grade_strictMono := card_strictMono covBy_grade s t := CovBy.card_multiset isMin_grade s hs := by rw [isMin_iff_eq_bot.1 hs]; exact isMin_bot @[simp] lemma grade_eq (m : Multiset α) : grade ℕ m = card m := rfl end Multiset namespace Finset variable {s t : Finset α} {a : α} /-- Finsets form an order-connected suborder of multisets. -/ lemma ordConnected_range_val : Set.OrdConnected (Set.range val : Set <| Multiset α) := ⟨by rintro _ _ _ ⟨s, rfl⟩ t ht; exact ⟨⟨t, Multiset.nodup_of_le ht.2 s.2⟩, rfl⟩⟩ /-- Finsets form an order-connected suborder of sets. -/ lemma ordConnected_range_coe : Set.OrdConnected (Set.range ((↑) : Finset α → Set α)) := ⟨by rintro _ _ _ ⟨s, rfl⟩ t ht; exact ⟨_, (s.finite_toSet.subset ht.2).coe_toFinset⟩⟩ @[simp] lemma val_wcovBy_val : s.1 ⩿ t.1 ↔ s ⩿ t := ordConnected_range_val.apply_wcovBy_apply_iff ⟨⟨_, val_injective⟩, val_le_iff⟩ @[simp] lemma val_covBy_val : s.1 ⋖ t.1 ↔ s ⋖ t := ordConnected_range_val.apply_covBy_apply_iff ⟨⟨_, val_injective⟩, val_le_iff⟩ @[simp] lemma coe_wcovBy_coe : (s : Set α) ⩿ t ↔ s ⩿ t := ordConnected_range_coe.apply_wcovBy_apply_iff ⟨⟨_, coe_injective⟩, coe_subset⟩ @[simp] lemma coe_covBy_coe : (s : Set α) ⋖ t ↔ s ⋖ t := ordConnected_range_coe.apply_covBy_apply_iff ⟨⟨_, coe_injective⟩, coe_subset⟩ alias ⟨_, _root_.WCovBy.finset_val⟩ := val_wcovBy_val alias ⟨_, _root_.CovBy.finset_val⟩ := val_covBy_val alias ⟨_, _root_.WCovBy.finset_coe⟩ := coe_wcovBy_coe alias ⟨_, _root_.CovBy.finset_coe⟩ := coe_covBy_coe @[simp] lemma covBy_cons (ha : a ∉ s) : s ⋖ s.cons a ha := by simp [← val_covBy_val] lemma _root_.CovBy.exists_finset_cons (h : s ⋖ t) : ∃ a, ∃ ha : a ∉ s, s.cons a ha = t := let ⟨a, ha, hst⟩ := ssubset_iff_exists_cons_subset.1 h.lt ⟨a, ha, (hst.eq_of_not_ssuperset <| h.2 <| ssubset_cons _).symm⟩ lemma covBy_iff_exists_cons : s ⋖ t ↔ ∃ a, ∃ ha : a ∉ s, s.cons a ha = t := ⟨CovBy.exists_finset_cons, by rintro ⟨a, ha, rfl⟩; exact covBy_cons _⟩ lemma _root_.CovBy.card_finset (h : s ⋖ t) : s.card ⋖ t.card := (val_covBy_val.2 h).card_multiset section DecidableEq variable [DecidableEq α] @[simp] lemma wcovBy_insert (s : Finset α) (a : α) : s ⩿ insert a s := by simp [← coe_wcovBy_coe] @[simp] lemma erase_wcovBy (s : Finset α) (a : α) : s.erase a ⩿ s := by simp [← coe_wcovBy_coe] lemma covBy_insert (ha : a ∉ s) : s ⋖ insert a s := (wcovBy_insert _ _).covBy_of_lt <| ssubset_insert ha @[simp] lemma erase_covBy (ha : a ∈ s) : s.erase a ⋖ s := ⟨erase_ssubset ha, (erase_wcovBy _ _).2⟩ lemma _root_.CovBy.exists_finset_insert (h : s ⋖ t) : ∃ a ∉ s, insert a s = t := by simpa using h.exists_finset_cons lemma _root_.CovBy.exists_finset_erase (h : s ⋖ t) : ∃ a ∈ t, t.erase a = s := by simpa only [← coe_inj, coe_erase] using h.finset_coe.exists_set_sdiff_singleton lemma covBy_iff_exists_insert : s ⋖ t ↔ ∃ a ∉ s, insert a s = t := by simp only [← coe_covBy_coe, Set.covBy_iff_exists_insert, ← coe_inj, coe_insert, mem_coe] lemma covBy_iff_card_sdiff_eq_one : t ⋖ s ↔ t ⊆ s ∧ (s \ t).card = 1 := by rw [covBy_iff_exists_insert] constructor · rintro ⟨a, ha, rfl⟩ simp [*] · simp_rw [card_eq_one] rintro ⟨hts, a, ha⟩ refine ⟨a, (mem_sdiff.1 <| superset_of_eq ha <| mem_singleton_self _).2, ?_⟩ rw [insert_eq, ← ha, sdiff_union_of_subset hts] lemma covBy_iff_exists_erase : s ⋖ t ↔ ∃ a ∈ t, t.erase a = s := by simp only [← coe_covBy_coe, Set.covBy_iff_exists_sdiff_singleton, ← coe_inj, coe_erase, mem_coe] end DecidableEq @[simp] lemma isAtom_singleton (a : α) : IsAtom ({a} : Finset α) := ⟨singleton_ne_empty a, fun _ ↦ eq_empty_of_ssubset_singleton⟩ protected lemma isAtom_iff : IsAtom s ↔ ∃ a, s = {a} := by simp [← bot_covBy_iff, covBy_iff_exists_cons, eq_comm] section Fintype variable [Fintype α] [DecidableEq α] lemma isCoatom_compl_singleton (a : α) : IsCoatom ({a}ᶜ : Finset α) := (isAtom_singleton a).compl protected lemma isCoatom_iff : IsCoatom s ↔ ∃ a, s = {a}ᶜ := by simp_rw [← isAtom_compl, Finset.isAtom_iff, compl_eq_iff_isCompl, eq_compl_iff_isCompl] end Fintype /-- Finsets are multiset-graded. This is not very meaningful mathematically but rather a handy way to record that the inclusion `Finset α ↪ Multiset α` preserves the covering relation. -/ instance instGradeMinOrder_multiset : GradeMinOrder (Multiset α) (Finset α) where grade := val grade_strictMono := val_strictMono covBy_grade _ _ := CovBy.finset_val isMin_grade s hs := by rw [isMin_iff_eq_bot.1 hs]; exact isMin_bot @[simp] lemma grade_multiset_eq (s : Finset α) : grade (Multiset α) s = s.1 := rfl instance instGradeMinOrder_nat : GradeMinOrder ℕ (Finset α) where grade := card grade_strictMono := card_strictMono covBy_grade _ _ := CovBy.card_finset isMin_grade s hs := by rw [isMin_iff_eq_bot.1 hs]; exact isMin_bot @[simp] lemma grade_eq (s : Finset α) : grade ℕ s = s.card := rfl end Finset
Data\Finset\Image.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.Algebra.Group.Embedding import Mathlib.Data.Fin.Basic import Mathlib.Data.Finset.Union /-! # Image and map operations on finite sets This file provides the finite analog of `Set.image`, along with some other similar functions. Note there are two ways to take the image over a finset; via `Finset.image` which applies the function then removes duplicates (requiring `DecidableEq`), or via `Finset.map` which exploits injectivity of the function to avoid needing to deduplicate. Choosing between these is similar to choosing between `insert` and `Finset.cons`, or between `Finset.union` and `Finset.disjUnion`. ## Main definitions * `Finset.image`: Given a function `f : α → β`, `s.image f` is the image finset in `β`. * `Finset.map`: Given an embedding `f : α ↪ β`, `s.map f` is the image finset in `β`. * `Finset.filterMap` Given a function `f : α → Option β`, `s.filterMap f` is the image finset in `β`, filtering out `none`s. * `Finset.subtype`: `s.subtype p` is the finset of `Subtype p` whose elements belong to `s`. * `Finset.fin`:`s.fin n` is the finset of all elements of `s` less than `n`. ## TODO Move the material about `Finset.range` so that the `Mathlib.Algebra.Group.Embedding` import can be removed. -/ -- TODO -- assert_not_exists OrderedCommMonoid assert_not_exists MonoidWithZero assert_not_exists MulAction variable {α β γ : Type*} open Multiset open Function namespace Finset /-! ### map -/ section Map open Function /-- When `f` is an embedding of `α` in `β` and `s` is a finset in `α`, then `s.map f` is the image finset in `β`. The embedding condition guarantees that there are no duplicates in the image. -/ def map (f : α ↪ β) (s : Finset α) : Finset β := ⟨s.1.map f, s.2.map f.2⟩ @[simp] theorem map_val (f : α ↪ β) (s : Finset α) : (map f s).1 = s.1.map f := rfl @[simp] theorem map_empty (f : α ↪ β) : (∅ : Finset α).map f = ∅ := rfl variable {f : α ↪ β} {s : Finset α} @[simp] theorem mem_map {b : β} : b ∈ s.map f ↔ ∃ a ∈ s, f a = b := Multiset.mem_map -- Porting note: Higher priority to apply before `mem_map`. @[simp 1100] theorem mem_map_equiv {f : α ≃ β} {b : β} : b ∈ s.map f.toEmbedding ↔ f.symm b ∈ s := by rw [mem_map] exact ⟨by rintro ⟨a, H, rfl⟩ simpa, fun h => ⟨_, h, by simp⟩⟩ @[simp 1100] theorem mem_map' (f : α ↪ β) {a} {s : Finset α} : f a ∈ s.map f ↔ a ∈ s := mem_map_of_injective f.2 theorem mem_map_of_mem (f : α ↪ β) {a} {s : Finset α} : a ∈ s → f a ∈ s.map f := (mem_map' _).2 theorem forall_mem_map {f : α ↪ β} {s : Finset α} {p : ∀ a, a ∈ s.map f → Prop} : (∀ y (H : y ∈ s.map f), p y H) ↔ ∀ x (H : x ∈ s), p (f x) (mem_map_of_mem _ H) := ⟨fun h y hy => h (f y) (mem_map_of_mem _ hy), fun h x hx => by obtain ⟨y, hy, rfl⟩ := mem_map.1 hx exact h _ hy⟩ theorem apply_coe_mem_map (f : α ↪ β) (s : Finset α) (x : s) : f x ∈ s.map f := mem_map_of_mem f x.prop @[simp, norm_cast] theorem coe_map (f : α ↪ β) (s : Finset α) : (s.map f : Set β) = f '' s := Set.ext (by simp only [mem_coe, mem_map, Set.mem_image, implies_true]) theorem coe_map_subset_range (f : α ↪ β) (s : Finset α) : (s.map f : Set β) ⊆ Set.range f := calc ↑(s.map f) = f '' s := coe_map f s _ ⊆ Set.range f := Set.image_subset_range f ↑s /-- If the only elements outside `s` are those left fixed by `σ`, then mapping by `σ` has no effect. -/ theorem map_perm {σ : Equiv.Perm α} (hs : { a | σ a ≠ a } ⊆ s) : s.map (σ : α ↪ α) = s := coe_injective <| (coe_map _ _).trans <| Set.image_perm hs theorem map_toFinset [DecidableEq α] [DecidableEq β] {s : Multiset α} : s.toFinset.map f = (s.map f).toFinset := ext fun _ => by simp only [mem_map, Multiset.mem_map, exists_prop, Multiset.mem_toFinset] @[simp] theorem map_refl : s.map (Embedding.refl _) = s := ext fun _ => by simpa only [mem_map, exists_prop] using exists_eq_right @[simp] theorem map_cast_heq {α β} (h : α = β) (s : Finset α) : HEq (s.map (Equiv.cast h).toEmbedding) s := by subst h simp theorem map_map (f : α ↪ β) (g : β ↪ γ) (s : Finset α) : (s.map f).map g = s.map (f.trans g) := eq_of_veq <| by simp only [map_val, Multiset.map_map]; rfl theorem map_comm {β'} {f : β ↪ γ} {g : α ↪ β} {f' : α ↪ β'} {g' : β' ↪ γ} (h_comm : ∀ a, f (g a) = g' (f' a)) : (s.map g).map f = (s.map f').map g' := by simp_rw [map_map, Embedding.trans, Function.comp, h_comm] theorem _root_.Function.Semiconj.finset_map {f : α ↪ β} {ga : α ↪ α} {gb : β ↪ β} (h : Function.Semiconj f ga gb) : Function.Semiconj (map f) (map ga) (map gb) := fun _ => map_comm h theorem _root_.Function.Commute.finset_map {f g : α ↪ α} (h : Function.Commute f g) : Function.Commute (map f) (map g) := Function.Semiconj.finset_map h @[simp] theorem map_subset_map {s₁ s₂ : Finset α} : s₁.map f ⊆ s₂.map f ↔ s₁ ⊆ s₂ := ⟨fun h x xs => (mem_map' _).1 <| h <| (mem_map' f).2 xs, fun h => by simp [subset_def, Multiset.map_subset_map h]⟩ @[gcongr] alias ⟨_, _root_.GCongr.finsetMap_subset⟩ := map_subset_map /-- The `Finset` version of `Equiv.subset_symm_image`. -/ theorem subset_map_symm {t : Finset β} {f : α ≃ β} : s ⊆ t.map f.symm ↔ s.map f ⊆ t := by constructor <;> intro h x hx · simp only [mem_map_equiv, Equiv.symm_symm] at hx simpa using h hx · simp only [mem_map_equiv] exact h (by simp [hx]) /-- The `Finset` version of `Equiv.symm_image_subset`. -/ theorem map_symm_subset {t : Finset β} {f : α ≃ β} : t.map f.symm ⊆ s ↔ t ⊆ s.map f := by simp only [← subset_map_symm, Equiv.symm_symm] /-- Associate to an embedding `f` from `α` to `β` the order embedding that maps a finset to its image under `f`. -/ def mapEmbedding (f : α ↪ β) : Finset α ↪o Finset β := OrderEmbedding.ofMapLEIff (map f) fun _ _ => map_subset_map @[simp] theorem map_inj {s₁ s₂ : Finset α} : s₁.map f = s₂.map f ↔ s₁ = s₂ := (mapEmbedding f).injective.eq_iff theorem map_injective (f : α ↪ β) : Injective (map f) := (mapEmbedding f).injective @[simp] theorem map_ssubset_map {s t : Finset α} : s.map f ⊂ t.map f ↔ s ⊂ t := (mapEmbedding f).lt_iff_lt @[gcongr] alias ⟨_, _root_.GCongr.finsetMap_ssubset⟩ := map_ssubset_map @[simp] theorem mapEmbedding_apply : mapEmbedding f s = map f s := rfl theorem filter_map {p : β → Prop} [DecidablePred p] : (s.map f).filter p = (s.filter (p ∘ f)).map f := eq_of_veq (Multiset.filter_map _ _ _) lemma map_filter' (p : α → Prop) [DecidablePred p] (f : α ↪ β) (s : Finset α) [DecidablePred (∃ a, p a ∧ f a = ·)] : (s.filter p).map f = (s.map f).filter fun b => ∃ a, p a ∧ f a = b := by simp [(· ∘ ·), filter_map, f.injective.eq_iff] lemma filter_attach' [DecidableEq α] (s : Finset α) (p : s → Prop) [DecidablePred p] : s.attach.filter p = (s.filter fun x => ∃ h, p ⟨x, h⟩).attach.map ⟨Subtype.map id <| filter_subset _ _, Subtype.map_injective _ injective_id⟩ := eq_of_veq <| Multiset.filter_attach' _ _ lemma filter_attach (p : α → Prop) [DecidablePred p] (s : Finset α) : s.attach.filter (fun a : s ↦ p a) = (s.filter p).attach.map ((Embedding.refl _).subtypeMap mem_of_mem_filter) := eq_of_veq <| Multiset.filter_attach _ _ theorem map_filter {f : α ≃ β} {p : α → Prop} [DecidablePred p] : (s.filter p).map f.toEmbedding = (s.map f.toEmbedding).filter (p ∘ f.symm) := by simp only [filter_map, Function.comp, Equiv.toEmbedding_apply, Equiv.symm_apply_apply] @[simp] theorem disjoint_map {s t : Finset α} (f : α ↪ β) : Disjoint (s.map f) (t.map f) ↔ Disjoint s t := mod_cast Set.disjoint_image_iff f.injective (s := s) (t := t) theorem map_disjUnion {f : α ↪ β} (s₁ s₂ : Finset α) (h) (h' := (disjoint_map _).mpr h) : (s₁.disjUnion s₂ h).map f = (s₁.map f).disjUnion (s₂.map f) h' := eq_of_veq <| Multiset.map_add _ _ _ /-- A version of `Finset.map_disjUnion` for writing in the other direction. -/ theorem map_disjUnion' {f : α ↪ β} (s₁ s₂ : Finset α) (h') (h := (disjoint_map _).mp h') : (s₁.disjUnion s₂ h).map f = (s₁.map f).disjUnion (s₂.map f) h' := map_disjUnion _ _ _ theorem map_union [DecidableEq α] [DecidableEq β] {f : α ↪ β} (s₁ s₂ : Finset α) : (s₁ ∪ s₂).map f = s₁.map f ∪ s₂.map f := mod_cast Set.image_union f s₁ s₂ theorem map_inter [DecidableEq α] [DecidableEq β] {f : α ↪ β} (s₁ s₂ : Finset α) : (s₁ ∩ s₂).map f = s₁.map f ∩ s₂.map f := mod_cast Set.image_inter f.injective (s := s₁) (t := s₂) @[simp] theorem map_singleton (f : α ↪ β) (a : α) : map f {a} = {f a} := coe_injective <| by simp only [coe_map, coe_singleton, Set.image_singleton] @[simp] theorem map_insert [DecidableEq α] [DecidableEq β] (f : α ↪ β) (a : α) (s : Finset α) : (insert a s).map f = insert (f a) (s.map f) := by simp only [insert_eq, map_union, map_singleton] @[simp] theorem map_cons (f : α ↪ β) (a : α) (s : Finset α) (ha : a ∉ s) : (cons a s ha).map f = cons (f a) (s.map f) (by simpa using ha) := eq_of_veq <| Multiset.map_cons f a s.val @[simp] theorem map_eq_empty : s.map f = ∅ ↔ s = ∅ := (map_injective f).eq_iff' (map_empty f) @[simp, aesop safe apply (rule_sets := [finsetNonempty])] theorem map_nonempty : (s.map f).Nonempty ↔ s.Nonempty := mod_cast Set.image_nonempty (f := f) (s := s) protected alias ⟨_, Nonempty.map⟩ := map_nonempty @[simp] theorem map_nontrivial : (s.map f).Nontrivial ↔ s.Nontrivial := mod_cast Set.image_nontrivial f.injective (s := s) theorem attach_map_val {s : Finset α} : s.attach.map (Embedding.subtype _) = s := eq_of_veq <| by rw [map_val, attach_val]; exact Multiset.attach_map_val _ theorem disjoint_range_addLeftEmbedding (a : ℕ) (s : Finset ℕ): Disjoint (range a) (map (addLeftEmbedding a) s) := by simp_rw [disjoint_left, mem_map, mem_range, addLeftEmbedding_apply] rintro _ h ⟨l, -, rfl⟩ omega theorem disjoint_range_addRightEmbedding (a : ℕ) (s : Finset ℕ) : Disjoint (range a) (map (addRightEmbedding a) s) := by rw [← addLeftEmbedding_eq_addRightEmbedding] apply disjoint_range_addLeftEmbedding theorem map_disjiUnion {f : α ↪ β} {s : Finset α} {t : β → Finset γ} {h} : (s.map f).disjiUnion t h = s.disjiUnion (fun a => t (f a)) fun _ ha _ hb hab => h (mem_map_of_mem _ ha) (mem_map_of_mem _ hb) (f.injective.ne hab) := eq_of_veq <| Multiset.bind_map _ _ _ theorem disjiUnion_map {s : Finset α} {t : α → Finset β} {f : β ↪ γ} {h} : (s.disjiUnion t h).map f = s.disjiUnion (fun a => (t a).map f) (h.mono' fun _ _ ↦ (disjoint_map _).2) := eq_of_veq <| Multiset.map_bind _ _ _ end Map theorem range_add_one' (n : ℕ) : range (n + 1) = insert 0 ((range n).map ⟨fun i => i + 1, fun i j => by simp⟩) := by ext (⟨⟩ | ⟨n⟩) <;> simp [Nat.zero_lt_succ n] /-! ### image -/ section Image variable [DecidableEq β] /-- `image f s` is the forward image of `s` under `f`. -/ def image (f : α → β) (s : Finset α) : Finset β := (s.1.map f).toFinset @[simp] theorem image_val (f : α → β) (s : Finset α) : (image f s).1 = (s.1.map f).dedup := rfl @[simp] theorem image_empty (f : α → β) : (∅ : Finset α).image f = ∅ := rfl variable {f g : α → β} {s : Finset α} {t : Finset β} {a : α} {b c : β} @[simp] theorem mem_image : b ∈ s.image f ↔ ∃ a ∈ s, f a = b := by simp only [mem_def, image_val, mem_dedup, Multiset.mem_map, exists_prop] theorem mem_image_of_mem (f : α → β) {a} (h : a ∈ s) : f a ∈ s.image f := mem_image.2 ⟨_, h, rfl⟩ theorem forall_image {p : β → Prop} : (∀ b ∈ s.image f, p b) ↔ ∀ a ∈ s, p (f a) := by simp only [mem_image, forall_exists_index, and_imp, forall_apply_eq_imp_iff₂] theorem map_eq_image (f : α ↪ β) (s : Finset α) : s.map f = s.image f := eq_of_veq (s.map f).2.dedup.symm --@[simp] Porting note: removing simp, `simp` [Nonempty] can prove it theorem mem_image_const : c ∈ s.image (const α b) ↔ s.Nonempty ∧ b = c := by rw [mem_image] simp only [exists_prop, const_apply, exists_and_right] rfl theorem mem_image_const_self : b ∈ s.image (const α b) ↔ s.Nonempty := mem_image_const.trans <| and_iff_left rfl instance canLift (c) (p) [CanLift β α c p] : CanLift (Finset β) (Finset α) (image c) fun s => ∀ x ∈ s, p x where prf := by rintro ⟨⟨l⟩, hd : l.Nodup⟩ hl lift l to List α using hl exact ⟨⟨l, hd.of_map _⟩, ext fun a => by simp⟩ theorem image_congr (h : (s : Set α).EqOn f g) : Finset.image f s = Finset.image g s := by ext simp_rw [mem_image, ← bex_def] exact exists₂_congr fun x hx => by rw [h hx] theorem _root_.Function.Injective.mem_finset_image (hf : Injective f) : f a ∈ s.image f ↔ a ∈ s := by refine ⟨fun h => ?_, Finset.mem_image_of_mem f⟩ obtain ⟨y, hy, heq⟩ := mem_image.1 h exact hf heq ▸ hy theorem filter_mem_image_eq_image (f : α → β) (s : Finset α) (t : Finset β) (h : ∀ x ∈ s, f x ∈ t) : (t.filter fun y => y ∈ s.image f) = s.image f := by ext simp only [mem_filter, mem_image, decide_eq_true_eq, and_iff_right_iff_imp, forall_exists_index, and_imp] rintro x xel rfl exact h _ xel theorem fiber_nonempty_iff_mem_image (f : α → β) (s : Finset α) (y : β) : (s.filter fun x => f x = y).Nonempty ↔ y ∈ s.image f := by simp [Finset.Nonempty] @[simp, norm_cast] theorem coe_image : ↑(s.image f) = f '' ↑s := Set.ext <| by simp only [mem_coe, mem_image, Set.mem_image, implies_true] @[simp, aesop safe apply (rule_sets := [finsetNonempty])] lemma image_nonempty : (s.image f).Nonempty ↔ s.Nonempty := mod_cast Set.image_nonempty (f := f) (s := (s : Set α)) protected theorem Nonempty.image (h : s.Nonempty) (f : α → β) : (s.image f).Nonempty := image_nonempty.2 h alias ⟨Nonempty.of_image, _⟩ := image_nonempty @[deprecated image_nonempty (since := "2023-12-29")] theorem Nonempty.image_iff (f : α → β) : (s.image f).Nonempty ↔ s.Nonempty := image_nonempty theorem image_toFinset [DecidableEq α] {s : Multiset α} : s.toFinset.image f = (s.map f).toFinset := ext fun _ => by simp only [mem_image, Multiset.mem_toFinset, exists_prop, Multiset.mem_map] theorem image_val_of_injOn (H : Set.InjOn f s) : (image f s).1 = s.1.map f := (s.2.map_on H).dedup @[simp] theorem image_id [DecidableEq α] : s.image id = s := ext fun _ => by simp only [mem_image, exists_prop, id, exists_eq_right] @[simp] theorem image_id' [DecidableEq α] : (s.image fun x => x) = s := image_id theorem image_image [DecidableEq γ] {g : β → γ} : (s.image f).image g = s.image (g ∘ f) := eq_of_veq <| by simp only [image_val, dedup_map_dedup_eq, Multiset.map_map] theorem image_comm {β'} [DecidableEq β'] [DecidableEq γ] {f : β → γ} {g : α → β} {f' : α → β'} {g' : β' → γ} (h_comm : ∀ a, f (g a) = g' (f' a)) : (s.image g).image f = (s.image f').image g' := by simp_rw [image_image, comp, h_comm] theorem _root_.Function.Semiconj.finset_image [DecidableEq α] {f : α → β} {ga : α → α} {gb : β → β} (h : Function.Semiconj f ga gb) : Function.Semiconj (image f) (image ga) (image gb) := fun _ => image_comm h theorem _root_.Function.Commute.finset_image [DecidableEq α] {f g : α → α} (h : Function.Commute f g) : Function.Commute (image f) (image g) := Function.Semiconj.finset_image h theorem image_subset_image {s₁ s₂ : Finset α} (h : s₁ ⊆ s₂) : s₁.image f ⊆ s₂.image f := by simp only [subset_def, image_val, subset_dedup', dedup_subset', Multiset.map_subset_map h] theorem image_subset_iff : s.image f ⊆ t ↔ ∀ x ∈ s, f x ∈ t := calc s.image f ⊆ t ↔ f '' ↑s ⊆ ↑t := by norm_cast _ ↔ _ := Set.image_subset_iff theorem image_mono (f : α → β) : Monotone (Finset.image f) := fun _ _ => image_subset_image lemma image_injective (hf : Injective f) : Injective (image f) := by simpa only [funext (map_eq_image _)] using map_injective ⟨f, hf⟩ lemma image_inj {t : Finset α} (hf : Injective f) : s.image f = t.image f ↔ s = t := (image_injective hf).eq_iff theorem image_subset_image_iff {t : Finset α} (hf : Injective f) : s.image f ⊆ t.image f ↔ s ⊆ t := mod_cast Set.image_subset_image_iff hf (s := s) (t := t) lemma image_ssubset_image {t : Finset α} (hf : Injective f) : s.image f ⊂ t.image f ↔ s ⊂ t := by simp_rw [← lt_iff_ssubset] exact lt_iff_lt_of_le_iff_le' (image_subset_image_iff hf) (image_subset_image_iff hf) theorem coe_image_subset_range : ↑(s.image f) ⊆ Set.range f := calc ↑(s.image f) = f '' ↑s := coe_image _ ⊆ Set.range f := Set.image_subset_range f ↑s theorem filter_image {p : β → Prop} [DecidablePred p] : (s.image f).filter p = (s.filter fun a ↦ p (f a)).image f := ext fun b => by simp only [mem_filter, mem_image, exists_prop] exact ⟨by rintro ⟨⟨x, h1, rfl⟩, h2⟩; exact ⟨x, ⟨h1, h2⟩, rfl⟩, by rintro ⟨x, ⟨h1, h2⟩, rfl⟩; exact ⟨⟨x, h1, rfl⟩, h2⟩⟩ theorem image_union [DecidableEq α] {f : α → β} (s₁ s₂ : Finset α) : (s₁ ∪ s₂).image f = s₁.image f ∪ s₂.image f := mod_cast Set.image_union f s₁ s₂ theorem image_inter_subset [DecidableEq α] (f : α → β) (s t : Finset α) : (s ∩ t).image f ⊆ s.image f ∩ t.image f := (image_mono f).map_inf_le s t theorem image_inter_of_injOn [DecidableEq α] {f : α → β} (s t : Finset α) (hf : Set.InjOn f (s ∪ t)) : (s ∩ t).image f = s.image f ∩ t.image f := coe_injective <| by push_cast exact Set.image_inter_on fun a ha b hb => hf (Or.inr ha) <| Or.inl hb theorem image_inter [DecidableEq α] (s₁ s₂ : Finset α) (hf : Injective f) : (s₁ ∩ s₂).image f = s₁.image f ∩ s₂.image f := image_inter_of_injOn _ _ hf.injOn @[simp] theorem image_singleton (f : α → β) (a : α) : image f {a} = {f a} := ext fun x => by simpa only [mem_image, exists_prop, mem_singleton, exists_eq_left] using eq_comm @[simp] theorem image_insert [DecidableEq α] (f : α → β) (a : α) (s : Finset α) : (insert a s).image f = insert (f a) (s.image f) := by simp only [insert_eq, image_singleton, image_union] theorem erase_image_subset_image_erase [DecidableEq α] (f : α → β) (s : Finset α) (a : α) : (s.image f).erase (f a) ⊆ (s.erase a).image f := by simp only [subset_iff, and_imp, exists_prop, mem_image, exists_imp, mem_erase] rintro b hb x hx rfl exact ⟨_, ⟨ne_of_apply_ne f hb, hx⟩, rfl⟩ @[simp] theorem image_erase [DecidableEq α] {f : α → β} (hf : Injective f) (s : Finset α) (a : α) : (s.erase a).image f = (s.image f).erase (f a) := coe_injective <| by push_cast [Set.image_diff hf, Set.image_singleton]; rfl @[simp] theorem image_eq_empty : s.image f = ∅ ↔ s = ∅ := mod_cast Set.image_eq_empty (f := f) (s := s) theorem image_sdiff [DecidableEq α] {f : α → β} (s t : Finset α) (hf : Injective f) : (s \ t).image f = s.image f \ t.image f := mod_cast Set.image_diff hf s t open scoped symmDiff in theorem image_symmDiff [DecidableEq α] {f : α → β} (s t : Finset α) (hf : Injective f) : (s ∆ t).image f = s.image f ∆ t.image f := mod_cast Set.image_symmDiff hf s t @[simp] theorem _root_.Disjoint.of_image_finset {s t : Finset α} {f : α → β} (h : Disjoint (s.image f) (t.image f)) : Disjoint s t := disjoint_iff_ne.2 fun _ ha _ hb => ne_of_apply_ne f <| h.forall_ne_finset (mem_image_of_mem _ ha) (mem_image_of_mem _ hb) theorem mem_range_iff_mem_finset_range_of_mod_eq' [DecidableEq α] {f : ℕ → α} {a : α} {n : ℕ} (hn : 0 < n) (h : ∀ i, f (i % n) = f i) : a ∈ Set.range f ↔ a ∈ (Finset.range n).image fun i => f i := by constructor · rintro ⟨i, hi⟩ simp only [mem_image, exists_prop, mem_range] exact ⟨i % n, Nat.mod_lt i hn, (rfl.congr hi).mp (h i)⟩ · rintro h simp only [mem_image, exists_prop, Set.mem_range, mem_range] at * rcases h with ⟨i, _, ha⟩ exact ⟨i, ha⟩ theorem mem_range_iff_mem_finset_range_of_mod_eq [DecidableEq α] {f : ℤ → α} {a : α} {n : ℕ} (hn : 0 < n) (h : ∀ i, f (i % n) = f i) : a ∈ Set.range f ↔ a ∈ (Finset.range n).image (fun (i : ℕ) => f i) := suffices (∃ i, f (i % n) = a) ↔ ∃ i, i < n ∧ f ↑i = a by simpa [h] have hn' : 0 < (n : ℤ) := Int.ofNat_lt.mpr hn Iff.intro (fun ⟨i, hi⟩ => have : 0 ≤ i % ↑n := Int.emod_nonneg _ (ne_of_gt hn') ⟨Int.toNat (i % n), by rw [← Int.ofNat_lt, Int.toNat_of_nonneg this]; exact ⟨Int.emod_lt_of_pos i hn', hi⟩⟩) fun ⟨i, hi, ha⟩ => ⟨i, by rw [Int.emod_eq_of_lt (Int.ofNat_zero_le _) (Int.ofNat_lt_ofNat_of_lt hi), ha]⟩ theorem range_add (a b : ℕ) : range (a + b) = range a ∪ (range b).map (addLeftEmbedding a) := by rw [← val_inj, union_val] exact Multiset.range_add_eq_union a b @[simp] theorem attach_image_val [DecidableEq α] {s : Finset α} : s.attach.image Subtype.val = s := eq_of_veq <| by rw [image_val, attach_val, Multiset.attach_map_val, dedup_eq_self] @[simp] theorem attach_insert [DecidableEq α] {a : α} {s : Finset α} : attach (insert a s) = insert (⟨a, mem_insert_self a s⟩ : { x // x ∈ insert a s }) ((attach s).image fun x => ⟨x.1, mem_insert_of_mem x.2⟩) := ext fun ⟨x, hx⟩ => ⟨Or.casesOn (mem_insert.1 hx) (fun h : x = a => fun _ => mem_insert.2 <| Or.inl <| Subtype.eq h) fun h : x ∈ s => fun _ => mem_insert_of_mem <| mem_image.2 <| ⟨⟨x, h⟩, mem_attach _ _, Subtype.eq rfl⟩, fun _ => Finset.mem_attach _ _⟩ @[simp] theorem disjoint_image {s t : Finset α} {f : α → β} (hf : Injective f) : Disjoint (s.image f) (t.image f) ↔ Disjoint s t := mod_cast Set.disjoint_image_iff hf (s := s) (t := t) theorem image_const {s : Finset α} (h : s.Nonempty) (b : β) : (s.image fun _ => b) = singleton b := mod_cast Set.Nonempty.image_const (coe_nonempty.2 h) b @[simp] theorem map_erase [DecidableEq α] (f : α ↪ β) (s : Finset α) (a : α) : (s.erase a).map f = (s.map f).erase (f a) := by simp_rw [map_eq_image] exact s.image_erase f.2 a theorem image_biUnion [DecidableEq γ] {f : α → β} {s : Finset α} {t : β → Finset γ} : (s.image f).biUnion t = s.biUnion fun a => t (f a) := haveI := Classical.decEq α Finset.induction_on s rfl fun a s _ ih => by simp only [image_insert, biUnion_insert, ih] theorem biUnion_image [DecidableEq γ] {s : Finset α} {t : α → Finset β} {f : β → γ} : (s.biUnion t).image f = s.biUnion fun a => (t a).image f := haveI := Classical.decEq α Finset.induction_on s rfl fun a s _ ih => by simp only [biUnion_insert, image_union, ih] theorem image_biUnion_filter_eq [DecidableEq α] (s : Finset β) (g : β → α) : ((s.image g).biUnion fun a => s.filter fun c => g c = a) = s := biUnion_filter_eq_of_maps_to fun _ => mem_image_of_mem g theorem biUnion_singleton {f : α → β} : (s.biUnion fun a => {f a}) = s.image f := ext fun x => by simp only [mem_biUnion, mem_image, mem_singleton, eq_comm] end Image /-! ### filterMap -/ section FilterMap /-- `filterMap f s` is a combination filter/map operation on `s`. The function `f : α → Option β` is applied to each element of `s`; if `f a` is `some b` then `b` is included in the result, otherwise `a` is excluded from the resulting finset. In notation, `filterMap f s` is the finset `{b : β | ∃ a ∈ s , f a = some b}`. -/ -- TODO: should there be `filterImage` too? def filterMap (f : α → Option β) (s : Finset α) (f_inj : ∀ a a' b, b ∈ f a → b ∈ f a' → a = a') : Finset β := ⟨s.val.filterMap f, s.nodup.filterMap f f_inj⟩ variable (f : α → Option β) (s' : Finset α) {s t : Finset α} {f_inj : ∀ a a' b, b ∈ f a → b ∈ f a' → a = a'} @[simp] theorem filterMap_val : (filterMap f s' f_inj).1 = s'.1.filterMap f := rfl @[simp] theorem filterMap_empty : (∅ : Finset α).filterMap f f_inj = ∅ := rfl @[simp] theorem mem_filterMap {b : β} : b ∈ s.filterMap f f_inj ↔ ∃ a ∈ s, f a = some b := s.val.mem_filterMap f @[simp, norm_cast] theorem coe_filterMap : (s.filterMap f f_inj : Set β) = {b | ∃ a ∈ s, f a = some b} := Set.ext (by simp only [mem_coe, mem_filterMap, Option.mem_def, Set.mem_setOf_eq, implies_true]) @[simp] theorem filterMap_some : s.filterMap some (by simp) = s := ext fun _ => by simp only [mem_filterMap, Option.some.injEq, exists_eq_right] theorem filterMap_mono (h : s ⊆ t) : filterMap f s f_inj ⊆ filterMap f t f_inj := by rw [← val_le_iff] at h ⊢ exact Multiset.filterMap_le_filterMap f h end FilterMap /-! ### Subtype -/ section Subtype /-- Given a finset `s` and a predicate `p`, `s.subtype p` is the finset of `Subtype p` whose elements belong to `s`. -/ protected def subtype {α} (p : α → Prop) [DecidablePred p] (s : Finset α) : Finset (Subtype p) := (s.filter p).attach.map ⟨fun x => ⟨x.1, by simpa using (Finset.mem_filter.1 x.2).2⟩, fun x y H => Subtype.eq <| Subtype.mk.inj H⟩ @[simp] theorem mem_subtype {p : α → Prop} [DecidablePred p] {s : Finset α} : ∀ {a : Subtype p}, a ∈ s.subtype p ↔ (a : α) ∈ s | ⟨a, ha⟩ => by simp [Finset.subtype, ha] theorem subtype_eq_empty {p : α → Prop} [DecidablePred p] {s : Finset α} : s.subtype p = ∅ ↔ ∀ x, p x → x ∉ s := by simp [ext_iff, Subtype.forall, Subtype.coe_mk] @[mono] theorem subtype_mono {p : α → Prop} [DecidablePred p] : Monotone (Finset.subtype p) := fun _ _ h _ hx => mem_subtype.2 <| h <| mem_subtype.1 hx /-- `s.subtype p` converts back to `s.filter p` with `Embedding.subtype`. -/ @[simp] theorem subtype_map (p : α → Prop) [DecidablePred p] {s : Finset α} : (s.subtype p).map (Embedding.subtype _) = s.filter p := by ext x simp [@and_comm _ (_ = _), @and_left_comm _ (_ = _), @and_comm (p x) (x ∈ s)] /-- If all elements of a `Finset` satisfy the predicate `p`, `s.subtype p` converts back to `s` with `Embedding.subtype`. -/ theorem subtype_map_of_mem {p : α → Prop} [DecidablePred p] {s : Finset α} (h : ∀ x ∈ s, p x) : (s.subtype p).map (Embedding.subtype _) = s := ext <| by simpa [subtype_map] using h /-- If a `Finset` of a subtype is converted to the main type with `Embedding.subtype`, all elements of the result have the property of the subtype. -/ theorem property_of_mem_map_subtype {p : α → Prop} (s : Finset { x // p x }) {a : α} (h : a ∈ s.map (Embedding.subtype _)) : p a := by rcases mem_map.1 h with ⟨x, _, rfl⟩ exact x.2 /-- If a `Finset` of a subtype is converted to the main type with `Embedding.subtype`, the result does not contain any value that does not satisfy the property of the subtype. -/ theorem not_mem_map_subtype_of_not_property {p : α → Prop} (s : Finset { x // p x }) {a : α} (h : ¬p a) : a ∉ s.map (Embedding.subtype _) := mt s.property_of_mem_map_subtype h /-- If a `Finset` of a subtype is converted to the main type with `Embedding.subtype`, the result is a subset of the set giving the subtype. -/ theorem map_subtype_subset {t : Set α} (s : Finset t) : ↑(s.map (Embedding.subtype _)) ⊆ t := by intro a ha rw [mem_coe] at ha convert property_of_mem_map_subtype s ha end Subtype /-! ### Fin -/ /-- Given a finset `s` of natural numbers and a bound `n`, `s.fin n` is the finset of all elements of `s` less than `n`. -/ protected def fin (n : ℕ) (s : Finset ℕ) : Finset (Fin n) := (s.subtype _).map Fin.equivSubtype.symm.toEmbedding @[simp] theorem mem_fin {n} {s : Finset ℕ} : ∀ a : Fin n, a ∈ s.fin n ↔ (a : ℕ) ∈ s | ⟨a, ha⟩ => by simp [Finset.fin, ha, and_comm] @[mono] theorem fin_mono {n} : Monotone (Finset.fin n) := fun s t h x => by simpa using @h x @[simp] theorem fin_map {n} {s : Finset ℕ} : (s.fin n).map Fin.valEmbedding = s.filter (· < n) := by simp [Finset.fin, Finset.map_map] /-- If a `Finset` is a subset of the image of a `Set` under `f`, then it is equal to the `Finset.image` of a `Finset` subset of that `Set`. -/ theorem subset_image_iff [DecidableEq β] {s : Set α} {t : Finset β} {f : α → β} : ↑t ⊆ f '' s ↔ ∃ s' : Finset α, ↑s' ⊆ s ∧ s'.image f = t := by constructor; swap · rintro ⟨t, ht, rfl⟩ rw [coe_image] exact Set.image_subset f ht intro h letI : CanLift β s (f ∘ (↑)) fun y => y ∈ f '' s := ⟨fun y ⟨x, hxt, hy⟩ => ⟨⟨x, hxt⟩, hy⟩⟩ lift t to Finset s using h refine ⟨t.map (Embedding.subtype _), map_subtype_subset _, ?_⟩ ext y; simp theorem range_sdiff_zero {n : ℕ} : range (n + 1) \ {0} = (range n).image Nat.succ := by induction' n with k hk · simp conv_rhs => rw [range_succ] rw [range_succ, image_insert, ← hk, insert_sdiff_of_not_mem] simp end Finset theorem Multiset.toFinset_map [DecidableEq α] [DecidableEq β] (f : α → β) (m : Multiset α) : (m.map f).toFinset = m.toFinset.image f := Finset.val_inj.1 (Multiset.dedup_map_dedup_eq _ _).symm namespace Equiv /-- Given an equivalence `α` to `β`, produce an equivalence between `Finset α` and `Finset β`. -/ protected def finsetCongr (e : α ≃ β) : Finset α ≃ Finset β where toFun s := s.map e.toEmbedding invFun s := s.map e.symm.toEmbedding left_inv s := by simp [Finset.map_map] right_inv s := by simp [Finset.map_map] @[simp] theorem finsetCongr_apply (e : α ≃ β) (s : Finset α) : e.finsetCongr s = s.map e.toEmbedding := rfl @[simp] theorem finsetCongr_refl : (Equiv.refl α).finsetCongr = Equiv.refl _ := by ext simp @[simp] theorem finsetCongr_symm (e : α ≃ β) : e.finsetCongr.symm = e.symm.finsetCongr := rfl @[simp] theorem finsetCongr_trans (e : α ≃ β) (e' : β ≃ γ) : e.finsetCongr.trans e'.finsetCongr = (e.trans e').finsetCongr := by ext simp [-Finset.mem_map, -Equiv.trans_toEmbedding] theorem finsetCongr_toEmbedding (e : α ≃ β) : e.finsetCongr.toEmbedding = (Finset.mapEmbedding e.toEmbedding).toEmbedding := rfl end Equiv namespace Finset @[deprecated (since := "2023-12-27")] alias image_filter := filter_image end Finset
Data\Finset\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.Grade import Mathlib.Order.Interval.Finset.Basic /-! # Intervals of finsets as finsets This file provides the `LocallyFiniteOrder` instance for `Finset α` and calculates the cardinality of finite intervals of finsets. If `s t : Finset α`, then `Finset.Icc s t` is the finset of finsets which include `s` and are included in `t`. For example, `Finset.Icc {0, 1} {0, 1, 2, 3} = {{0, 1}, {0, 1, 2}, {0, 1, 3}, {0, 1, 2, 3}}` and `Finset.Icc {0, 1, 2} {0, 1, 3} = {}`. In addition, this file gives characterizations of monotone and strictly monotone functions out of `Finset α` in terms of `Finset.insert` -/ variable {α β : Type*} namespace Finset section Decidable variable [DecidableEq α] (s t : Finset α) instance instLocallyFiniteOrder : LocallyFiniteOrder (Finset α) where finsetIcc s t := t.powerset.filter (s ⊆ ·) finsetIco s t := t.ssubsets.filter (s ⊆ ·) finsetIoc s t := t.powerset.filter (s ⊂ ·) finsetIoo s t := t.ssubsets.filter (s ⊂ ·) finset_mem_Icc s t u := by rw [mem_filter, mem_powerset] exact and_comm finset_mem_Ico s t u := by rw [mem_filter, mem_ssubsets] exact and_comm finset_mem_Ioc s t u := by rw [mem_filter, mem_powerset] exact and_comm finset_mem_Ioo s t u := by rw [mem_filter, mem_ssubsets] exact and_comm theorem Icc_eq_filter_powerset : Icc s t = t.powerset.filter (s ⊆ ·) := rfl theorem Ico_eq_filter_ssubsets : Ico s t = t.ssubsets.filter (s ⊆ ·) := rfl theorem Ioc_eq_filter_powerset : Ioc s t = t.powerset.filter (s ⊂ ·) := rfl theorem Ioo_eq_filter_ssubsets : Ioo s t = t.ssubsets.filter (s ⊂ ·) := rfl theorem Iic_eq_powerset : Iic s = s.powerset := filter_true_of_mem fun t _ => empty_subset t theorem Iio_eq_ssubsets : Iio s = s.ssubsets := filter_true_of_mem fun t _ => empty_subset t variable {s t} theorem Icc_eq_image_powerset (h : s ⊆ t) : Icc s t = (t \ s).powerset.image (s ∪ ·) := by ext u simp_rw [mem_Icc, mem_image, mem_powerset] constructor · rintro ⟨hs, ht⟩ exact ⟨u \ s, sdiff_le_sdiff_right ht, sup_sdiff_cancel_right hs⟩ · rintro ⟨v, hv, rfl⟩ exact ⟨le_sup_left, union_subset h <| hv.trans sdiff_subset⟩ theorem Ico_eq_image_ssubsets (h : s ⊆ t) : Ico s t = (t \ s).ssubsets.image (s ∪ ·) := by ext u simp_rw [mem_Ico, mem_image, mem_ssubsets] constructor · rintro ⟨hs, ht⟩ exact ⟨u \ s, sdiff_lt_sdiff_right ht hs, sup_sdiff_cancel_right hs⟩ · rintro ⟨v, hv, rfl⟩ exact ⟨le_sup_left, sup_lt_of_lt_sdiff_left hv h⟩ /-- Cardinality of a non-empty `Icc` of finsets. -/ theorem card_Icc_finset (h : s ⊆ t) : (Icc s t).card = 2 ^ (t.card - s.card) := by rw [← card_sdiff h, ← card_powerset, Icc_eq_image_powerset h, Finset.card_image_iff] rintro u hu v hv (huv : s ⊔ u = s ⊔ v) rw [mem_coe, mem_powerset] at hu hv rw [← (disjoint_sdiff.mono_right hu : Disjoint s u).sup_sdiff_cancel_left, ← (disjoint_sdiff.mono_right hv : Disjoint s v).sup_sdiff_cancel_left, huv] /-- Cardinality of an `Ico` of finsets. -/ theorem card_Ico_finset (h : s ⊆ t) : (Ico s t).card = 2 ^ (t.card - s.card) - 1 := by rw [card_Ico_eq_card_Icc_sub_one, card_Icc_finset h] /-- Cardinality of an `Ioc` of finsets. -/ theorem card_Ioc_finset (h : s ⊆ t) : (Ioc s t).card = 2 ^ (t.card - s.card) - 1 := by rw [card_Ioc_eq_card_Icc_sub_one, card_Icc_finset h] /-- Cardinality of an `Ioo` of finsets. -/ theorem card_Ioo_finset (h : s ⊆ t) : (Ioo s t).card = 2 ^ (t.card - s.card) - 2 := by rw [card_Ioo_eq_card_Icc_sub_two, card_Icc_finset h] /-- Cardinality of an `Iic` of finsets. -/ theorem card_Iic_finset : (Iic s).card = 2 ^ s.card := by rw [Iic_eq_powerset, card_powerset] /-- Cardinality of an `Iio` of finsets. -/ theorem card_Iio_finset : (Iio s).card = 2 ^ s.card - 1 := by rw [Iio_eq_ssubsets, ssubsets, card_erase_of_mem (mem_powerset_self _), card_powerset] end Decidable variable [Preorder β] {s t : Finset α} {f : Finset α → β} section Cons /-- A function `f` from `Finset α` is monotone if and only if `f s ≤ f (cons a s ha)` for all `s` and `a ∉ s`. -/ lemma monotone_iff_forall_le_cons : Monotone f ↔ ∀ s, ∀ ⦃a⦄ (ha), f s ≤ f (cons a s ha) := by classical simp [monotone_iff_forall_covBy, covBy_iff_exists_cons] /-- A function `f` from `Finset α` is antitone if and only if `f (cons a s ha) ≤ f s` for all `s` and `a ∉ s`. -/ lemma antitone_iff_forall_cons_le : Antitone f ↔ ∀ s ⦃a⦄ ha, f (cons a s ha) ≤ f s := monotone_iff_forall_le_cons (β := βᵒᵈ) /-- A function `f` from `Finset α` is strictly monotone if and only if `f s < f (cons a s ha)` for all `s` and `a ∉ s`. -/ lemma strictMono_iff_forall_lt_cons : StrictMono f ↔ ∀ s ⦃a⦄ ha, f s < f (cons a s ha) := by classical simp [strictMono_iff_forall_covBy, covBy_iff_exists_cons] /-- A function `f` from `Finset α` is strictly antitone if and only if `f (cons a s ha) < f s` for all `s` and `a ∉ s`. -/ lemma strictAnti_iff_forall_cons_lt : StrictAnti f ↔ ∀ s ⦃a⦄ ha, f (cons a s ha) < f s := strictMono_iff_forall_lt_cons (β := βᵒᵈ) end Cons section Insert variable [DecidableEq α] /-- A function `f` from `Finset α` is monotone if and only if `f s ≤ f (insert a s)` for all `s` and `a ∉ s`. -/ lemma monotone_iff_forall_le_insert : Monotone f ↔ ∀ s ⦃a⦄, a ∉ s → f s ≤ f (insert a s) := by simp [monotone_iff_forall_le_cons] /-- A function `f` from `Finset α` is antitone if and only if `f (insert a s) ≤ f s` for all `s` and `a ∉ s`. -/ lemma antitone_iff_forall_insert_le : Antitone f ↔ ∀ s ⦃a⦄, a ∉ s → f (insert a s) ≤ f s := monotone_iff_forall_le_insert (β := βᵒᵈ) /-- A function `f` from `Finset α` is strictly monotone if and only if `f s < f (insert a s)` for all `s` and `a ∉ s`. -/ lemma strictMono_iff_forall_lt_insert : StrictMono f ↔ ∀ s ⦃a⦄, a ∉ s → f s < f (insert a s) := by simp [strictMono_iff_forall_lt_cons] /-- A function `f` from `Finset α` is strictly antitone if and only if `f (insert a s) < f s` for all `s` and `a ∉ s`. -/ lemma strictAnti_iff_forall_lt_insert : StrictAnti f ↔ ∀ s ⦃a⦄, a ∉ s → f (insert a s) < f s := strictMono_iff_forall_lt_insert (β := βᵒᵈ) end Insert end Finset
Data\Finset\Lattice.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.Algebra.Order.Monoid.Unbundled.Pow import Mathlib.Data.Finset.Fold import Mathlib.Data.Finset.Option import Mathlib.Data.Finset.Pi import Mathlib.Data.Finset.Prod import Mathlib.Data.Multiset.Lattice import Mathlib.Data.Set.Lattice import Mathlib.Order.Hom.Lattice import Mathlib.Order.Minimal import Mathlib.Order.Nat /-! # Lattice operations on finsets -/ -- TODO: -- assert_not_exists OrderedCommMonoid assert_not_exists MonoidWithZero open Function Multiset OrderDual variable {F α β γ ι κ : Type*} namespace Finset /-! ### sup -/ section Sup -- TODO: define with just `[Bot α]` where some lemmas hold without requiring `[OrderBot α]` variable [SemilatticeSup α] [OrderBot α] /-- Supremum of a finite set: `sup {a, b, c} f = f a ⊔ f b ⊔ f c` -/ def sup (s : Finset β) (f : β → α) : α := s.fold (· ⊔ ·) ⊥ f variable {s s₁ s₂ : Finset β} {f g : β → α} {a : α} theorem sup_def : s.sup f = (s.1.map f).sup := rfl @[simp] theorem sup_empty : (∅ : Finset β).sup f = ⊥ := fold_empty @[simp] theorem sup_cons {b : β} (h : b ∉ s) : (cons b s h).sup f = f b ⊔ s.sup f := fold_cons h @[simp] theorem sup_insert [DecidableEq β] {b : β} : (insert b s : Finset β).sup f = f b ⊔ s.sup f := fold_insert_idem @[simp] theorem sup_image [DecidableEq β] (s : Finset γ) (f : γ → β) (g : β → α) : (s.image f).sup g = s.sup (g ∘ f) := fold_image_idem @[simp] theorem sup_map (s : Finset γ) (f : γ ↪ β) (g : β → α) : (s.map f).sup g = s.sup (g ∘ f) := fold_map @[simp] theorem sup_singleton {b : β} : ({b} : Finset β).sup f = f b := Multiset.sup_singleton theorem sup_sup : s.sup (f ⊔ g) = s.sup f ⊔ s.sup g := by induction s using Finset.cons_induction with | empty => rw [sup_empty, sup_empty, sup_empty, bot_sup_eq] | cons _ _ _ ih => rw [sup_cons, sup_cons, sup_cons, ih] exact sup_sup_sup_comm _ _ _ _ theorem sup_congr {f g : β → α} (hs : s₁ = s₂) (hfg : ∀ a ∈ s₂, f a = g a) : s₁.sup f = s₂.sup g := by subst hs exact Finset.fold_congr hfg @[simp] theorem _root_.map_finset_sup [SemilatticeSup β] [OrderBot β] [FunLike F α β] [SupBotHomClass F α β] (f : F) (s : Finset ι) (g : ι → α) : f (s.sup g) = s.sup (f ∘ g) := Finset.cons_induction_on s (map_bot f) fun i s _ h => by rw [sup_cons, sup_cons, map_sup, h, Function.comp_apply] @[simp] protected theorem sup_le_iff {a : α} : s.sup f ≤ a ↔ ∀ b ∈ s, f b ≤ a := by apply Iff.trans Multiset.sup_le simp only [Multiset.mem_map, and_imp, exists_imp] exact ⟨fun k b hb => k _ _ hb rfl, fun k a' b hb h => h ▸ k _ hb⟩ protected alias ⟨_, sup_le⟩ := Finset.sup_le_iff theorem sup_const_le : (s.sup fun _ => a) ≤ a := Finset.sup_le fun _ _ => le_rfl theorem le_sup {b : β} (hb : b ∈ s) : f b ≤ s.sup f := Finset.sup_le_iff.1 le_rfl _ hb theorem le_sup_of_le {b : β} (hb : b ∈ s) (h : a ≤ f b) : a ≤ s.sup f := h.trans <| le_sup hb theorem sup_union [DecidableEq β] : (s₁ ∪ s₂).sup f = s₁.sup f ⊔ s₂.sup f := eq_of_forall_ge_iff fun c => by simp [or_imp, forall_and] @[simp] theorem sup_biUnion [DecidableEq β] (s : Finset γ) (t : γ → Finset β) : (s.biUnion t).sup f = s.sup fun x => (t x).sup f := eq_of_forall_ge_iff fun c => by simp [@forall_swap _ β] theorem sup_const {s : Finset β} (h : s.Nonempty) (c : α) : (s.sup fun _ => c) = c := eq_of_forall_ge_iff (fun _ => Finset.sup_le_iff.trans h.forall_const) @[simp] theorem sup_bot (s : Finset β) : (s.sup fun _ => ⊥) = (⊥ : α) := by obtain rfl | hs := s.eq_empty_or_nonempty · exact sup_empty · exact sup_const hs _ theorem sup_ite (p : β → Prop) [DecidablePred p] : (s.sup fun i => ite (p i) (f i) (g i)) = (s.filter p).sup f ⊔ (s.filter fun i => ¬p i).sup g := fold_ite _ theorem sup_mono_fun {g : β → α} (h : ∀ b ∈ s, f b ≤ g b) : s.sup f ≤ s.sup g := Finset.sup_le fun b hb => le_trans (h b hb) (le_sup hb) @[gcongr] theorem sup_mono (h : s₁ ⊆ s₂) : s₁.sup f ≤ s₂.sup f := Finset.sup_le (fun _ hb => le_sup (h hb)) protected theorem sup_comm (s : Finset β) (t : Finset γ) (f : β → γ → α) : (s.sup fun b => t.sup (f b)) = t.sup fun c => s.sup fun b => f b c := eq_of_forall_ge_iff fun a => by simpa using forall₂_swap @[simp, nolint simpNF] -- Porting note: linter claims that LHS does not simplify theorem sup_attach (s : Finset β) (f : β → α) : (s.attach.sup fun x => f x) = s.sup f := (s.attach.sup_map (Function.Embedding.subtype _) f).symm.trans <| congr_arg _ attach_map_val /-- See also `Finset.product_biUnion`. -/ theorem sup_product_left (s : Finset β) (t : Finset γ) (f : β × γ → α) : (s ×ˢ t).sup f = s.sup fun i => t.sup fun i' => f ⟨i, i'⟩ := eq_of_forall_ge_iff fun a => by simp [@forall_swap _ γ] theorem sup_product_right (s : Finset β) (t : Finset γ) (f : β × γ → α) : (s ×ˢ t).sup f = t.sup fun i' => s.sup fun i => f ⟨i, i'⟩ := by rw [sup_product_left, Finset.sup_comm] section Prod variable {ι κ α β : Type*} [SemilatticeSup α] [SemilatticeSup β] [OrderBot α] [OrderBot β] {s : Finset ι} {t : Finset κ} @[simp] lemma sup_prodMap (hs : s.Nonempty) (ht : t.Nonempty) (f : ι → α) (g : κ → β) : sup (s ×ˢ t) (Prod.map f g) = (sup s f, sup t g) := eq_of_forall_ge_iff fun i ↦ by obtain ⟨a, ha⟩ := hs obtain ⟨b, hb⟩ := ht simp only [Prod.map, Finset.sup_le_iff, mem_product, and_imp, Prod.forall, Prod.le_def] exact ⟨fun h ↦ ⟨fun i hi ↦ (h _ _ hi hb).1, fun j hj ↦ (h _ _ ha hj).2⟩, by aesop⟩ end Prod @[simp] theorem sup_erase_bot [DecidableEq α] (s : Finset α) : (s.erase ⊥).sup id = s.sup id := by refine (sup_mono (s.erase_subset _)).antisymm (Finset.sup_le_iff.2 fun a ha => ?_) obtain rfl | ha' := eq_or_ne a ⊥ · exact bot_le · exact le_sup (mem_erase.2 ⟨ha', ha⟩) theorem sup_sdiff_right {α β : Type*} [GeneralizedBooleanAlgebra α] (s : Finset β) (f : β → α) (a : α) : (s.sup fun b => f b \ a) = s.sup f \ a := by induction s using Finset.cons_induction with | empty => rw [sup_empty, sup_empty, bot_sdiff] | cons _ _ _ h => rw [sup_cons, sup_cons, h, sup_sdiff] theorem comp_sup_eq_sup_comp [SemilatticeSup γ] [OrderBot γ] {s : Finset β} {f : β → α} (g : α → γ) (g_sup : ∀ x y, g (x ⊔ y) = g x ⊔ g y) (bot : g ⊥ = ⊥) : g (s.sup f) = s.sup (g ∘ f) := Finset.cons_induction_on s bot fun c t hc ih => by rw [sup_cons, sup_cons, g_sup, ih, Function.comp_apply] /-- Computing `sup` in a subtype (closed under `sup`) is the same as computing it in `α`. -/ theorem sup_coe {P : α → Prop} {Pbot : P ⊥} {Psup : ∀ ⦃x y⦄, P x → P y → P (x ⊔ y)} (t : Finset β) (f : β → { x : α // P x }) : (@sup { x // P x } _ (Subtype.semilatticeSup Psup) (Subtype.orderBot Pbot) t f : α) = t.sup fun x => ↑(f x) := by letI := Subtype.semilatticeSup Psup letI := Subtype.orderBot Pbot apply comp_sup_eq_sup_comp Subtype.val <;> intros <;> rfl @[simp] theorem sup_toFinset {α β} [DecidableEq β] (s : Finset α) (f : α → Multiset β) : (s.sup f).toFinset = s.sup fun x => (f x).toFinset := comp_sup_eq_sup_comp Multiset.toFinset toFinset_union rfl theorem _root_.List.foldr_sup_eq_sup_toFinset [DecidableEq α] (l : List α) : l.foldr (· ⊔ ·) ⊥ = l.toFinset.sup id := by rw [← coe_fold_r, ← Multiset.fold_dedup_idem, sup_def, ← List.toFinset_coe, toFinset_val, Multiset.map_id] rfl theorem subset_range_sup_succ (s : Finset ℕ) : s ⊆ range (s.sup id).succ := fun _ hn => mem_range.2 <| Nat.lt_succ_of_le <| @le_sup _ _ _ _ _ id _ hn theorem exists_nat_subset_range (s : Finset ℕ) : ∃ n : ℕ, s ⊆ range n := ⟨_, s.subset_range_sup_succ⟩ theorem sup_induction {p : α → Prop} (hb : p ⊥) (hp : ∀ a₁, p a₁ → ∀ a₂, p a₂ → p (a₁ ⊔ a₂)) (hs : ∀ b ∈ s, p (f b)) : p (s.sup f) := by induction s using Finset.cons_induction with | empty => exact hb | cons _ _ _ ih => simp only [sup_cons, forall_mem_cons] at hs ⊢ exact hp _ hs.1 _ (ih hs.2) theorem sup_le_of_le_directed {α : Type*} [SemilatticeSup α] [OrderBot α] (s : Set α) (hs : s.Nonempty) (hdir : DirectedOn (· ≤ ·) s) (t : Finset α) : (∀ x ∈ t, ∃ y ∈ s, x ≤ y) → ∃ x ∈ s, t.sup id ≤ x := by classical induction' t using Finset.induction_on with a r _ ih h · simpa only [forall_prop_of_true, and_true_iff, forall_prop_of_false, bot_le, not_false_iff, sup_empty, forall_true_iff, not_mem_empty] · intro h have incs : (r : Set α) ⊆ ↑(insert a r) := by rw [Finset.coe_subset] apply Finset.subset_insert -- x ∈ s is above the sup of r obtain ⟨x, ⟨hxs, hsx_sup⟩⟩ := ih fun x hx => h x <| incs hx -- y ∈ s is above a obtain ⟨y, hys, hay⟩ := h a (Finset.mem_insert_self a r) -- z ∈ s is above x and y obtain ⟨z, hzs, ⟨hxz, hyz⟩⟩ := hdir x hxs y hys use z, hzs rw [sup_insert, id, sup_le_iff] exact ⟨le_trans hay hyz, le_trans hsx_sup hxz⟩ -- If we acquire sublattices -- the hypotheses should be reformulated as `s : SubsemilatticeSupBot` theorem sup_mem (s : Set α) (w₁ : ⊥ ∈ s) (w₂ : ∀ᵉ (x ∈ s) (y ∈ s), x ⊔ y ∈ s) {ι : Type*} (t : Finset ι) (p : ι → α) (h : ∀ i ∈ t, p i ∈ s) : t.sup p ∈ s := @sup_induction _ _ _ _ _ _ (· ∈ s) w₁ w₂ h @[simp] protected theorem sup_eq_bot_iff (f : β → α) (S : Finset β) : S.sup f = ⊥ ↔ ∀ s ∈ S, f s = ⊥ := by classical induction' S using Finset.induction with a S _ hi <;> simp [*] end Sup theorem sup_eq_iSup [CompleteLattice β] (s : Finset α) (f : α → β) : s.sup f = ⨆ a ∈ s, f a := le_antisymm (Finset.sup_le (fun a ha => le_iSup_of_le a <| le_iSup (fun _ => f a) ha)) (iSup_le fun _ => iSup_le fun ha => le_sup ha) theorem sup_id_eq_sSup [CompleteLattice α] (s : Finset α) : s.sup id = sSup s := by simp [sSup_eq_iSup, sup_eq_iSup] theorem sup_id_set_eq_sUnion (s : Finset (Set α)) : s.sup id = ⋃₀ ↑s := sup_id_eq_sSup _ @[simp] theorem sup_set_eq_biUnion (s : Finset α) (f : α → Set β) : s.sup f = ⋃ x ∈ s, f x := sup_eq_iSup _ _ theorem sup_eq_sSup_image [CompleteLattice β] (s : Finset α) (f : α → β) : s.sup f = sSup (f '' s) := by classical rw [← Finset.coe_image, ← sup_id_eq_sSup, sup_image, Function.id_comp] /-! ### inf -/ section Inf -- TODO: define with just `[Top α]` where some lemmas hold without requiring `[OrderTop α]` variable [SemilatticeInf α] [OrderTop α] /-- Infimum of a finite set: `inf {a, b, c} f = f a ⊓ f b ⊓ f c` -/ def inf (s : Finset β) (f : β → α) : α := s.fold (· ⊓ ·) ⊤ f variable {s s₁ s₂ : Finset β} {f g : β → α} {a : α} theorem inf_def : s.inf f = (s.1.map f).inf := rfl @[simp] theorem inf_empty : (∅ : Finset β).inf f = ⊤ := fold_empty @[simp] theorem inf_cons {b : β} (h : b ∉ s) : (cons b s h).inf f = f b ⊓ s.inf f := @sup_cons αᵒᵈ _ _ _ _ _ _ h @[simp] theorem inf_insert [DecidableEq β] {b : β} : (insert b s : Finset β).inf f = f b ⊓ s.inf f := fold_insert_idem @[simp] theorem inf_image [DecidableEq β] (s : Finset γ) (f : γ → β) (g : β → α) : (s.image f).inf g = s.inf (g ∘ f) := fold_image_idem @[simp] theorem inf_map (s : Finset γ) (f : γ ↪ β) (g : β → α) : (s.map f).inf g = s.inf (g ∘ f) := fold_map @[simp] theorem inf_singleton {b : β} : ({b} : Finset β).inf f = f b := Multiset.inf_singleton theorem inf_inf : s.inf (f ⊓ g) = s.inf f ⊓ s.inf g := @sup_sup αᵒᵈ _ _ _ _ _ _ theorem inf_congr {f g : β → α} (hs : s₁ = s₂) (hfg : ∀ a ∈ s₂, f a = g a) : s₁.inf f = s₂.inf g := by subst hs exact Finset.fold_congr hfg @[simp] theorem _root_.map_finset_inf [SemilatticeInf β] [OrderTop β] [FunLike F α β] [InfTopHomClass F α β] (f : F) (s : Finset ι) (g : ι → α) : f (s.inf g) = s.inf (f ∘ g) := Finset.cons_induction_on s (map_top f) fun i s _ h => by rw [inf_cons, inf_cons, map_inf, h, Function.comp_apply] @[simp] protected theorem le_inf_iff {a : α} : a ≤ s.inf f ↔ ∀ b ∈ s, a ≤ f b := @Finset.sup_le_iff αᵒᵈ _ _ _ _ _ _ protected alias ⟨_, le_inf⟩ := Finset.le_inf_iff theorem le_inf_const_le : a ≤ s.inf fun _ => a := Finset.le_inf fun _ _ => le_rfl theorem inf_le {b : β} (hb : b ∈ s) : s.inf f ≤ f b := Finset.le_inf_iff.1 le_rfl _ hb theorem inf_le_of_le {b : β} (hb : b ∈ s) (h : f b ≤ a) : s.inf f ≤ a := (inf_le hb).trans h theorem inf_union [DecidableEq β] : (s₁ ∪ s₂).inf f = s₁.inf f ⊓ s₂.inf f := eq_of_forall_le_iff fun c ↦ by simp [or_imp, forall_and] @[simp] theorem inf_biUnion [DecidableEq β] (s : Finset γ) (t : γ → Finset β) : (s.biUnion t).inf f = s.inf fun x => (t x).inf f := @sup_biUnion αᵒᵈ _ _ _ _ _ _ _ _ theorem inf_const (h : s.Nonempty) (c : α) : (s.inf fun _ => c) = c := @sup_const αᵒᵈ _ _ _ _ h _ @[simp] theorem inf_top (s : Finset β) : (s.inf fun _ => ⊤) = (⊤ : α) := @sup_bot αᵒᵈ _ _ _ _ theorem inf_ite (p : β → Prop) [DecidablePred p] : (s.inf fun i ↦ ite (p i) (f i) (g i)) = (s.filter p).inf f ⊓ (s.filter fun i ↦ ¬ p i).inf g := fold_ite _ theorem inf_mono_fun {g : β → α} (h : ∀ b ∈ s, f b ≤ g b) : s.inf f ≤ s.inf g := Finset.le_inf fun b hb => le_trans (inf_le hb) (h b hb) @[gcongr] theorem inf_mono (h : s₁ ⊆ s₂) : s₂.inf f ≤ s₁.inf f := Finset.le_inf (fun _ hb => inf_le (h hb)) protected theorem inf_comm (s : Finset β) (t : Finset γ) (f : β → γ → α) : (s.inf fun b => t.inf (f b)) = t.inf fun c => s.inf fun b => f b c := @Finset.sup_comm αᵒᵈ _ _ _ _ _ _ _ theorem inf_attach (s : Finset β) (f : β → α) : (s.attach.inf fun x => f x) = s.inf f := @sup_attach αᵒᵈ _ _ _ _ _ theorem inf_product_left (s : Finset β) (t : Finset γ) (f : β × γ → α) : (s ×ˢ t).inf f = s.inf fun i => t.inf fun i' => f ⟨i, i'⟩ := @sup_product_left αᵒᵈ _ _ _ _ _ _ _ theorem inf_product_right (s : Finset β) (t : Finset γ) (f : β × γ → α) : (s ×ˢ t).inf f = t.inf fun i' => s.inf fun i => f ⟨i, i'⟩ := @sup_product_right αᵒᵈ _ _ _ _ _ _ _ section Prod variable {ι κ α β : Type*} [SemilatticeInf α] [SemilatticeInf β] [OrderTop α] [OrderTop β] {s : Finset ι} {t : Finset κ} @[simp] lemma inf_prodMap (hs : s.Nonempty) (ht : t.Nonempty) (f : ι → α) (g : κ → β) : inf (s ×ˢ t) (Prod.map f g) = (inf s f, inf t g) := sup_prodMap (α := αᵒᵈ) (β := βᵒᵈ) hs ht _ _ end Prod @[simp] theorem inf_erase_top [DecidableEq α] (s : Finset α) : (s.erase ⊤).inf id = s.inf id := @sup_erase_bot αᵒᵈ _ _ _ _ theorem comp_inf_eq_inf_comp [SemilatticeInf γ] [OrderTop γ] {s : Finset β} {f : β → α} (g : α → γ) (g_inf : ∀ x y, g (x ⊓ y) = g x ⊓ g y) (top : g ⊤ = ⊤) : g (s.inf f) = s.inf (g ∘ f) := @comp_sup_eq_sup_comp αᵒᵈ _ γᵒᵈ _ _ _ _ _ _ _ g_inf top /-- Computing `inf` in a subtype (closed under `inf`) is the same as computing it in `α`. -/ theorem inf_coe {P : α → Prop} {Ptop : P ⊤} {Pinf : ∀ ⦃x y⦄, P x → P y → P (x ⊓ y)} (t : Finset β) (f : β → { x : α // P x }) : (@inf { x // P x } _ (Subtype.semilatticeInf Pinf) (Subtype.orderTop Ptop) t f : α) = t.inf fun x => ↑(f x) := @sup_coe αᵒᵈ _ _ _ _ Ptop Pinf t f theorem _root_.List.foldr_inf_eq_inf_toFinset [DecidableEq α] (l : List α) : l.foldr (· ⊓ ·) ⊤ = l.toFinset.inf id := by rw [← coe_fold_r, ← Multiset.fold_dedup_idem, inf_def, ← List.toFinset_coe, toFinset_val, Multiset.map_id] rfl theorem inf_induction {p : α → Prop} (ht : p ⊤) (hp : ∀ a₁, p a₁ → ∀ a₂, p a₂ → p (a₁ ⊓ a₂)) (hs : ∀ b ∈ s, p (f b)) : p (s.inf f) := @sup_induction αᵒᵈ _ _ _ _ _ _ ht hp hs theorem inf_mem (s : Set α) (w₁ : ⊤ ∈ s) (w₂ : ∀ᵉ (x ∈ s) (y ∈ s), x ⊓ y ∈ s) {ι : Type*} (t : Finset ι) (p : ι → α) (h : ∀ i ∈ t, p i ∈ s) : t.inf p ∈ s := @inf_induction _ _ _ _ _ _ (· ∈ s) w₁ w₂ h @[simp] protected theorem inf_eq_top_iff (f : β → α) (S : Finset β) : S.inf f = ⊤ ↔ ∀ s ∈ S, f s = ⊤ := @Finset.sup_eq_bot_iff αᵒᵈ _ _ _ _ _ end Inf @[simp] theorem toDual_sup [SemilatticeSup α] [OrderBot α] (s : Finset β) (f : β → α) : toDual (s.sup f) = s.inf (toDual ∘ f) := rfl @[simp] theorem toDual_inf [SemilatticeInf α] [OrderTop α] (s : Finset β) (f : β → α) : toDual (s.inf f) = s.sup (toDual ∘ f) := rfl @[simp] theorem ofDual_sup [SemilatticeInf α] [OrderTop α] (s : Finset β) (f : β → αᵒᵈ) : ofDual (s.sup f) = s.inf (ofDual ∘ f) := rfl @[simp] theorem ofDual_inf [SemilatticeSup α] [OrderBot α] (s : Finset β) (f : β → αᵒᵈ) : ofDual (s.inf f) = s.sup (ofDual ∘ f) := rfl section DistribLattice variable [DistribLattice α] section OrderBot variable [OrderBot α] {s : Finset ι} {t : Finset κ} {f : ι → α} {g : κ → α} {a : α} theorem sup_inf_distrib_left (s : Finset ι) (f : ι → α) (a : α) : a ⊓ s.sup f = s.sup fun i => a ⊓ f i := by induction s using Finset.cons_induction with | empty => simp_rw [Finset.sup_empty, inf_bot_eq] | cons _ _ _ h => rw [sup_cons, sup_cons, inf_sup_left, h] theorem sup_inf_distrib_right (s : Finset ι) (f : ι → α) (a : α) : s.sup f ⊓ a = s.sup fun i => f i ⊓ a := by rw [_root_.inf_comm, s.sup_inf_distrib_left] simp_rw [_root_.inf_comm] protected theorem disjoint_sup_right : Disjoint a (s.sup f) ↔ ∀ ⦃i⦄, i ∈ s → Disjoint a (f i) := by simp only [disjoint_iff, sup_inf_distrib_left, Finset.sup_eq_bot_iff] protected theorem disjoint_sup_left : Disjoint (s.sup f) a ↔ ∀ ⦃i⦄, i ∈ s → Disjoint (f i) a := by simp only [disjoint_iff, sup_inf_distrib_right, Finset.sup_eq_bot_iff] theorem sup_inf_sup (s : Finset ι) (t : Finset κ) (f : ι → α) (g : κ → α) : s.sup f ⊓ t.sup g = (s ×ˢ t).sup fun i => f i.1 ⊓ g i.2 := by simp_rw [Finset.sup_inf_distrib_right, Finset.sup_inf_distrib_left, sup_product_left] end OrderBot section OrderTop variable [OrderTop α] {f : ι → α} {g : κ → α} {s : Finset ι} {t : Finset κ} {a : α} theorem inf_sup_distrib_left (s : Finset ι) (f : ι → α) (a : α) : a ⊔ s.inf f = s.inf fun i => a ⊔ f i := @sup_inf_distrib_left αᵒᵈ _ _ _ _ _ _ theorem inf_sup_distrib_right (s : Finset ι) (f : ι → α) (a : α) : s.inf f ⊔ a = s.inf fun i => f i ⊔ a := @sup_inf_distrib_right αᵒᵈ _ _ _ _ _ _ protected theorem codisjoint_inf_right : Codisjoint a (s.inf f) ↔ ∀ ⦃i⦄, i ∈ s → Codisjoint a (f i) := @Finset.disjoint_sup_right αᵒᵈ _ _ _ _ _ _ protected theorem codisjoint_inf_left : Codisjoint (s.inf f) a ↔ ∀ ⦃i⦄, i ∈ s → Codisjoint (f i) a := @Finset.disjoint_sup_left αᵒᵈ _ _ _ _ _ _ theorem inf_sup_inf (s : Finset ι) (t : Finset κ) (f : ι → α) (g : κ → α) : s.inf f ⊔ t.inf g = (s ×ˢ t).inf fun i => f i.1 ⊔ g i.2 := @sup_inf_sup αᵒᵈ _ _ _ _ _ _ _ _ end OrderTop section BoundedOrder variable [BoundedOrder α] [DecidableEq ι] --TODO: Extract out the obvious isomorphism `(insert i s).pi t ≃ t i ×ˢ s.pi t` from this proof theorem inf_sup {κ : ι → Type*} (s : Finset ι) (t : ∀ i, Finset (κ i)) (f : ∀ i, κ i → α) : (s.inf fun i => (t i).sup (f i)) = (s.pi t).sup fun g => s.attach.inf fun i => f _ <| g _ i.2 := by induction' s using Finset.induction with i s hi ih · simp rw [inf_insert, ih, attach_insert, sup_inf_sup] refine eq_of_forall_ge_iff fun c => ?_ simp only [Finset.sup_le_iff, mem_product, mem_pi, and_imp, Prod.forall, inf_insert, inf_image] refine ⟨fun h g hg => h (g i <| mem_insert_self _ _) (fun j hj => g j <| mem_insert_of_mem hj) (hg _ <| mem_insert_self _ _) fun j hj => hg _ <| mem_insert_of_mem hj, fun h a g ha hg => ?_⟩ -- TODO: This `have` must be named to prevent it being shadowed by the internal `this` in `simpa` have aux : ∀ j : { x // x ∈ s }, ↑j ≠ i := fun j : s => ne_of_mem_of_not_mem j.2 hi -- Porting note: `simpa` doesn't support placeholders in proof terms have := h (fun j hj => if hji : j = i then cast (congr_arg κ hji.symm) a else g _ <| mem_of_mem_insert_of_ne hj hji) (fun j hj => ?_) · simpa only [cast_eq, dif_pos, Function.comp, Subtype.coe_mk, dif_neg, aux] using this rw [mem_insert] at hj obtain (rfl | hj) := hj · simpa · simpa [ne_of_mem_of_not_mem hj hi] using hg _ _ theorem sup_inf {κ : ι → Type*} (s : Finset ι) (t : ∀ i, Finset (κ i)) (f : ∀ i, κ i → α) : (s.sup fun i => (t i).inf (f i)) = (s.pi t).inf fun g => s.attach.sup fun i => f _ <| g _ i.2 := @inf_sup αᵒᵈ _ _ _ _ _ _ _ _ end BoundedOrder end DistribLattice section BooleanAlgebra variable [BooleanAlgebra α] {s : Finset ι} theorem sup_sdiff_left (s : Finset ι) (f : ι → α) (a : α) : (s.sup fun b => a \ f b) = a \ s.inf f := by induction s using Finset.cons_induction with | empty => rw [sup_empty, inf_empty, sdiff_top] | cons _ _ _ h => rw [sup_cons, inf_cons, h, sdiff_inf] theorem inf_sdiff_left (hs : s.Nonempty) (f : ι → α) (a : α) : (s.inf fun b => a \ f b) = a \ s.sup f := by induction hs using Finset.Nonempty.cons_induction with | singleton => rw [sup_singleton, inf_singleton] | cons _ _ _ _ ih => rw [sup_cons, inf_cons, ih, sdiff_sup] theorem inf_sdiff_right (hs : s.Nonempty) (f : ι → α) (a : α) : (s.inf fun b => f b \ a) = s.inf f \ a := by induction hs using Finset.Nonempty.cons_induction with | singleton => rw [inf_singleton, inf_singleton] | cons _ _ _ _ ih => rw [inf_cons, inf_cons, ih, inf_sdiff] theorem inf_himp_right (s : Finset ι) (f : ι → α) (a : α) : (s.inf fun b => f b ⇨ a) = s.sup f ⇨ a := @sup_sdiff_left αᵒᵈ _ _ _ _ _ theorem sup_himp_right (hs : s.Nonempty) (f : ι → α) (a : α) : (s.sup fun b => f b ⇨ a) = s.inf f ⇨ a := @inf_sdiff_left αᵒᵈ _ _ _ hs _ _ theorem sup_himp_left (hs : s.Nonempty) (f : ι → α) (a : α) : (s.sup fun b => a ⇨ f b) = a ⇨ s.sup f := @inf_sdiff_right αᵒᵈ _ _ _ hs _ _ @[simp] protected theorem compl_sup (s : Finset ι) (f : ι → α) : (s.sup f)ᶜ = s.inf fun i => (f i)ᶜ := map_finset_sup (OrderIso.compl α) _ _ @[simp] protected theorem compl_inf (s : Finset ι) (f : ι → α) : (s.inf f)ᶜ = s.sup fun i => (f i)ᶜ := map_finset_inf (OrderIso.compl α) _ _ end BooleanAlgebra section LinearOrder variable [LinearOrder α] section OrderBot variable [OrderBot α] {s : Finset ι} {f : ι → α} {a : α} theorem comp_sup_eq_sup_comp_of_is_total [SemilatticeSup β] [OrderBot β] (g : α → β) (mono_g : Monotone g) (bot : g ⊥ = ⊥) : g (s.sup f) = s.sup (g ∘ f) := comp_sup_eq_sup_comp g mono_g.map_sup bot @[simp] protected theorem le_sup_iff (ha : ⊥ < a) : a ≤ s.sup f ↔ ∃ b ∈ s, a ≤ f b := by apply Iff.intro · induction s using cons_induction with | empty => exact (absurd · (not_le_of_lt ha)) | cons c t hc ih => rw [sup_cons, le_sup_iff] exact fun | Or.inl h => ⟨c, mem_cons.2 (Or.inl rfl), h⟩ | Or.inr h => let ⟨b, hb, hle⟩ := ih h; ⟨b, mem_cons.2 (Or.inr hb), hle⟩ · exact fun ⟨b, hb, hle⟩ => le_trans hle (le_sup hb) protected theorem sup_eq_top_iff {α : Type*} [LinearOrder α] [BoundedOrder α] [Nontrivial α] {s : Finset ι} {f : ι → α} : s.sup f = ⊤ ↔ ∃ b ∈ s, f b = ⊤ := by simp only [← top_le_iff] exact Finset.le_sup_iff bot_lt_top protected theorem Nonempty.sup_eq_top_iff {α : Type*} [LinearOrder α] [BoundedOrder α] {s : Finset ι} {f : ι → α} (hs : s.Nonempty) : s.sup f = ⊤ ↔ ∃ b ∈ s, f b = ⊤ := by cases subsingleton_or_nontrivial α · simpa [Subsingleton.elim _ (⊤ : α)] · exact Finset.sup_eq_top_iff @[simp] protected theorem lt_sup_iff : a < s.sup f ↔ ∃ b ∈ s, a < f b := by apply Iff.intro · induction s using cons_induction with | empty => exact (absurd · not_lt_bot) | cons c t hc ih => rw [sup_cons, lt_sup_iff] exact fun | Or.inl h => ⟨c, mem_cons.2 (Or.inl rfl), h⟩ | Or.inr h => let ⟨b, hb, hlt⟩ := ih h; ⟨b, mem_cons.2 (Or.inr hb), hlt⟩ · exact fun ⟨b, hb, hlt⟩ => lt_of_lt_of_le hlt (le_sup hb) @[simp] protected theorem sup_lt_iff (ha : ⊥ < a) : s.sup f < a ↔ ∀ b ∈ s, f b < a := ⟨fun hs b hb => lt_of_le_of_lt (le_sup hb) hs, Finset.cons_induction_on s (fun _ => ha) fun c t hc => by simpa only [sup_cons, sup_lt_iff, mem_cons, forall_eq_or_imp] using And.imp_right⟩ end OrderBot section OrderTop variable [OrderTop α] {s : Finset ι} {f : ι → α} {a : α} theorem comp_inf_eq_inf_comp_of_is_total [SemilatticeInf β] [OrderTop β] (g : α → β) (mono_g : Monotone g) (top : g ⊤ = ⊤) : g (s.inf f) = s.inf (g ∘ f) := comp_inf_eq_inf_comp g mono_g.map_inf top @[simp] protected theorem inf_le_iff (ha : a < ⊤) : s.inf f ≤ a ↔ ∃ b ∈ s, f b ≤ a := @Finset.le_sup_iff αᵒᵈ _ _ _ _ _ _ ha protected theorem inf_eq_bot_iff {α : Type*} [LinearOrder α] [BoundedOrder α] [Nontrivial α] {s : Finset ι} {f : ι → α} : s.inf f = ⊥ ↔ ∃ b ∈ s, f b = ⊥ := Finset.sup_eq_top_iff (α := αᵒᵈ) protected theorem Nonempty.inf_eq_bot_iff {α : Type*} [LinearOrder α] [BoundedOrder α] {s : Finset ι} {f : ι → α} (h : s.Nonempty) : s.inf f = ⊥ ↔ ∃ b ∈ s, f b = ⊥ := h.sup_eq_top_iff (α := αᵒᵈ) @[simp] protected theorem inf_lt_iff : s.inf f < a ↔ ∃ b ∈ s, f b < a := @Finset.lt_sup_iff αᵒᵈ _ _ _ _ _ _ @[simp] protected theorem lt_inf_iff (ha : a < ⊤) : a < s.inf f ↔ ∀ b ∈ s, a < f b := @Finset.sup_lt_iff αᵒᵈ _ _ _ _ _ _ ha end OrderTop end LinearOrder theorem inf_eq_iInf [CompleteLattice β] (s : Finset α) (f : α → β) : s.inf f = ⨅ a ∈ s, f a := @sup_eq_iSup _ βᵒᵈ _ _ _ theorem inf_id_eq_sInf [CompleteLattice α] (s : Finset α) : s.inf id = sInf s := @sup_id_eq_sSup αᵒᵈ _ _ theorem inf_id_set_eq_sInter (s : Finset (Set α)) : s.inf id = ⋂₀ ↑s := inf_id_eq_sInf _ @[simp] theorem inf_set_eq_iInter (s : Finset α) (f : α → Set β) : s.inf f = ⋂ x ∈ s, f x := inf_eq_iInf _ _ theorem inf_eq_sInf_image [CompleteLattice β] (s : Finset α) (f : α → β) : s.inf f = sInf (f '' s) := @sup_eq_sSup_image _ βᵒᵈ _ _ _ section Sup' variable [SemilatticeSup α] theorem sup_of_mem {s : Finset β} (f : β → α) {b : β} (h : b ∈ s) : ∃ a : α, s.sup ((↑) ∘ f : β → WithBot α) = ↑a := Exists.imp (fun _ => And.left) (@le_sup (WithBot α) _ _ _ _ _ _ h (f b) rfl) /-- Given nonempty finset `s` then `s.sup' H f` is the supremum of its image under `f` in (possibly unbounded) join-semilattice `α`, where `H` is a proof of nonemptiness. If `α` has a bottom element you may instead use `Finset.sup` which does not require `s` nonempty. -/ def sup' (s : Finset β) (H : s.Nonempty) (f : β → α) : α := WithBot.unbot (s.sup ((↑) ∘ f)) (by simpa using H) variable {s : Finset β} (H : s.Nonempty) (f : β → α) @[simp] theorem coe_sup' : ((s.sup' H f : α) : WithBot α) = s.sup ((↑) ∘ f) := by rw [sup', WithBot.coe_unbot] @[simp] theorem sup'_cons {b : β} {hb : b ∉ s} : (cons b s hb).sup' (nonempty_cons hb) f = f b ⊔ s.sup' H f := by rw [← WithBot.coe_eq_coe] simp [WithBot.coe_sup] @[simp] theorem sup'_insert [DecidableEq β] {b : β} : (insert b s).sup' (insert_nonempty _ _) f = f b ⊔ s.sup' H f := by rw [← WithBot.coe_eq_coe] simp [WithBot.coe_sup] @[simp] theorem sup'_singleton {b : β} : ({b} : Finset β).sup' (singleton_nonempty _) f = f b := rfl @[simp] theorem sup'_le_iff {a : α} : s.sup' H f ≤ a ↔ ∀ b ∈ s, f b ≤ a := by simp_rw [← @WithBot.coe_le_coe α, coe_sup', Finset.sup_le_iff]; rfl alias ⟨_, sup'_le⟩ := sup'_le_iff theorem le_sup' {b : β} (h : b ∈ s) : f b ≤ s.sup' ⟨b, h⟩ f := (sup'_le_iff ⟨b, h⟩ f).1 le_rfl b h theorem le_sup'_of_le {a : α} {b : β} (hb : b ∈ s) (h : a ≤ f b) : a ≤ s.sup' ⟨b, hb⟩ f := h.trans <| le_sup' _ hb @[simp] theorem sup'_const (a : α) : s.sup' H (fun _ => a) = a := by apply le_antisymm · apply sup'_le intros exact le_rfl · apply le_sup' (fun _ => a) H.choose_spec theorem sup'_union [DecidableEq β] {s₁ s₂ : Finset β} (h₁ : s₁.Nonempty) (h₂ : s₂.Nonempty) (f : β → α) : (s₁ ∪ s₂).sup' (h₁.mono subset_union_left) f = s₁.sup' h₁ f ⊔ s₂.sup' h₂ f := eq_of_forall_ge_iff fun a => by simp [or_imp, forall_and] theorem sup'_biUnion [DecidableEq β] {s : Finset γ} (Hs : s.Nonempty) {t : γ → Finset β} (Ht : ∀ b, (t b).Nonempty) : (s.biUnion t).sup' (Hs.biUnion fun b _ => Ht b) f = s.sup' Hs (fun b => (t b).sup' (Ht b) f) := eq_of_forall_ge_iff fun c => by simp [@forall_swap _ β] protected theorem sup'_comm {t : Finset γ} (hs : s.Nonempty) (ht : t.Nonempty) (f : β → γ → α) : (s.sup' hs fun b => t.sup' ht (f b)) = t.sup' ht fun c => s.sup' hs fun b => f b c := eq_of_forall_ge_iff fun a => by simpa using forall₂_swap theorem sup'_product_left {t : Finset γ} (h : (s ×ˢ t).Nonempty) (f : β × γ → α) : (s ×ˢ t).sup' h f = s.sup' h.fst fun i => t.sup' h.snd fun i' => f ⟨i, i'⟩ := eq_of_forall_ge_iff fun a => by simp [@forall_swap _ γ] theorem sup'_product_right {t : Finset γ} (h : (s ×ˢ t).Nonempty) (f : β × γ → α) : (s ×ˢ t).sup' h f = t.sup' h.snd fun i' => s.sup' h.fst fun i => f ⟨i, i'⟩ := by rw [sup'_product_left, Finset.sup'_comm] section Prod variable {ι κ α β : Type*} [SemilatticeSup α] [SemilatticeSup β] {s : Finset ι} {t : Finset κ} /-- See also `Finset.sup'_prodMap`. -/ lemma prodMk_sup'_sup' (hs : s.Nonempty) (ht : t.Nonempty) (f : ι → α) (g : κ → β) : (sup' s hs f, sup' t ht g) = sup' (s ×ˢ t) (hs.product ht) (Prod.map f g) := eq_of_forall_ge_iff fun i ↦ by obtain ⟨a, ha⟩ := hs obtain ⟨b, hb⟩ := ht simp only [Prod.map, sup'_le_iff, mem_product, and_imp, Prod.forall, Prod.le_def] exact ⟨by aesop, fun h ↦ ⟨fun i hi ↦ (h _ _ hi hb).1, fun j hj ↦ (h _ _ ha hj).2⟩⟩ /-- See also `Finset.prodMk_sup'_sup'`. -/ -- @[simp] -- TODO: Why does `Prod.map_apply` simplify the LHS? lemma sup'_prodMap (hst : (s ×ˢ t).Nonempty) (f : ι → α) (g : κ → β) : sup' (s ×ˢ t) hst (Prod.map f g) = (sup' s hst.fst f, sup' t hst.snd g) := (prodMk_sup'_sup' _ _ _ _).symm end Prod theorem sup'_induction {p : α → Prop} (hp : ∀ a₁, p a₁ → ∀ a₂, p a₂ → p (a₁ ⊔ a₂)) (hs : ∀ b ∈ s, p (f b)) : p (s.sup' H f) := by show @WithBot.recBotCoe α (fun _ => Prop) True p ↑(s.sup' H f) rw [coe_sup'] refine sup_induction trivial (fun a₁ h₁ a₂ h₂ ↦ ?_) hs match a₁, a₂ with | ⊥, _ => rwa [bot_sup_eq] | (a₁ : α), ⊥ => rwa [sup_bot_eq] | (a₁ : α), (a₂ : α) => exact hp a₁ h₁ a₂ h₂ theorem sup'_mem (s : Set α) (w : ∀ᵉ (x ∈ s) (y ∈ s), x ⊔ y ∈ s) {ι : Type*} (t : Finset ι) (H : t.Nonempty) (p : ι → α) (h : ∀ i ∈ t, p i ∈ s) : t.sup' H p ∈ s := sup'_induction H p w h @[congr] theorem sup'_congr {t : Finset β} {f g : β → α} (h₁ : s = t) (h₂ : ∀ x ∈ s, f x = g x) : s.sup' H f = t.sup' (h₁ ▸ H) g := by subst s refine eq_of_forall_ge_iff fun c => ?_ simp (config := { contextual := true }) only [sup'_le_iff, h₂] theorem comp_sup'_eq_sup'_comp [SemilatticeSup γ] {s : Finset β} (H : s.Nonempty) {f : β → α} (g : α → γ) (g_sup : ∀ x y, g (x ⊔ y) = g x ⊔ g y) : g (s.sup' H f) = s.sup' H (g ∘ f) := by refine H.cons_induction ?_ ?_ <;> intros <;> simp [*] @[simp] theorem _root_.map_finset_sup' [SemilatticeSup β] [FunLike F α β] [SupHomClass F α β] (f : F) {s : Finset ι} (hs) (g : ι → α) : f (s.sup' hs g) = s.sup' hs (f ∘ g) := by refine hs.cons_induction ?_ ?_ <;> intros <;> simp [*] lemma nsmul_sup' {α'} [LinearOrderedAddCommMonoid β] {s : Finset α'} (hs : s.Nonempty) (f : α' → β) (n : ℕ) : s.sup' hs (fun a => n • f a) = n • s.sup' hs f := let ns : SupHom β β := { toFun := (n • ·), map_sup' := fun _ _ => (nsmul_right_mono n).map_max } (map_finset_sup' ns hs _).symm /-- To rewrite from right to left, use `Finset.sup'_comp_eq_image`. -/ @[simp] theorem sup'_image [DecidableEq β] {s : Finset γ} {f : γ → β} (hs : (s.image f).Nonempty) (g : β → α) : (s.image f).sup' hs g = s.sup' hs.of_image (g ∘ f) := by rw [← WithBot.coe_eq_coe]; simp only [coe_sup', sup_image, WithBot.coe_sup]; rfl /-- A version of `Finset.sup'_image` with LHS and RHS reversed. Also, this lemma assumes that `s` is nonempty instead of assuming that its image is nonempty. -/ lemma sup'_comp_eq_image [DecidableEq β] {s : Finset γ} {f : γ → β} (hs : s.Nonempty) (g : β → α) : s.sup' hs (g ∘ f) = (s.image f).sup' (hs.image f) g := .symm <| sup'_image _ _ /-- To rewrite from right to left, use `Finset.sup'_comp_eq_map`. -/ @[simp] theorem sup'_map {s : Finset γ} {f : γ ↪ β} (g : β → α) (hs : (s.map f).Nonempty) : (s.map f).sup' hs g = s.sup' (map_nonempty.1 hs) (g ∘ f) := by rw [← WithBot.coe_eq_coe, coe_sup', sup_map, coe_sup'] rfl /-- A version of `Finset.sup'_map` with LHS and RHS reversed. Also, this lemma assumes that `s` is nonempty instead of assuming that its image is nonempty. -/ lemma sup'_comp_eq_map {s : Finset γ} {f : γ ↪ β} (g : β → α) (hs : s.Nonempty) : s.sup' hs (g ∘ f) = (s.map f).sup' (map_nonempty.2 hs) g := .symm <| sup'_map _ _ @[gcongr] theorem sup'_mono {s₁ s₂ : Finset β} (h : s₁ ⊆ s₂) (h₁ : s₁.Nonempty) : s₁.sup' h₁ f ≤ s₂.sup' (h₁.mono h) f := Finset.sup'_le h₁ _ (fun _ hb => le_sup' _ (h hb)) end Sup' section Inf' variable [SemilatticeInf α] theorem inf_of_mem {s : Finset β} (f : β → α) {b : β} (h : b ∈ s) : ∃ a : α, s.inf ((↑) ∘ f : β → WithTop α) = ↑a := @sup_of_mem αᵒᵈ _ _ _ f _ h /-- Given nonempty finset `s` then `s.inf' H f` is the infimum of its image under `f` in (possibly unbounded) meet-semilattice `α`, where `H` is a proof of nonemptiness. If `α` has a top element you may instead use `Finset.inf` which does not require `s` nonempty. -/ def inf' (s : Finset β) (H : s.Nonempty) (f : β → α) : α := WithTop.untop (s.inf ((↑) ∘ f)) (by simpa using H) variable {s : Finset β} (H : s.Nonempty) (f : β → α) @[simp] theorem coe_inf' : ((s.inf' H f : α) : WithTop α) = s.inf ((↑) ∘ f) := @coe_sup' αᵒᵈ _ _ _ H f @[simp] theorem inf'_cons {b : β} {hb : b ∉ s} : (cons b s hb).inf' (nonempty_cons hb) f = f b ⊓ s.inf' H f := @sup'_cons αᵒᵈ _ _ _ H f _ _ @[simp] theorem inf'_insert [DecidableEq β] {b : β} : (insert b s).inf' (insert_nonempty _ _) f = f b ⊓ s.inf' H f := @sup'_insert αᵒᵈ _ _ _ H f _ _ @[simp] theorem inf'_singleton {b : β} : ({b} : Finset β).inf' (singleton_nonempty _) f = f b := rfl @[simp] theorem le_inf'_iff {a : α} : a ≤ s.inf' H f ↔ ∀ b ∈ s, a ≤ f b := sup'_le_iff (α := αᵒᵈ) H f theorem le_inf' {a : α} (hs : ∀ b ∈ s, a ≤ f b) : a ≤ s.inf' H f := sup'_le (α := αᵒᵈ) H f hs theorem inf'_le {b : β} (h : b ∈ s) : s.inf' ⟨b, h⟩ f ≤ f b := le_sup' (α := αᵒᵈ) f h theorem inf'_le_of_le {a : α} {b : β} (hb : b ∈ s) (h : f b ≤ a) : s.inf' ⟨b, hb⟩ f ≤ a := (inf'_le _ hb).trans h @[simp] theorem inf'_const (a : α) : (s.inf' H fun _ => a) = a := sup'_const (α := αᵒᵈ) H a theorem inf'_union [DecidableEq β] {s₁ s₂ : Finset β} (h₁ : s₁.Nonempty) (h₂ : s₂.Nonempty) (f : β → α) : (s₁ ∪ s₂).inf' (h₁.mono subset_union_left) f = s₁.inf' h₁ f ⊓ s₂.inf' h₂ f := @sup'_union αᵒᵈ _ _ _ _ _ h₁ h₂ _ theorem inf'_biUnion [DecidableEq β] {s : Finset γ} (Hs : s.Nonempty) {t : γ → Finset β} (Ht : ∀ b, (t b).Nonempty) : (s.biUnion t).inf' (Hs.biUnion fun b _ => Ht b) f = s.inf' Hs (fun b => (t b).inf' (Ht b) f) := sup'_biUnion (α := αᵒᵈ) _ Hs Ht protected theorem inf'_comm {t : Finset γ} (hs : s.Nonempty) (ht : t.Nonempty) (f : β → γ → α) : (s.inf' hs fun b => t.inf' ht (f b)) = t.inf' ht fun c => s.inf' hs fun b => f b c := @Finset.sup'_comm αᵒᵈ _ _ _ _ _ hs ht _ theorem inf'_product_left {t : Finset γ} (h : (s ×ˢ t).Nonempty) (f : β × γ → α) : (s ×ˢ t).inf' h f = s.inf' h.fst fun i => t.inf' h.snd fun i' => f ⟨i, i'⟩ := sup'_product_left (α := αᵒᵈ) h f theorem inf'_product_right {t : Finset γ} (h : (s ×ˢ t).Nonempty) (f : β × γ → α) : (s ×ˢ t).inf' h f = t.inf' h.snd fun i' => s.inf' h.fst fun i => f ⟨i, i'⟩ := sup'_product_right (α := αᵒᵈ) h f section Prod variable {ι κ α β : Type*} [SemilatticeInf α] [SemilatticeInf β] {s : Finset ι} {t : Finset κ} /-- See also `Finset.inf'_prodMap`. -/ lemma prodMk_inf'_inf' (hs : s.Nonempty) (ht : t.Nonempty) (f : ι → α) (g : κ → β) : (inf' s hs f, inf' t ht g) = inf' (s ×ˢ t) (hs.product ht) (Prod.map f g) := prodMk_sup'_sup' (α := αᵒᵈ) (β := βᵒᵈ) hs ht _ _ /-- See also `Finset.prodMk_inf'_inf'`. -/ -- @[simp] -- TODO: Why does `Prod.map_apply` simplify the LHS? lemma inf'_prodMap (hst : (s ×ˢ t).Nonempty) (f : ι → α) (g : κ → β) : inf' (s ×ˢ t) hst (Prod.map f g) = (inf' s hst.fst f, inf' t hst.snd g) := (prodMk_inf'_inf' _ _ _ _).symm end Prod theorem comp_inf'_eq_inf'_comp [SemilatticeInf γ] {s : Finset β} (H : s.Nonempty) {f : β → α} (g : α → γ) (g_inf : ∀ x y, g (x ⊓ y) = g x ⊓ g y) : g (s.inf' H f) = s.inf' H (g ∘ f) := comp_sup'_eq_sup'_comp (α := αᵒᵈ) (γ := γᵒᵈ) H g g_inf theorem inf'_induction {p : α → Prop} (hp : ∀ a₁, p a₁ → ∀ a₂, p a₂ → p (a₁ ⊓ a₂)) (hs : ∀ b ∈ s, p (f b)) : p (s.inf' H f) := sup'_induction (α := αᵒᵈ) H f hp hs theorem inf'_mem (s : Set α) (w : ∀ᵉ (x ∈ s) (y ∈ s), x ⊓ y ∈ s) {ι : Type*} (t : Finset ι) (H : t.Nonempty) (p : ι → α) (h : ∀ i ∈ t, p i ∈ s) : t.inf' H p ∈ s := inf'_induction H p w h @[congr] theorem inf'_congr {t : Finset β} {f g : β → α} (h₁ : s = t) (h₂ : ∀ x ∈ s, f x = g x) : s.inf' H f = t.inf' (h₁ ▸ H) g := sup'_congr (α := αᵒᵈ) H h₁ h₂ @[simp] theorem _root_.map_finset_inf' [SemilatticeInf β] [FunLike F α β] [InfHomClass F α β] (f : F) {s : Finset ι} (hs) (g : ι → α) : f (s.inf' hs g) = s.inf' hs (f ∘ g) := by refine hs.cons_induction ?_ ?_ <;> intros <;> simp [*] lemma nsmul_inf' {α'} [LinearOrderedAddCommMonoid β] {s : Finset α'} (hs : s.Nonempty) (f : α' → β) (n : ℕ) : s.inf' hs (fun a => n • f a) = n • s.inf' hs f := let ns : InfHom β β := { toFun := (n • ·), map_inf' := fun _ _ => (nsmul_right_mono n).map_min } (map_finset_inf' ns hs _).symm /-- To rewrite from right to left, use `Finset.inf'_comp_eq_image`. -/ @[simp] theorem inf'_image [DecidableEq β] {s : Finset γ} {f : γ → β} (hs : (s.image f).Nonempty) (g : β → α) : (s.image f).inf' hs g = s.inf' hs.of_image (g ∘ f) := @sup'_image αᵒᵈ _ _ _ _ _ _ hs _ /-- A version of `Finset.inf'_image` with LHS and RHS reversed. Also, this lemma assumes that `s` is nonempty instead of assuming that its image is nonempty. -/ lemma inf'_comp_eq_image [DecidableEq β] {s : Finset γ} {f : γ → β} (hs : s.Nonempty) (g : β → α) : s.inf' hs (g ∘ f) = (s.image f).inf' (hs.image f) g := sup'_comp_eq_image (α := αᵒᵈ) hs g /-- To rewrite from right to left, use `Finset.inf'_comp_eq_map`. -/ @[simp] theorem inf'_map {s : Finset γ} {f : γ ↪ β} (g : β → α) (hs : (s.map f).Nonempty) : (s.map f).inf' hs g = s.inf' (map_nonempty.1 hs) (g ∘ f) := sup'_map (α := αᵒᵈ) _ hs /-- A version of `Finset.inf'_map` with LHS and RHS reversed. Also, this lemma assumes that `s` is nonempty instead of assuming that its image is nonempty. -/ lemma inf'_comp_eq_map {s : Finset γ} {f : γ ↪ β} (g : β → α) (hs : s.Nonempty) : s.inf' hs (g ∘ f) = (s.map f).inf' (map_nonempty.2 hs) g := sup'_comp_eq_map (α := αᵒᵈ) g hs @[gcongr] theorem inf'_mono {s₁ s₂ : Finset β} (h : s₁ ⊆ s₂) (h₁ : s₁.Nonempty) : s₂.inf' (h₁.mono h) f ≤ s₁.inf' h₁ f := Finset.le_inf' h₁ _ (fun _ hb => inf'_le _ (h hb)) end Inf' section Sup variable [SemilatticeSup α] [OrderBot α] theorem sup'_eq_sup {s : Finset β} (H : s.Nonempty) (f : β → α) : s.sup' H f = s.sup f := le_antisymm (sup'_le H f fun _ => le_sup) (Finset.sup_le fun _ => le_sup' f) theorem coe_sup_of_nonempty {s : Finset β} (h : s.Nonempty) (f : β → α) : (↑(s.sup f) : WithBot α) = s.sup ((↑) ∘ f) := by simp only [← sup'_eq_sup h, coe_sup' h] end Sup section Inf variable [SemilatticeInf α] [OrderTop α] theorem inf'_eq_inf {s : Finset β} (H : s.Nonempty) (f : β → α) : s.inf' H f = s.inf f := sup'_eq_sup (α := αᵒᵈ) H f theorem coe_inf_of_nonempty {s : Finset β} (h : s.Nonempty) (f : β → α) : (↑(s.inf f) : WithTop α) = s.inf ((↑) ∘ f) := coe_sup_of_nonempty (α := αᵒᵈ) h f end Inf @[simp] protected theorem sup_apply {C : β → Type*} [∀ b : β, SemilatticeSup (C b)] [∀ b : β, OrderBot (C b)] (s : Finset α) (f : α → ∀ b : β, C b) (b : β) : s.sup f b = s.sup fun a => f a b := comp_sup_eq_sup_comp (fun x : ∀ b : β, C b => x b) (fun _ _ => rfl) rfl @[simp] protected theorem inf_apply {C : β → Type*} [∀ b : β, SemilatticeInf (C b)] [∀ b : β, OrderTop (C b)] (s : Finset α) (f : α → ∀ b : β, C b) (b : β) : s.inf f b = s.inf fun a => f a b := Finset.sup_apply (C := fun b => (C b)ᵒᵈ) s f b @[simp] protected theorem sup'_apply {C : β → Type*} [∀ b : β, SemilatticeSup (C b)] {s : Finset α} (H : s.Nonempty) (f : α → ∀ b : β, C b) (b : β) : s.sup' H f b = s.sup' H fun a => f a b := comp_sup'_eq_sup'_comp H (fun x : ∀ b : β, C b => x b) fun _ _ => rfl @[simp] protected theorem inf'_apply {C : β → Type*} [∀ b : β, SemilatticeInf (C b)] {s : Finset α} (H : s.Nonempty) (f : α → ∀ b : β, C b) (b : β) : s.inf' H f b = s.inf' H fun a => f a b := Finset.sup'_apply (C := fun b => (C b)ᵒᵈ) H f b @[simp] theorem toDual_sup' [SemilatticeSup α] {s : Finset ι} (hs : s.Nonempty) (f : ι → α) : toDual (s.sup' hs f) = s.inf' hs (toDual ∘ f) := rfl @[simp] theorem toDual_inf' [SemilatticeInf α] {s : Finset ι} (hs : s.Nonempty) (f : ι → α) : toDual (s.inf' hs f) = s.sup' hs (toDual ∘ f) := rfl @[simp] theorem ofDual_sup' [SemilatticeInf α] {s : Finset ι} (hs : s.Nonempty) (f : ι → αᵒᵈ) : ofDual (s.sup' hs f) = s.inf' hs (ofDual ∘ f) := rfl @[simp] theorem ofDual_inf' [SemilatticeSup α] {s : Finset ι} (hs : s.Nonempty) (f : ι → αᵒᵈ) : ofDual (s.inf' hs f) = s.sup' hs (ofDual ∘ f) := rfl section DistribLattice variable [DistribLattice α] {s : Finset ι} {t : Finset κ} (hs : s.Nonempty) (ht : t.Nonempty) {f : ι → α} {g : κ → α} {a : α} theorem sup'_inf_distrib_left (f : ι → α) (a : α) : a ⊓ s.sup' hs f = s.sup' hs fun i ↦ a ⊓ f i := by induction hs using Finset.Nonempty.cons_induction with | singleton => simp | cons _ _ _ hs ih => simp_rw [sup'_cons hs, inf_sup_left, ih] theorem sup'_inf_distrib_right (f : ι → α) (a : α) : s.sup' hs f ⊓ a = s.sup' hs fun i => f i ⊓ a := by rw [inf_comm, sup'_inf_distrib_left]; simp_rw [inf_comm] theorem sup'_inf_sup' (f : ι → α) (g : κ → α) : s.sup' hs f ⊓ t.sup' ht g = (s ×ˢ t).sup' (hs.product ht) fun i => f i.1 ⊓ g i.2 := by simp_rw [Finset.sup'_inf_distrib_right, Finset.sup'_inf_distrib_left, sup'_product_left] theorem inf'_sup_distrib_left (f : ι → α) (a : α) : a ⊔ s.inf' hs f = s.inf' hs fun i => a ⊔ f i := @sup'_inf_distrib_left αᵒᵈ _ _ _ hs _ _ theorem inf'_sup_distrib_right (f : ι → α) (a : α) : s.inf' hs f ⊔ a = s.inf' hs fun i => f i ⊔ a := @sup'_inf_distrib_right αᵒᵈ _ _ _ hs _ _ theorem inf'_sup_inf' (f : ι → α) (g : κ → α) : s.inf' hs f ⊔ t.inf' ht g = (s ×ˢ t).inf' (hs.product ht) fun i => f i.1 ⊔ g i.2 := @sup'_inf_sup' αᵒᵈ _ _ _ _ _ hs ht _ _ end DistribLattice section LinearOrder variable [LinearOrder α] {s : Finset ι} (H : s.Nonempty) {f : ι → α} {a : α} @[simp] theorem le_sup'_iff : a ≤ s.sup' H f ↔ ∃ b ∈ s, a ≤ f b := by rw [← WithBot.coe_le_coe, coe_sup', Finset.le_sup_iff (WithBot.bot_lt_coe a)] exact exists_congr (fun _ => and_congr_right' WithBot.coe_le_coe) @[simp] theorem lt_sup'_iff : a < s.sup' H f ↔ ∃ b ∈ s, a < f b := by rw [← WithBot.coe_lt_coe, coe_sup', Finset.lt_sup_iff] exact exists_congr (fun _ => and_congr_right' WithBot.coe_lt_coe) @[simp] theorem sup'_lt_iff : s.sup' H f < a ↔ ∀ i ∈ s, f i < a := by rw [← WithBot.coe_lt_coe, coe_sup', Finset.sup_lt_iff (WithBot.bot_lt_coe a)] exact forall₂_congr (fun _ _ => WithBot.coe_lt_coe) @[simp] theorem inf'_le_iff : s.inf' H f ≤ a ↔ ∃ i ∈ s, f i ≤ a := le_sup'_iff (α := αᵒᵈ) H @[simp] theorem inf'_lt_iff : s.inf' H f < a ↔ ∃ i ∈ s, f i < a := lt_sup'_iff (α := αᵒᵈ) H @[simp] theorem lt_inf'_iff : a < s.inf' H f ↔ ∀ i ∈ s, a < f i := sup'_lt_iff (α := αᵒᵈ) H theorem exists_mem_eq_sup' (f : ι → α) : ∃ i, i ∈ s ∧ s.sup' H f = f i := by induction H using Finset.Nonempty.cons_induction with | singleton c => exact ⟨c, mem_singleton_self c, rfl⟩ | cons c s hcs hs ih => rcases ih with ⟨b, hb, h'⟩ rw [sup'_cons hs, h'] cases le_total (f b) (f c) with | inl h => exact ⟨c, mem_cons.2 (Or.inl rfl), sup_eq_left.2 h⟩ | inr h => exact ⟨b, mem_cons.2 (Or.inr hb), sup_eq_right.2 h⟩ theorem exists_mem_eq_inf' (f : ι → α) : ∃ i, i ∈ s ∧ s.inf' H f = f i := exists_mem_eq_sup' (α := αᵒᵈ) H f theorem exists_mem_eq_sup [OrderBot α] (s : Finset ι) (h : s.Nonempty) (f : ι → α) : ∃ i, i ∈ s ∧ s.sup f = f i := sup'_eq_sup h f ▸ exists_mem_eq_sup' h f theorem exists_mem_eq_inf [OrderTop α] (s : Finset ι) (h : s.Nonempty) (f : ι → α) : ∃ i, i ∈ s ∧ s.inf f = f i := exists_mem_eq_sup (α := αᵒᵈ) s h f end LinearOrder /-! ### max and min of finite sets -/ section MaxMin variable [LinearOrder α] /-- Let `s` be a finset in a linear order. Then `s.max` is the maximum of `s` if `s` is not empty, and `⊥` otherwise. It belongs to `WithBot α`. If you want to get an element of `α`, see `s.max'`. -/ protected def max (s : Finset α) : WithBot α := sup s (↑) theorem max_eq_sup_coe {s : Finset α} : s.max = s.sup (↑) := rfl theorem max_eq_sup_withBot (s : Finset α) : s.max = sup s (↑) := rfl @[simp] theorem max_empty : (∅ : Finset α).max = ⊥ := rfl @[simp] theorem max_insert {a : α} {s : Finset α} : (insert a s).max = max ↑a s.max := fold_insert_idem @[simp] theorem max_singleton {a : α} : Finset.max {a} = (a : WithBot α) := by rw [← insert_emptyc_eq] exact max_insert theorem max_of_mem {s : Finset α} {a : α} (h : a ∈ s) : ∃ b : α, s.max = b := by obtain ⟨b, h, _⟩ := le_sup (α := WithBot α) h _ rfl exact ⟨b, h⟩ theorem max_of_nonempty {s : Finset α} (h : s.Nonempty) : ∃ a : α, s.max = a := let ⟨_, h⟩ := h max_of_mem h theorem max_eq_bot {s : Finset α} : s.max = ⊥ ↔ s = ∅ := ⟨fun h ↦ s.eq_empty_or_nonempty.elim id fun H ↦ by obtain ⟨a, ha⟩ := max_of_nonempty H rw [h] at ha; cases ha; , -- the `;` is needed since the `cases` syntax allows `cases a, b` fun h ↦ h.symm ▸ max_empty⟩ theorem mem_of_max {s : Finset α} : ∀ {a : α}, s.max = a → a ∈ s := by induction' s using Finset.induction_on with b s _ ih · intro _ H; cases H · intro a h by_cases p : b = a · induction p exact mem_insert_self b s · cases' max_choice (↑b) s.max with q q <;> rw [max_insert, q] at h · cases h cases p rfl · exact mem_insert_of_mem (ih h) theorem le_max {a : α} {s : Finset α} (as : a ∈ s) : ↑a ≤ s.max := le_sup as theorem not_mem_of_max_lt_coe {a : α} {s : Finset α} (h : s.max < a) : a ∉ s := mt le_max h.not_le theorem le_max_of_eq {s : Finset α} {a b : α} (h₁ : a ∈ s) (h₂ : s.max = b) : a ≤ b := WithBot.coe_le_coe.mp <| (le_max h₁).trans h₂.le theorem not_mem_of_max_lt {s : Finset α} {a b : α} (h₁ : b < a) (h₂ : s.max = ↑b) : a ∉ s := Finset.not_mem_of_max_lt_coe <| h₂.trans_lt <| WithBot.coe_lt_coe.mpr h₁ @[gcongr] theorem max_mono {s t : Finset α} (st : s ⊆ t) : s.max ≤ t.max := sup_mono st protected theorem max_le {M : WithBot α} {s : Finset α} (st : ∀ a ∈ s, (a : WithBot α) ≤ M) : s.max ≤ M := Finset.sup_le st @[simp] protected lemma max_le_iff {m : WithBot α} {s : Finset α} : s.max ≤ m ↔ ∀ a ∈ s, a ≤ m := Finset.sup_le_iff @[simp] protected lemma max_eq_top [OrderTop α] {s : Finset α} : s.max = ⊤ ↔ ⊤ ∈ s := Finset.sup_eq_top_iff.trans <| by simp /-- Let `s` be a finset in a linear order. Then `s.min` is the minimum of `s` if `s` is not empty, and `⊤` otherwise. It belongs to `WithTop α`. If you want to get an element of `α`, see `s.min'`. -/ protected def min (s : Finset α) : WithTop α := inf s (↑) theorem min_eq_inf_withTop (s : Finset α) : s.min = inf s (↑) := rfl @[simp] theorem min_empty : (∅ : Finset α).min = ⊤ := rfl @[simp] theorem min_insert {a : α} {s : Finset α} : (insert a s).min = min (↑a) s.min := fold_insert_idem @[simp] theorem min_singleton {a : α} : Finset.min {a} = (a : WithTop α) := by rw [← insert_emptyc_eq] exact min_insert theorem min_of_mem {s : Finset α} {a : α} (h : a ∈ s) : ∃ b : α, s.min = b := by obtain ⟨b, h, _⟩ := inf_le (α := WithTop α) h _ rfl exact ⟨b, h⟩ theorem min_of_nonempty {s : Finset α} (h : s.Nonempty) : ∃ a : α, s.min = a := let ⟨_, h⟩ := h min_of_mem h @[simp] theorem min_eq_top {s : Finset α} : s.min = ⊤ ↔ s = ∅ := by simp [Finset.min, eq_empty_iff_forall_not_mem] theorem mem_of_min {s : Finset α} : ∀ {a : α}, s.min = a → a ∈ s := @mem_of_max αᵒᵈ _ s theorem min_le {a : α} {s : Finset α} (as : a ∈ s) : s.min ≤ a := inf_le as theorem not_mem_of_coe_lt_min {a : α} {s : Finset α} (h : ↑a < s.min) : a ∉ s := mt min_le h.not_le theorem min_le_of_eq {s : Finset α} {a b : α} (h₁ : b ∈ s) (h₂ : s.min = a) : a ≤ b := WithTop.coe_le_coe.mp <| h₂.ge.trans (min_le h₁) theorem not_mem_of_lt_min {s : Finset α} {a b : α} (h₁ : a < b) (h₂ : s.min = ↑b) : a ∉ s := Finset.not_mem_of_coe_lt_min <| (WithTop.coe_lt_coe.mpr h₁).trans_eq h₂.symm @[gcongr] theorem min_mono {s t : Finset α} (st : s ⊆ t) : t.min ≤ s.min := inf_mono st protected theorem le_min {m : WithTop α} {s : Finset α} (st : ∀ a : α, a ∈ s → m ≤ a) : m ≤ s.min := Finset.le_inf st @[simp] protected theorem le_min_iff {m : WithTop α} {s : Finset α} : m ≤ s.min ↔ ∀ a ∈ s, m ≤ a := Finset.le_inf_iff @[simp] protected theorem min_eq_bot [OrderBot α] {s : Finset α} : s.min = ⊥ ↔ ⊥ ∈ s := Finset.max_eq_top (α := αᵒᵈ) /-- Given a nonempty finset `s` in a linear order `α`, then `s.min' h` is its minimum, as an element of `α`, where `h` is a proof of nonemptiness. Without this assumption, use instead `s.min`, taking values in `WithTop α`. -/ def min' (s : Finset α) (H : s.Nonempty) : α := inf' s H id /-- Given a nonempty finset `s` in a linear order `α`, then `s.max' h` is its maximum, as an element of `α`, where `h` is a proof of nonemptiness. Without this assumption, use instead `s.max`, taking values in `WithBot α`. -/ def max' (s : Finset α) (H : s.Nonempty) : α := sup' s H id variable (s : Finset α) (H : s.Nonempty) {x : α} theorem min'_mem : s.min' H ∈ s := mem_of_min <| by simp only [Finset.min, min', id_eq, coe_inf']; rfl theorem min'_le (x) (H2 : x ∈ s) : s.min' ⟨x, H2⟩ ≤ x := min_le_of_eq H2 (WithTop.coe_untop _ _).symm theorem le_min' (x) (H2 : ∀ y ∈ s, x ≤ y) : x ≤ s.min' H := H2 _ <| min'_mem _ _ theorem isLeast_min' : IsLeast (↑s) (s.min' H) := ⟨min'_mem _ _, min'_le _⟩ @[simp] theorem le_min'_iff {x} : x ≤ s.min' H ↔ ∀ y ∈ s, x ≤ y := le_isGLB_iff (isLeast_min' s H).isGLB /-- `{a}.min' _` is `a`. -/ @[simp] theorem min'_singleton (a : α) : ({a} : Finset α).min' (singleton_nonempty _) = a := by simp [min'] theorem max'_mem : s.max' H ∈ s := mem_of_max <| by simp only [max', Finset.max, id_eq, coe_sup']; rfl theorem le_max' (x) (H2 : x ∈ s) : x ≤ s.max' ⟨x, H2⟩ := le_max_of_eq H2 (WithBot.coe_unbot _ _).symm theorem max'_le (x) (H2 : ∀ y ∈ s, y ≤ x) : s.max' H ≤ x := H2 _ <| max'_mem _ _ theorem isGreatest_max' : IsGreatest (↑s) (s.max' H) := ⟨max'_mem _ _, le_max' _⟩ @[simp] theorem max'_le_iff {x} : s.max' H ≤ x ↔ ∀ y ∈ s, y ≤ x := isLUB_le_iff (isGreatest_max' s H).isLUB @[simp] theorem max'_lt_iff {x} : s.max' H < x ↔ ∀ y ∈ s, y < x := ⟨fun Hlt y hy => (s.le_max' y hy).trans_lt Hlt, fun H => H _ <| s.max'_mem _⟩ @[simp] theorem lt_min'_iff : x < s.min' H ↔ ∀ y ∈ s, x < y := @max'_lt_iff αᵒᵈ _ _ H _ theorem max'_eq_sup' : s.max' H = s.sup' H id := rfl theorem min'_eq_inf' : s.min' H = s.inf' H id := rfl /-- `{a}.max' _` is `a`. -/ @[simp] theorem max'_singleton (a : α) : ({a} : Finset α).max' (singleton_nonempty _) = a := by simp [max'] theorem min'_lt_max' {i j} (H1 : i ∈ s) (H2 : j ∈ s) (H3 : i ≠ j) : s.min' ⟨i, H1⟩ < s.max' ⟨i, H1⟩ := isGLB_lt_isLUB_of_ne (s.isLeast_min' _).isGLB (s.isGreatest_max' _).isLUB H1 H2 H3 /-- If there's more than 1 element, the min' is less than the max'. An alternate version of `min'_lt_max'` which is sometimes more convenient. -/ theorem min'_lt_max'_of_card (h₂ : 1 < card s) : s.min' (Finset.card_pos.1 <| by omega) < s.max' (Finset.card_pos.1 <| by omega) := by rcases one_lt_card.1 h₂ with ⟨a, ha, b, hb, hab⟩ exact s.min'_lt_max' ha hb hab theorem map_ofDual_min (s : Finset αᵒᵈ) : s.min.map ofDual = (s.image ofDual).max := by rw [max_eq_sup_withBot, sup_image] exact congr_fun Option.map_id _ theorem map_ofDual_max (s : Finset αᵒᵈ) : s.max.map ofDual = (s.image ofDual).min := by rw [min_eq_inf_withTop, inf_image] exact congr_fun Option.map_id _ theorem map_toDual_min (s : Finset α) : s.min.map toDual = (s.image toDual).max := by rw [max_eq_sup_withBot, sup_image] exact congr_fun Option.map_id _ theorem map_toDual_max (s : Finset α) : s.max.map toDual = (s.image toDual).min := by rw [min_eq_inf_withTop, inf_image] exact congr_fun Option.map_id _ -- Porting note: new proofs without `convert` for the next four theorems. theorem ofDual_min' {s : Finset αᵒᵈ} (hs : s.Nonempty) : ofDual (min' s hs) = max' (s.image ofDual) (hs.image _) := by rw [← WithBot.coe_eq_coe] simp only [min'_eq_inf', id_eq, ofDual_inf', Function.comp_apply, coe_sup', max'_eq_sup', sup_image] rfl theorem ofDual_max' {s : Finset αᵒᵈ} (hs : s.Nonempty) : ofDual (max' s hs) = min' (s.image ofDual) (hs.image _) := by rw [← WithTop.coe_eq_coe] simp only [max'_eq_sup', id_eq, ofDual_sup', Function.comp_apply, coe_inf', min'_eq_inf', inf_image] rfl theorem toDual_min' {s : Finset α} (hs : s.Nonempty) : toDual (min' s hs) = max' (s.image toDual) (hs.image _) := by rw [← WithBot.coe_eq_coe] simp only [min'_eq_inf', id_eq, toDual_inf', Function.comp_apply, coe_sup', max'_eq_sup', sup_image] rfl theorem toDual_max' {s : Finset α} (hs : s.Nonempty) : toDual (max' s hs) = min' (s.image toDual) (hs.image _) := by rw [← WithTop.coe_eq_coe] simp only [max'_eq_sup', id_eq, toDual_sup', Function.comp_apply, coe_inf', min'_eq_inf', inf_image] rfl theorem max'_subset {s t : Finset α} (H : s.Nonempty) (hst : s ⊆ t) : s.max' H ≤ t.max' (H.mono hst) := le_max' _ _ (hst (s.max'_mem H)) theorem min'_subset {s t : Finset α} (H : s.Nonempty) (hst : s ⊆ t) : t.min' (H.mono hst) ≤ s.min' H := min'_le _ _ (hst (s.min'_mem H)) theorem max'_insert (a : α) (s : Finset α) (H : s.Nonempty) : (insert a s).max' (s.insert_nonempty a) = max (s.max' H) a := (isGreatest_max' _ _).unique <| by rw [coe_insert, max_comm] exact (isGreatest_max' _ _).insert _ theorem min'_insert (a : α) (s : Finset α) (H : s.Nonempty) : (insert a s).min' (s.insert_nonempty a) = min (s.min' H) a := (isLeast_min' _ _).unique <| by rw [coe_insert, min_comm] exact (isLeast_min' _ _).insert _ theorem lt_max'_of_mem_erase_max' [DecidableEq α] {a : α} (ha : a ∈ s.erase (s.max' H)) : a < s.max' H := lt_of_le_of_ne (le_max' _ _ (mem_of_mem_erase ha)) <| ne_of_mem_of_not_mem ha <| not_mem_erase _ _ theorem min'_lt_of_mem_erase_min' [DecidableEq α] {a : α} (ha : a ∈ s.erase (s.min' H)) : s.min' H < a := @lt_max'_of_mem_erase_max' αᵒᵈ _ s H _ a ha /-- To rewrite from right to left, use `Monotone.map_finset_max'`. -/ @[simp] theorem max'_image [LinearOrder β] {f : α → β} (hf : Monotone f) (s : Finset α) (h : (s.image f).Nonempty) : (s.image f).max' h = f (s.max' h.of_image) := by simp only [max', sup'_image] exact .symm <| comp_sup'_eq_sup'_comp _ _ fun _ _ ↦ hf.map_max /-- A version of `Finset.max'_image` with LHS and RHS reversed. Also, this version assumes that `s` is nonempty, not its image. -/ lemma _root_.Monotone.map_finset_max' [LinearOrder β] {f : α → β} (hf : Monotone f) {s : Finset α} (h : s.Nonempty) : f (s.max' h) = (s.image f).max' (h.image f) := .symm <| max'_image hf .. /-- To rewrite from right to left, use `Monotone.map_finset_min'`. -/ @[simp] theorem min'_image [LinearOrder β] {f : α → β} (hf : Monotone f) (s : Finset α) (h : (s.image f).Nonempty) : (s.image f).min' h = f (s.min' h.of_image) := by simp only [min', inf'_image] exact .symm <| comp_inf'_eq_inf'_comp _ _ fun _ _ ↦ hf.map_min /-- A version of `Finset.min'_image` with LHS and RHS reversed. Also, this version assumes that `s` is nonempty, not its image. -/ lemma _root_.Monotone.map_finset_min' [LinearOrder β] {f : α → β} (hf : Monotone f) {s : Finset α} (h : s.Nonempty) : f (s.min' h) = (s.image f).min' (h.image f) := .symm <| min'_image hf .. theorem coe_max' {s : Finset α} (hs : s.Nonempty) : ↑(s.max' hs) = s.max := coe_sup' hs id theorem coe_min' {s : Finset α} (hs : s.Nonempty) : ↑(s.min' hs) = s.min := coe_inf' hs id theorem max_mem_image_coe {s : Finset α} (hs : s.Nonempty) : s.max ∈ (s.image (↑) : Finset (WithBot α)) := mem_image.2 ⟨max' s hs, max'_mem _ _, coe_max' hs⟩ theorem min_mem_image_coe {s : Finset α} (hs : s.Nonempty) : s.min ∈ (s.image (↑) : Finset (WithTop α)) := mem_image.2 ⟨min' s hs, min'_mem _ _, coe_min' hs⟩ theorem max_mem_insert_bot_image_coe (s : Finset α) : s.max ∈ (insert ⊥ (s.image (↑)) : Finset (WithBot α)) := mem_insert.2 <| s.eq_empty_or_nonempty.imp max_eq_bot.2 max_mem_image_coe theorem min_mem_insert_top_image_coe (s : Finset α) : s.min ∈ (insert ⊤ (s.image (↑)) : Finset (WithTop α)) := mem_insert.2 <| s.eq_empty_or_nonempty.imp min_eq_top.2 min_mem_image_coe theorem max'_erase_ne_self {s : Finset α} (s0 : (s.erase x).Nonempty) : (s.erase x).max' s0 ≠ x := ne_of_mem_erase (max'_mem _ s0) theorem min'_erase_ne_self {s : Finset α} (s0 : (s.erase x).Nonempty) : (s.erase x).min' s0 ≠ x := ne_of_mem_erase (min'_mem _ s0) theorem max_erase_ne_self {s : Finset α} : (s.erase x).max ≠ x := by by_cases s0 : (s.erase x).Nonempty · refine ne_of_eq_of_ne (coe_max' s0).symm ?_ exact WithBot.coe_eq_coe.not.mpr (max'_erase_ne_self _) · rw [not_nonempty_iff_eq_empty.mp s0, max_empty] exact WithBot.bot_ne_coe theorem min_erase_ne_self {s : Finset α} : (s.erase x).min ≠ x := by -- Porting note: old proof `convert @max_erase_ne_self αᵒᵈ _ _ _` convert @max_erase_ne_self αᵒᵈ _ (toDual x) (s.map toDual.toEmbedding) using 1 apply congr_arg -- Porting note: forces unfolding to see `Finset.min` is `Finset.max` congr! ext; simp only [mem_map_equiv]; exact Iff.rfl theorem exists_next_right {x : α} {s : Finset α} (h : ∃ y ∈ s, x < y) : ∃ y ∈ s, x < y ∧ ∀ z ∈ s, x < z → y ≤ z := have Hne : (s.filter (x < ·)).Nonempty := h.imp fun y hy => mem_filter.2 (by simpa) have aux := mem_filter.1 (min'_mem _ Hne) ⟨min' _ Hne, aux.1, by simp, fun z hzs hz => min'_le _ _ <| mem_filter.2 ⟨hzs, by simpa⟩⟩ theorem exists_next_left {x : α} {s : Finset α} (h : ∃ y ∈ s, y < x) : ∃ y ∈ s, y < x ∧ ∀ z ∈ s, z < x → z ≤ y := @exists_next_right αᵒᵈ _ x s h /-- If finsets `s` and `t` are interleaved, then `Finset.card s ≤ Finset.card t + 1`. -/ theorem card_le_of_interleaved {s t : Finset α} (h : ∀ᵉ (x ∈ s) (y ∈ s), x < y → (∀ z ∈ s, z ∉ Set.Ioo x y) → ∃ z ∈ t, x < z ∧ z < y) : s.card ≤ t.card + 1 := by replace h : ∀ᵉ (x ∈ s) (y ∈ s), x < y → ∃ z ∈ t, x < z ∧ z < y := by intro x hx y hy hxy rcases exists_next_right ⟨y, hy, hxy⟩ with ⟨a, has, hxa, ha⟩ rcases h x hx a has hxa fun z hzs hz => hz.2.not_le <| ha _ hzs hz.1 with ⟨b, hbt, hxb, hba⟩ exact ⟨b, hbt, hxb, hba.trans_le <| ha _ hy hxy⟩ set f : α → WithTop α := fun x => (t.filter fun y => x < y).min have f_mono : StrictMonoOn f s := by intro x hx y hy hxy rcases h x hx y hy hxy with ⟨a, hat, hxa, hay⟩ calc f x ≤ a := min_le (mem_filter.2 ⟨hat, by simpa⟩) _ < f y := (Finset.lt_inf_iff <| WithTop.coe_lt_top a).2 fun b hb => WithTop.coe_lt_coe.2 <| hay.trans (by simpa using (mem_filter.1 hb).2) calc s.card = (s.image f).card := (card_image_of_injOn f_mono.injOn).symm _ ≤ (insert ⊤ (t.image (↑)) : Finset (WithTop α)).card := card_mono <| image_subset_iff.2 fun x _ => insert_subset_insert _ (image_subset_image <| filter_subset _ _) (min_mem_insert_top_image_coe _) _ ≤ t.card + 1 := (card_insert_le _ _).trans (Nat.add_le_add_right card_image_le _) /-- If finsets `s` and `t` are interleaved, then `Finset.card s ≤ Finset.card (t \ s) + 1`. -/ theorem card_le_diff_of_interleaved {s t : Finset α} (h : ∀ᵉ (x ∈ s) (y ∈ s), x < y → (∀ z ∈ s, z ∉ Set.Ioo x y) → ∃ z ∈ t, x < z ∧ z < y) : s.card ≤ (t \ s).card + 1 := card_le_of_interleaved fun x hx y hy hxy hs => let ⟨z, hzt, hxz, hzy⟩ := h x hx y hy hxy hs ⟨z, mem_sdiff.2 ⟨hzt, fun hzs => hs z hzs ⟨hxz, hzy⟩⟩, hxz, hzy⟩ /-- Induction principle for `Finset`s in a linearly ordered type: a predicate is true on all `s : Finset α` provided that: * it is true on the empty `Finset`, * for every `s : Finset α` and an element `a` strictly greater than all elements of `s`, `p s` implies `p (insert a s)`. -/ @[elab_as_elim] theorem induction_on_max [DecidableEq α] {p : Finset α → Prop} (s : Finset α) (h0 : p ∅) (step : ∀ a s, (∀ x ∈ s, x < a) → p s → p (insert a s)) : p s := by induction' s using Finset.strongInductionOn with s ihs rcases s.eq_empty_or_nonempty with (rfl | hne) · exact h0 · have H : s.max' hne ∈ s := max'_mem s hne rw [← insert_erase H] exact step _ _ (fun x => s.lt_max'_of_mem_erase_max' hne) (ihs _ <| erase_ssubset H) /-- Induction principle for `Finset`s in a linearly ordered type: a predicate is true on all `s : Finset α` provided that: * it is true on the empty `Finset`, * for every `s : Finset α` and an element `a` strictly less than all elements of `s`, `p s` implies `p (insert a s)`. -/ @[elab_as_elim] theorem induction_on_min [DecidableEq α] {p : Finset α → Prop} (s : Finset α) (h0 : p ∅) (step : ∀ a s, (∀ x ∈ s, a < x) → p s → p (insert a s)) : p s := @induction_on_max αᵒᵈ _ _ _ s h0 step end MaxMin section MaxMinInductionValue variable [LinearOrder α] [LinearOrder β] /-- Induction principle for `Finset`s in any type from which a given function `f` maps to a linearly ordered type : a predicate is true on all `s : Finset α` provided that: * it is true on the empty `Finset`, * for every `s : Finset α` and an element `a` such that for elements of `s` denoted by `x` we have `f x ≤ f a`, `p s` implies `p (insert a s)`. -/ @[elab_as_elim] theorem induction_on_max_value [DecidableEq ι] (f : ι → α) {p : Finset ι → Prop} (s : Finset ι) (h0 : p ∅) (step : ∀ a s, a ∉ s → (∀ x ∈ s, f x ≤ f a) → p s → p (insert a s)) : p s := by induction' s using Finset.strongInductionOn with s ihs rcases (s.image f).eq_empty_or_nonempty with (hne | hne) · simp only [image_eq_empty] at hne simp only [hne, h0] · have H : (s.image f).max' hne ∈ s.image f := max'_mem (s.image f) hne simp only [mem_image, exists_prop] at H rcases H with ⟨a, has, hfa⟩ rw [← insert_erase has] refine step _ _ (not_mem_erase a s) (fun x hx => ?_) (ihs _ <| erase_ssubset has) rw [hfa] exact le_max' _ _ (mem_image_of_mem _ <| mem_of_mem_erase hx) /-- Induction principle for `Finset`s in any type from which a given function `f` maps to a linearly ordered type : a predicate is true on all `s : Finset α` provided that: * it is true on the empty `Finset`, * for every `s : Finset α` and an element `a` such that for elements of `s` denoted by `x` we have `f a ≤ f x`, `p s` implies `p (insert a s)`. -/ @[elab_as_elim] theorem induction_on_min_value [DecidableEq ι] (f : ι → α) {p : Finset ι → Prop} (s : Finset ι) (h0 : p ∅) (step : ∀ a s, a ∉ s → (∀ x ∈ s, f a ≤ f x) → p s → p (insert a s)) : p s := @induction_on_max_value αᵒᵈ ι _ _ _ _ s h0 step end MaxMinInductionValue section ExistsMaxMin variable [LinearOrder α] theorem exists_max_image (s : Finset β) (f : β → α) (h : s.Nonempty) : ∃ x ∈ s, ∀ x' ∈ s, f x' ≤ f x := by cases' max_of_nonempty (h.image f) with y hy rcases mem_image.mp (mem_of_max hy) with ⟨x, hx, rfl⟩ exact ⟨x, hx, fun x' hx' => le_max_of_eq (mem_image_of_mem f hx') hy⟩ theorem exists_min_image (s : Finset β) (f : β → α) (h : s.Nonempty) : ∃ x ∈ s, ∀ x' ∈ s, f x ≤ f x' := @exists_max_image αᵒᵈ β _ s f h end ExistsMaxMin theorem isGLB_iff_isLeast [LinearOrder α] (i : α) (s : Finset α) (hs : s.Nonempty) : IsGLB (s : Set α) i ↔ IsLeast (↑s) i := by refine ⟨fun his => ?_, IsLeast.isGLB⟩ suffices i = min' s hs by rw [this] exact isLeast_min' s hs rw [IsGLB, IsGreatest, mem_lowerBounds, mem_upperBounds] at his exact le_antisymm (his.1 (Finset.min' s hs) (Finset.min'_mem s hs)) (his.2 _ (Finset.min'_le s)) theorem isLUB_iff_isGreatest [LinearOrder α] (i : α) (s : Finset α) (hs : s.Nonempty) : IsLUB (s : Set α) i ↔ IsGreatest (↑s) i := @isGLB_iff_isLeast αᵒᵈ _ i s hs theorem isGLB_mem [LinearOrder α] {i : α} (s : Finset α) (his : IsGLB (s : Set α) i) (hs : s.Nonempty) : i ∈ s := by rw [← mem_coe] exact ((isGLB_iff_isLeast i s hs).mp his).1 theorem isLUB_mem [LinearOrder α] {i : α} (s : Finset α) (his : IsLUB (s : Set α) i) (hs : s.Nonempty) : i ∈ s := @isGLB_mem αᵒᵈ _ i s his hs end Finset namespace Multiset theorem map_finset_sup [DecidableEq α] [DecidableEq β] (s : Finset γ) (f : γ → Multiset β) (g : β → α) (hg : Function.Injective g) : map g (s.sup f) = s.sup (map g ∘ f) := Finset.comp_sup_eq_sup_comp _ (fun _ _ => map_union hg) (map_zero _) theorem count_finset_sup [DecidableEq β] (s : Finset α) (f : α → Multiset β) (b : β) : count b (s.sup f) = s.sup fun a => count b (f a) := by letI := Classical.decEq α refine s.induction ?_ ?_ · exact count_zero _ · intro i s _ ih rw [Finset.sup_insert, sup_eq_union, count_union, Finset.sup_insert, ih] rfl theorem mem_sup {α β} [DecidableEq β] {s : Finset α} {f : α → Multiset β} {x : β} : x ∈ s.sup f ↔ ∃ v ∈ s, x ∈ f v := by induction s using Finset.cons_induction <;> simp [*] end Multiset namespace Finset theorem mem_sup {α β} [DecidableEq β] {s : Finset α} {f : α → Finset β} {x : β} : x ∈ s.sup f ↔ ∃ v ∈ s, x ∈ f v := by change _ ↔ ∃ v ∈ s, x ∈ (f v).val rw [← Multiset.mem_sup, ← Multiset.mem_toFinset, sup_toFinset] simp_rw [val_toFinset] theorem sup_eq_biUnion {α β} [DecidableEq β] (s : Finset α) (t : α → Finset β) : s.sup t = s.biUnion t := by ext rw [mem_sup, mem_biUnion] @[simp] theorem sup_singleton'' [DecidableEq α] (s : Finset β) (f : β → α) : (s.sup fun b => {f b}) = s.image f := by ext a rw [mem_sup, mem_image] simp only [mem_singleton, eq_comm] @[simp] theorem sup_singleton' [DecidableEq α] (s : Finset α) : s.sup singleton = s := (s.sup_singleton'' _).trans image_id end Finset section Lattice variable {ι' : Sort*} [CompleteLattice α] /-- Supremum of `s i`, `i : ι`, is equal to the supremum over `t : Finset ι` of suprema `⨆ i ∈ t, s i`. This version assumes `ι` is a `Type*`. See `iSup_eq_iSup_finset'` for a version that works for `ι : Sort*`. -/ theorem iSup_eq_iSup_finset (s : ι → α) : ⨆ i, s i = ⨆ t : Finset ι, ⨆ i ∈ t, s i := by classical refine le_antisymm ?_ ?_ · exact iSup_le fun b => le_iSup_of_le {b} <| le_iSup_of_le b <| le_iSup_of_le (by simp) <| le_rfl · exact iSup_le fun t => iSup_le fun b => iSup_le fun _ => le_iSup _ _ /-- Supremum of `s i`, `i : ι`, is equal to the supremum over `t : Finset ι` of suprema `⨆ i ∈ t, s i`. This version works for `ι : Sort*`. See `iSup_eq_iSup_finset` for a version that assumes `ι : Type*` but has no `PLift`s. -/ theorem iSup_eq_iSup_finset' (s : ι' → α) : ⨆ i, s i = ⨆ t : Finset (PLift ι'), ⨆ i ∈ t, s (PLift.down i) := by rw [← iSup_eq_iSup_finset, ← Equiv.plift.surjective.iSup_comp]; rfl /-- Infimum of `s i`, `i : ι`, is equal to the infimum over `t : Finset ι` of infima `⨅ i ∈ t, s i`. This version assumes `ι` is a `Type*`. See `iInf_eq_iInf_finset'` for a version that works for `ι : Sort*`. -/ theorem iInf_eq_iInf_finset (s : ι → α) : ⨅ i, s i = ⨅ (t : Finset ι) (i ∈ t), s i := @iSup_eq_iSup_finset αᵒᵈ _ _ _ /-- Infimum of `s i`, `i : ι`, is equal to the infimum over `t : Finset ι` of infima `⨅ i ∈ t, s i`. This version works for `ι : Sort*`. See `iInf_eq_iInf_finset` for a version that assumes `ι : Type*` but has no `PLift`s. -/ theorem iInf_eq_iInf_finset' (s : ι' → α) : ⨅ i, s i = ⨅ t : Finset (PLift ι'), ⨅ i ∈ t, s (PLift.down i) := @iSup_eq_iSup_finset' αᵒᵈ _ _ _ end Lattice namespace Set variable {ι' : Sort*} /-- Union of an indexed family of sets `s : ι → Set α` is equal to the union of the unions of finite subfamilies. This version assumes `ι : Type*`. See also `iUnion_eq_iUnion_finset'` for a version that works for `ι : Sort*`. -/ theorem iUnion_eq_iUnion_finset (s : ι → Set α) : ⋃ i, s i = ⋃ t : Finset ι, ⋃ i ∈ t, s i := iSup_eq_iSup_finset s /-- Union of an indexed family of sets `s : ι → Set α` is equal to the union of the unions of finite subfamilies. This version works for `ι : Sort*`. See also `iUnion_eq_iUnion_finset` for a version that assumes `ι : Type*` but avoids `PLift`s in the right hand side. -/ theorem iUnion_eq_iUnion_finset' (s : ι' → Set α) : ⋃ i, s i = ⋃ t : Finset (PLift ι'), ⋃ i ∈ t, s (PLift.down i) := iSup_eq_iSup_finset' s /-- Intersection of an indexed family of sets `s : ι → Set α` is equal to the intersection of the intersections of finite subfamilies. This version assumes `ι : Type*`. See also `iInter_eq_iInter_finset'` for a version that works for `ι : Sort*`. -/ theorem iInter_eq_iInter_finset (s : ι → Set α) : ⋂ i, s i = ⋂ t : Finset ι, ⋂ i ∈ t, s i := iInf_eq_iInf_finset s /-- Intersection of an indexed family of sets `s : ι → Set α` is equal to the intersection of the intersections of finite subfamilies. This version works for `ι : Sort*`. See also `iInter_eq_iInter_finset` for a version that assumes `ι : Type*` but avoids `PLift`s in the right hand side. -/ theorem iInter_eq_iInter_finset' (s : ι' → Set α) : ⋂ i, s i = ⋂ t : Finset (PLift ι'), ⋂ i ∈ t, s (PLift.down i) := iInf_eq_iInf_finset' s end Set namespace Finset section minimal variable [DecidableEq α] {P : Finset α → Prop} {s : Finset α} theorem maximal_iff_forall_insert (hP : ∀ ⦃s t⦄, P t → s ⊆ t → P s) : Maximal P s ↔ P s ∧ ∀ x ∉ s, ¬ P (insert x s) := by simp only [Maximal, and_congr_right_iff] exact fun _ ↦ ⟨fun h x hxs hx ↦ hxs <| h hx (subset_insert _ _) (mem_insert_self x s), fun h t ht hst x hxt ↦ by_contra fun hxs ↦ h x hxs (hP ht (insert_subset hxt hst))⟩ theorem minimal_iff_forall_diff_singleton (hP : ∀ ⦃s t⦄, P t → t ⊆ s → P s) : Minimal P s ↔ P s ∧ ∀ x ∈ s, ¬ P (s.erase x) where mp h := ⟨h.prop, fun x hxs hx ↦ by simpa using h.le_of_le hx (erase_subset _ _) hxs⟩ mpr h := ⟨h.1, fun t ht hts x hxs ↦ by_contra fun hxt ↦ h.2 x hxs <| hP ht (subset_erase.2 ⟨hts, hxt⟩)⟩ end minimal /-! ### Interaction with big lattice/set operations -/ section Lattice theorem iSup_coe [SupSet β] (f : α → β) (s : Finset α) : ⨆ x ∈ (↑s : Set α), f x = ⨆ x ∈ s, f x := rfl theorem iInf_coe [InfSet β] (f : α → β) (s : Finset α) : ⨅ x ∈ (↑s : Set α), f x = ⨅ x ∈ s, f x := rfl variable [CompleteLattice β] theorem iSup_singleton (a : α) (s : α → β) : ⨆ x ∈ ({a} : Finset α), s x = s a := by simp theorem iInf_singleton (a : α) (s : α → β) : ⨅ x ∈ ({a} : Finset α), s x = s a := by simp theorem iSup_option_toFinset (o : Option α) (f : α → β) : ⨆ x ∈ o.toFinset, f x = ⨆ x ∈ o, f x := by simp theorem iInf_option_toFinset (o : Option α) (f : α → β) : ⨅ x ∈ o.toFinset, f x = ⨅ x ∈ o, f x := @iSup_option_toFinset _ βᵒᵈ _ _ _ variable [DecidableEq α] theorem iSup_union {f : α → β} {s t : Finset α} : ⨆ x ∈ s ∪ t, f x = (⨆ x ∈ s, f x) ⊔ ⨆ x ∈ t, f x := by simp [iSup_or, iSup_sup_eq] theorem iInf_union {f : α → β} {s t : Finset α} : ⨅ x ∈ s ∪ t, f x = (⨅ x ∈ s, f x) ⊓ ⨅ x ∈ t, f x := @iSup_union α βᵒᵈ _ _ _ _ _ theorem iSup_insert (a : α) (s : Finset α) (t : α → β) : ⨆ x ∈ insert a s, t x = t a ⊔ ⨆ x ∈ s, t x := by rw [insert_eq] simp only [iSup_union, Finset.iSup_singleton] theorem iInf_insert (a : α) (s : Finset α) (t : α → β) : ⨅ x ∈ insert a s, t x = t a ⊓ ⨅ x ∈ s, t x := @iSup_insert α βᵒᵈ _ _ _ _ _ theorem iSup_finset_image {f : γ → α} {g : α → β} {s : Finset γ} : ⨆ x ∈ s.image f, g x = ⨆ y ∈ s, g (f y) := by rw [← iSup_coe, coe_image, iSup_image, iSup_coe] theorem iInf_finset_image {f : γ → α} {g : α → β} {s : Finset γ} : ⨅ x ∈ s.image f, g x = ⨅ y ∈ s, g (f y) := by rw [← iInf_coe, coe_image, iInf_image, iInf_coe] theorem iSup_insert_update {x : α} {t : Finset α} (f : α → β) {s : β} (hx : x ∉ t) : ⨆ i ∈ insert x t, Function.update f x s i = s ⊔ ⨆ i ∈ t, f i := by simp only [Finset.iSup_insert, update_same] rcongr (i hi); apply update_noteq; rintro rfl; exact hx hi theorem iInf_insert_update {x : α} {t : Finset α} (f : α → β) {s : β} (hx : x ∉ t) : ⨅ i ∈ insert x t, update f x s i = s ⊓ ⨅ i ∈ t, f i := @iSup_insert_update α βᵒᵈ _ _ _ _ f _ hx theorem iSup_biUnion (s : Finset γ) (t : γ → Finset α) (f : α → β) : ⨆ y ∈ s.biUnion t, f y = ⨆ (x ∈ s) (y ∈ t x), f y := by simp [@iSup_comm _ α, iSup_and] theorem iInf_biUnion (s : Finset γ) (t : γ → Finset α) (f : α → β) : ⨅ y ∈ s.biUnion t, f y = ⨅ (x ∈ s) (y ∈ t x), f y := @iSup_biUnion _ βᵒᵈ _ _ _ _ _ _ end Lattice theorem set_biUnion_coe (s : Finset α) (t : α → Set β) : ⋃ x ∈ (↑s : Set α), t x = ⋃ x ∈ s, t x := rfl theorem set_biInter_coe (s : Finset α) (t : α → Set β) : ⋂ x ∈ (↑s : Set α), t x = ⋂ x ∈ s, t x := rfl theorem set_biUnion_singleton (a : α) (s : α → Set β) : ⋃ x ∈ ({a} : Finset α), s x = s a := iSup_singleton a s theorem set_biInter_singleton (a : α) (s : α → Set β) : ⋂ x ∈ ({a} : Finset α), s x = s a := iInf_singleton a s @[simp] theorem set_biUnion_preimage_singleton (f : α → β) (s : Finset β) : ⋃ y ∈ s, f ⁻¹' {y} = f ⁻¹' s := Set.biUnion_preimage_singleton f s theorem set_biUnion_option_toFinset (o : Option α) (f : α → Set β) : ⋃ x ∈ o.toFinset, f x = ⋃ x ∈ o, f x := iSup_option_toFinset o f theorem set_biInter_option_toFinset (o : Option α) (f : α → Set β) : ⋂ x ∈ o.toFinset, f x = ⋂ x ∈ o, f x := iInf_option_toFinset o f theorem subset_set_biUnion_of_mem {s : Finset α} {f : α → Set β} {x : α} (h : x ∈ s) : f x ⊆ ⋃ y ∈ s, f y := show f x ≤ ⨆ y ∈ s, f y from le_iSup_of_le x <| by simp only [h, iSup_pos, le_refl] variable [DecidableEq α] theorem set_biUnion_union (s t : Finset α) (u : α → Set β) : ⋃ x ∈ s ∪ t, u x = (⋃ x ∈ s, u x) ∪ ⋃ x ∈ t, u x := iSup_union theorem set_biInter_inter (s t : Finset α) (u : α → Set β) : ⋂ x ∈ s ∪ t, u x = (⋂ x ∈ s, u x) ∩ ⋂ x ∈ t, u x := iInf_union theorem set_biUnion_insert (a : α) (s : Finset α) (t : α → Set β) : ⋃ x ∈ insert a s, t x = t a ∪ ⋃ x ∈ s, t x := iSup_insert a s t theorem set_biInter_insert (a : α) (s : Finset α) (t : α → Set β) : ⋂ x ∈ insert a s, t x = t a ∩ ⋂ x ∈ s, t x := iInf_insert a s t theorem set_biUnion_finset_image {f : γ → α} {g : α → Set β} {s : Finset γ} : ⋃ x ∈ s.image f, g x = ⋃ y ∈ s, g (f y) := iSup_finset_image theorem set_biInter_finset_image {f : γ → α} {g : α → Set β} {s : Finset γ} : ⋂ x ∈ s.image f, g x = ⋂ y ∈ s, g (f y) := iInf_finset_image theorem set_biUnion_insert_update {x : α} {t : Finset α} (f : α → Set β) {s : Set β} (hx : x ∉ t) : ⋃ i ∈ insert x t, @update _ _ _ f x s i = s ∪ ⋃ i ∈ t, f i := iSup_insert_update f hx theorem set_biInter_insert_update {x : α} {t : Finset α} (f : α → Set β) {s : Set β} (hx : x ∉ t) : ⋂ i ∈ insert x t, @update _ _ _ f x s i = s ∩ ⋂ i ∈ t, f i := iInf_insert_update f hx theorem set_biUnion_biUnion (s : Finset γ) (t : γ → Finset α) (f : α → Set β) : ⋃ y ∈ s.biUnion t, f y = ⋃ (x ∈ s) (y ∈ t x), f y := iSup_biUnion s t f theorem set_biInter_biUnion (s : Finset γ) (t : γ → Finset α) (f : α → Set β) : ⋂ y ∈ s.biUnion t, f y = ⋂ (x ∈ s) (y ∈ t x), f y := iInf_biUnion s t f end Finset
Data\Finset\MulAntidiagonal.lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Yaël Dillies -/ import Mathlib.Data.Set.Pointwise.Basic import Mathlib.Data.Set.MulAntidiagonal /-! # Multiplication antidiagonal as a `Finset`. We construct the `Finset` of all pairs of an element in `s` and an element in `t` that multiply to `a`, given that `s` and `t` are well-ordered. -/ namespace Set open Pointwise variable {α : Type*} {s t : Set α} @[to_additive] theorem IsPWO.mul [OrderedCancelCommMonoid α] (hs : s.IsPWO) (ht : t.IsPWO) : IsPWO (s * t) := by rw [← image_mul_prod] exact (hs.prod ht).image_of_monotone (monotone_fst.mul' monotone_snd) variable [LinearOrderedCancelCommMonoid α] @[to_additive] theorem IsWF.mul (hs : s.IsWF) (ht : t.IsWF) : IsWF (s * t) := (hs.isPWO.mul ht.isPWO).isWF @[to_additive] theorem IsWF.min_mul (hs : s.IsWF) (ht : t.IsWF) (hsn : s.Nonempty) (htn : t.Nonempty) : (hs.mul ht).min (hsn.mul htn) = hs.min hsn * ht.min htn := by refine le_antisymm (IsWF.min_le _ _ (mem_mul.2 ⟨_, hs.min_mem _, _, ht.min_mem _, rfl⟩)) ?_ rw [IsWF.le_min_iff] rintro _ ⟨x, hx, y, hy, rfl⟩ exact mul_le_mul' (hs.min_le _ hx) (ht.min_le _ hy) end Set namespace Finset open Pointwise variable {α : Type*} variable [OrderedCancelCommMonoid α] {s t : Set α} (hs : s.IsPWO) (ht : t.IsPWO) (a : α) /-- `Finset.mulAntidiagonal hs ht a` is the set of all pairs of an element in `s` and an element in `t` that multiply to `a`, but its construction requires proofs that `s` and `t` are well-ordered. -/ @[to_additive "`Finset.addAntidiagonal hs ht a` is the set of all pairs of an element in `s` and an element in `t` that add to `a`, but its construction requires proofs that `s` and `t` are well-ordered."] noncomputable def mulAntidiagonal : Finset (α × α) := (Set.MulAntidiagonal.finite_of_isPWO hs ht a).toFinset variable {hs ht a} {u : Set α} {hu : u.IsPWO} {x : α × α} @[to_additive (attr := simp)] theorem mem_mulAntidiagonal : x ∈ mulAntidiagonal hs ht a ↔ x.1 ∈ s ∧ x.2 ∈ t ∧ x.1 * x.2 = a := by simp only [mulAntidiagonal, Set.Finite.mem_toFinset, Set.mem_mulAntidiagonal] @[to_additive] theorem mulAntidiagonal_mono_left (h : u ⊆ s) : mulAntidiagonal hu ht a ⊆ mulAntidiagonal hs ht a := Set.Finite.toFinset_mono <| Set.mulAntidiagonal_mono_left h @[to_additive] theorem mulAntidiagonal_mono_right (h : u ⊆ t) : mulAntidiagonal hs hu a ⊆ mulAntidiagonal hs ht a := Set.Finite.toFinset_mono <| Set.mulAntidiagonal_mono_right h -- Porting note: removed `(attr := simp)`. simp can prove this. @[to_additive] theorem swap_mem_mulAntidiagonal : x.swap ∈ Finset.mulAntidiagonal hs ht a ↔ x ∈ Finset.mulAntidiagonal ht hs a := by simp only [mem_mulAntidiagonal, Prod.fst_swap, Prod.snd_swap, Set.swap_mem_mulAntidiagonal_aux, Set.mem_mulAntidiagonal] @[to_additive] theorem support_mulAntidiagonal_subset_mul : { a | (mulAntidiagonal hs ht a).Nonempty } ⊆ s * t := fun a ⟨b, hb⟩ => by rw [mem_mulAntidiagonal] at hb exact ⟨b.1, hb.1, b.2, hb.2⟩ @[to_additive] theorem isPWO_support_mulAntidiagonal : { a | (mulAntidiagonal hs ht a).Nonempty }.IsPWO := (hs.mul ht).mono support_mulAntidiagonal_subset_mul @[to_additive] theorem mulAntidiagonal_min_mul_min {α} [LinearOrderedCancelCommMonoid α] {s t : Set α} (hs : s.IsWF) (ht : t.IsWF) (hns : s.Nonempty) (hnt : t.Nonempty) : mulAntidiagonal hs.isPWO ht.isPWO (hs.min hns * ht.min hnt) = {(hs.min hns, ht.min hnt)} := by ext ⟨a, b⟩ simp only [mem_mulAntidiagonal, mem_singleton, Prod.ext_iff] constructor · rintro ⟨has, hat, hst⟩ obtain rfl := (hs.min_le hns has).eq_of_not_lt fun hlt => (mul_lt_mul_of_lt_of_le hlt <| ht.min_le hnt hat).ne' hst exact ⟨rfl, mul_left_cancel hst⟩ · rintro ⟨rfl, rfl⟩ exact ⟨hs.min_mem _, ht.min_mem _, rfl⟩ end Finset
Data\Finset\NAry.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.Data.Finset.Prod import Mathlib.Data.Set.Finite /-! # N-ary images of finsets This file defines `Finset.image₂`, the binary image of finsets. This is the finset version of `Set.image2`. This is mostly useful to define pointwise operations. ## Notes This file is very similar to `Data.Set.NAry`, `Order.Filter.NAry` and `Data.Option.NAry`. Please keep them in sync. We do not define `Finset.image₃` as its only purpose would be to prove properties of `Finset.image₂` and `Set.image2` already fulfills this task. -/ open Function Set variable {α α' β β' γ γ' δ δ' ε ε' ζ ζ' ν : Type*} namespace Finset variable [DecidableEq α'] [DecidableEq β'] [DecidableEq γ] [DecidableEq γ'] [DecidableEq δ'] [DecidableEq ε] [DecidableEq ε'] {f f' : α → β → γ} {g g' : α → β → γ → δ} {s s' : Finset α} {t t' : Finset β} {u u' : Finset γ} {a a' : α} {b b' : β} {c : γ} /-- The image of a binary function `f : α → β → γ` as a function `Finset α → Finset β → Finset γ`. Mathematically this should be thought of as the image of the corresponding function `α × β → γ`. -/ def image₂ (f : α → β → γ) (s : Finset α) (t : Finset β) : Finset γ := (s ×ˢ t).image <| uncurry f @[simp] theorem mem_image₂ : c ∈ image₂ f s t ↔ ∃ a ∈ s, ∃ b ∈ t, f a b = c := by simp [image₂, and_assoc] @[simp, norm_cast] theorem coe_image₂ (f : α → β → γ) (s : Finset α) (t : Finset β) : (image₂ f s t : Set γ) = Set.image2 f s t := Set.ext fun _ => mem_image₂ theorem card_image₂_le (f : α → β → γ) (s : Finset α) (t : Finset β) : (image₂ f s t).card ≤ s.card * t.card := card_image_le.trans_eq <| card_product _ _ theorem card_image₂_iff : (image₂ f s t).card = s.card * t.card ↔ (s ×ˢ t : Set (α × β)).InjOn fun x => f x.1 x.2 := by rw [← card_product, ← coe_product] exact card_image_iff theorem card_image₂ (hf : Injective2 f) (s : Finset α) (t : Finset β) : (image₂ f s t).card = s.card * t.card := (card_image_of_injective _ hf.uncurry).trans <| card_product _ _ theorem mem_image₂_of_mem (ha : a ∈ s) (hb : b ∈ t) : f a b ∈ image₂ f s t := mem_image₂.2 ⟨a, ha, b, hb, rfl⟩ theorem mem_image₂_iff (hf : Injective2 f) : f a b ∈ image₂ f s t ↔ a ∈ s ∧ b ∈ t := by rw [← mem_coe, coe_image₂, mem_image2_iff hf, mem_coe, mem_coe] theorem image₂_subset (hs : s ⊆ s') (ht : t ⊆ t') : image₂ f s t ⊆ image₂ f s' t' := by rw [← coe_subset, coe_image₂, coe_image₂] exact image2_subset hs ht theorem image₂_subset_left (ht : t ⊆ t') : image₂ f s t ⊆ image₂ f s t' := image₂_subset Subset.rfl ht theorem image₂_subset_right (hs : s ⊆ s') : image₂ f s t ⊆ image₂ f s' t := image₂_subset hs Subset.rfl theorem image_subset_image₂_left (hb : b ∈ t) : s.image (fun a => f a b) ⊆ image₂ f s t := image_subset_iff.2 fun _ ha => mem_image₂_of_mem ha hb theorem image_subset_image₂_right (ha : a ∈ s) : t.image (fun b => f a b) ⊆ image₂ f s t := image_subset_iff.2 fun _ => mem_image₂_of_mem ha theorem forall_image₂_iff {p : γ → Prop} : (∀ z ∈ image₂ f s t, p z) ↔ ∀ x ∈ s, ∀ y ∈ t, p (f x y) := by simp_rw [← mem_coe, coe_image₂, forall_image2_iff] @[simp] theorem image₂_subset_iff : image₂ f s t ⊆ u ↔ ∀ x ∈ s, ∀ y ∈ t, f x y ∈ u := forall_image₂_iff theorem image₂_subset_iff_left : image₂ f s t ⊆ u ↔ ∀ a ∈ s, (t.image fun b => f a b) ⊆ u := by simp_rw [image₂_subset_iff, image_subset_iff] theorem image₂_subset_iff_right : image₂ f s t ⊆ u ↔ ∀ b ∈ t, (s.image fun a => f a b) ⊆ u := by simp_rw [image₂_subset_iff, image_subset_iff, @forall₂_swap α] @[simp, aesop safe apply (rule_sets := [finsetNonempty])] theorem image₂_nonempty_iff : (image₂ f s t).Nonempty ↔ s.Nonempty ∧ t.Nonempty := by rw [← coe_nonempty, coe_image₂] exact image2_nonempty_iff theorem Nonempty.image₂ (hs : s.Nonempty) (ht : t.Nonempty) : (image₂ f s t).Nonempty := image₂_nonempty_iff.2 ⟨hs, ht⟩ theorem Nonempty.of_image₂_left (h : (s.image₂ f t).Nonempty) : s.Nonempty := (image₂_nonempty_iff.1 h).1 theorem Nonempty.of_image₂_right (h : (s.image₂ f t).Nonempty) : t.Nonempty := (image₂_nonempty_iff.1 h).2 @[simp] theorem image₂_empty_left : image₂ f ∅ t = ∅ := coe_injective <| by simp @[simp] theorem image₂_empty_right : image₂ f s ∅ = ∅ := coe_injective <| by simp @[simp] theorem image₂_eq_empty_iff : image₂ f s t = ∅ ↔ s = ∅ ∨ t = ∅ := by simp_rw [← not_nonempty_iff_eq_empty, image₂_nonempty_iff, not_and_or] @[simp] theorem image₂_singleton_left : image₂ f {a} t = t.image fun b => f a b := ext fun x => by simp @[simp] theorem image₂_singleton_right : image₂ f s {b} = s.image fun a => f a b := ext fun x => by simp theorem image₂_singleton_left' : image₂ f {a} t = t.image (f a) := image₂_singleton_left theorem image₂_singleton : image₂ f {a} {b} = {f a b} := by simp theorem image₂_union_left [DecidableEq α] : image₂ f (s ∪ s') t = image₂ f s t ∪ image₂ f s' t := coe_injective <| by push_cast exact image2_union_left theorem image₂_union_right [DecidableEq β] : image₂ f s (t ∪ t') = image₂ f s t ∪ image₂ f s t' := coe_injective <| by push_cast exact image2_union_right @[simp] theorem image₂_insert_left [DecidableEq α] : image₂ f (insert a s) t = (t.image fun b => f a b) ∪ image₂ f s t := coe_injective <| by push_cast exact image2_insert_left @[simp] theorem image₂_insert_right [DecidableEq β] : image₂ f s (insert b t) = (s.image fun a => f a b) ∪ image₂ f s t := coe_injective <| by push_cast exact image2_insert_right theorem image₂_inter_left [DecidableEq α] (hf : Injective2 f) : image₂ f (s ∩ s') t = image₂ f s t ∩ image₂ f s' t := coe_injective <| by push_cast exact image2_inter_left hf theorem image₂_inter_right [DecidableEq β] (hf : Injective2 f) : image₂ f s (t ∩ t') = image₂ f s t ∩ image₂ f s t' := coe_injective <| by push_cast exact image2_inter_right hf theorem image₂_inter_subset_left [DecidableEq α] : image₂ f (s ∩ s') t ⊆ image₂ f s t ∩ image₂ f s' t := coe_subset.1 <| by push_cast exact image2_inter_subset_left theorem image₂_inter_subset_right [DecidableEq β] : image₂ f s (t ∩ t') ⊆ image₂ f s t ∩ image₂ f s t' := coe_subset.1 <| by push_cast exact image2_inter_subset_right theorem image₂_congr (h : ∀ a ∈ s, ∀ b ∈ t, f a b = f' a b) : image₂ f s t = image₂ f' s t := coe_injective <| by push_cast exact image2_congr h /-- A common special case of `image₂_congr` -/ theorem image₂_congr' (h : ∀ a b, f a b = f' a b) : image₂ f s t = image₂ f' s t := image₂_congr fun a _ b _ => h a b variable (s t) theorem card_image₂_singleton_left (hf : Injective (f a)) : (image₂ f {a} t).card = t.card := by rw [image₂_singleton_left, card_image_of_injective _ hf] theorem card_image₂_singleton_right (hf : Injective fun a => f a b) : (image₂ f s {b}).card = s.card := by rw [image₂_singleton_right, card_image_of_injective _ hf] theorem image₂_singleton_inter [DecidableEq β] (t₁ t₂ : Finset β) (hf : Injective (f a)) : image₂ f {a} (t₁ ∩ t₂) = image₂ f {a} t₁ ∩ image₂ f {a} t₂ := by simp_rw [image₂_singleton_left, image_inter _ _ hf] theorem image₂_inter_singleton [DecidableEq α] (s₁ s₂ : Finset α) (hf : Injective fun a => f a b) : image₂ f (s₁ ∩ s₂) {b} = image₂ f s₁ {b} ∩ image₂ f s₂ {b} := by simp_rw [image₂_singleton_right, image_inter _ _ hf] theorem card_le_card_image₂_left {s : Finset α} (hs : s.Nonempty) (hf : ∀ a, Injective (f a)) : t.card ≤ (image₂ f s t).card := by obtain ⟨a, ha⟩ := hs rw [← card_image₂_singleton_left _ (hf a)] exact card_le_card (image₂_subset_right <| singleton_subset_iff.2 ha) theorem card_le_card_image₂_right {t : Finset β} (ht : t.Nonempty) (hf : ∀ b, Injective fun a => f a b) : s.card ≤ (image₂ f s t).card := by obtain ⟨b, hb⟩ := ht rw [← card_image₂_singleton_right _ (hf b)] exact card_le_card (image₂_subset_left <| singleton_subset_iff.2 hb) variable {s t} theorem biUnion_image_left : (s.biUnion fun a => t.image <| f a) = image₂ f s t := coe_injective <| by push_cast exact Set.iUnion_image_left _ theorem biUnion_image_right : (t.biUnion fun b => s.image fun a => f a b) = image₂ f s t := coe_injective <| by push_cast exact Set.iUnion_image_right _ /-! ### Algebraic replacement rules A collection of lemmas to transfer associativity, commutativity, distributivity, ... of operations to the associativity, commutativity, distributivity, ... of `Finset.image₂` of those operations. The proof pattern is `image₂_lemma operation_lemma`. For example, `image₂_comm mul_comm` proves that `image₂ (*) f g = image₂ (*) g f` in a `CommSemigroup`. -/ section variable [DecidableEq δ] theorem image_image₂ (f : α → β → γ) (g : γ → δ) : (image₂ f s t).image g = image₂ (fun a b => g (f a b)) s t := coe_injective <| by push_cast exact image_image2 _ _ theorem image₂_image_left (f : γ → β → δ) (g : α → γ) : image₂ f (s.image g) t = image₂ (fun a b => f (g a) b) s t := coe_injective <| by push_cast exact image2_image_left _ _ theorem image₂_image_right (f : α → γ → δ) (g : β → γ) : image₂ f s (t.image g) = image₂ (fun a b => f a (g b)) s t := coe_injective <| by push_cast exact image2_image_right _ _ @[simp] theorem image₂_mk_eq_product [DecidableEq α] [DecidableEq β] (s : Finset α) (t : Finset β) : image₂ Prod.mk s t = s ×ˢ t := by ext; simp [Prod.ext_iff] @[simp] theorem image₂_curry (f : α × β → γ) (s : Finset α) (t : Finset β) : image₂ (curry f) s t = (s ×ˢ t).image f := rfl @[simp] theorem image_uncurry_product (f : α → β → γ) (s : Finset α) (t : Finset β) : (s ×ˢ t).image (uncurry f) = image₂ f s t := rfl theorem image₂_swap (f : α → β → γ) (s : Finset α) (t : Finset β) : image₂ f s t = image₂ (fun a b => f b a) t s := coe_injective <| by push_cast exact image2_swap _ _ _ @[simp] theorem image₂_left [DecidableEq α] (h : t.Nonempty) : image₂ (fun x _ => x) s t = s := coe_injective <| by push_cast exact image2_left h @[simp] theorem image₂_right [DecidableEq β] (h : s.Nonempty) : image₂ (fun _ y => y) s t = t := coe_injective <| by push_cast exact image2_right h theorem image₂_assoc {γ : Type*} {u : Finset γ} {f : δ → γ → ε} {g : α → β → δ} {f' : α → ε' → ε} {g' : β → γ → ε'} (h_assoc : ∀ a b c, f (g a b) c = f' a (g' b c)) : image₂ f (image₂ g s t) u = image₂ f' s (image₂ g' t u) := coe_injective <| by push_cast exact image2_assoc h_assoc theorem image₂_comm {g : β → α → γ} (h_comm : ∀ a b, f a b = g b a) : image₂ f s t = image₂ g t s := (image₂_swap _ _ _).trans <| by simp_rw [h_comm] theorem image₂_left_comm {γ : Type*} {u : Finset γ} {f : α → δ → ε} {g : β → γ → δ} {f' : α → γ → δ'} {g' : β → δ' → ε} (h_left_comm : ∀ a b c, f a (g b c) = g' b (f' a c)) : image₂ f s (image₂ g t u) = image₂ g' t (image₂ f' s u) := coe_injective <| by push_cast exact image2_left_comm h_left_comm theorem image₂_right_comm {γ : Type*} {u : Finset γ} {f : δ → γ → ε} {g : α → β → δ} {f' : α → γ → δ'} {g' : δ' → β → ε} (h_right_comm : ∀ a b c, f (g a b) c = g' (f' a c) b) : image₂ f (image₂ g s t) u = image₂ g' (image₂ f' s u) t := coe_injective <| by push_cast exact image2_right_comm h_right_comm theorem image₂_image₂_image₂_comm {γ δ : Type*} {u : Finset γ} {v : Finset δ} [DecidableEq ζ] [DecidableEq ζ'] [DecidableEq ν] {f : ε → ζ → ν} {g : α → β → ε} {h : γ → δ → ζ} {f' : ε' → ζ' → ν} {g' : α → γ → ε'} {h' : β → δ → ζ'} (h_comm : ∀ a b c d, f (g a b) (h c d) = f' (g' a c) (h' b d)) : image₂ f (image₂ g s t) (image₂ h u v) = image₂ f' (image₂ g' s u) (image₂ h' t v) := coe_injective <| by push_cast exact image2_image2_image2_comm h_comm theorem image_image₂_distrib {g : γ → δ} {f' : α' → β' → δ} {g₁ : α → α'} {g₂ : β → β'} (h_distrib : ∀ a b, g (f a b) = f' (g₁ a) (g₂ b)) : (image₂ f s t).image g = image₂ f' (s.image g₁) (t.image g₂) := coe_injective <| by push_cast exact image_image2_distrib h_distrib /-- Symmetric statement to `Finset.image₂_image_left_comm`. -/ theorem image_image₂_distrib_left {g : γ → δ} {f' : α' → β → δ} {g' : α → α'} (h_distrib : ∀ a b, g (f a b) = f' (g' a) b) : (image₂ f s t).image g = image₂ f' (s.image g') t := coe_injective <| by push_cast exact image_image2_distrib_left h_distrib /-- Symmetric statement to `Finset.image_image₂_right_comm`. -/ theorem image_image₂_distrib_right {g : γ → δ} {f' : α → β' → δ} {g' : β → β'} (h_distrib : ∀ a b, g (f a b) = f' a (g' b)) : (image₂ f s t).image g = image₂ f' s (t.image g') := coe_injective <| by push_cast exact image_image2_distrib_right h_distrib /-- Symmetric statement to `Finset.image_image₂_distrib_left`. -/ theorem image₂_image_left_comm {f : α' → β → γ} {g : α → α'} {f' : α → β → δ} {g' : δ → γ} (h_left_comm : ∀ a b, f (g a) b = g' (f' a b)) : image₂ f (s.image g) t = (image₂ f' s t).image g' := (image_image₂_distrib_left fun a b => (h_left_comm a b).symm).symm /-- Symmetric statement to `Finset.image_image₂_distrib_right`. -/ theorem image_image₂_right_comm {f : α → β' → γ} {g : β → β'} {f' : α → β → δ} {g' : δ → γ} (h_right_comm : ∀ a b, f a (g b) = g' (f' a b)) : image₂ f s (t.image g) = (image₂ f' s t).image g' := (image_image₂_distrib_right fun a b => (h_right_comm a b).symm).symm /-- The other direction does not hold because of the `s`-`s` cross terms on the RHS. -/ theorem image₂_distrib_subset_left {γ : Type*} {u : Finset γ} {f : α → δ → ε} {g : β → γ → δ} {f₁ : α → β → β'} {f₂ : α → γ → γ'} {g' : β' → γ' → ε} (h_distrib : ∀ a b c, f a (g b c) = g' (f₁ a b) (f₂ a c)) : image₂ f s (image₂ g t u) ⊆ image₂ g' (image₂ f₁ s t) (image₂ f₂ s u) := coe_subset.1 <| by push_cast exact Set.image2_distrib_subset_left h_distrib /-- The other direction does not hold because of the `u`-`u` cross terms on the RHS. -/ theorem image₂_distrib_subset_right {γ : Type*} {u : Finset γ} {f : δ → γ → ε} {g : α → β → δ} {f₁ : α → γ → α'} {f₂ : β → γ → β'} {g' : α' → β' → ε} (h_distrib : ∀ a b c, f (g a b) c = g' (f₁ a c) (f₂ b c)) : image₂ f (image₂ g s t) u ⊆ image₂ g' (image₂ f₁ s u) (image₂ f₂ t u) := coe_subset.1 <| by push_cast exact Set.image2_distrib_subset_right h_distrib theorem image_image₂_antidistrib {g : γ → δ} {f' : β' → α' → δ} {g₁ : β → β'} {g₂ : α → α'} (h_antidistrib : ∀ a b, g (f a b) = f' (g₁ b) (g₂ a)) : (image₂ f s t).image g = image₂ f' (t.image g₁) (s.image g₂) := by rw [image₂_swap f] exact image_image₂_distrib fun _ _ => h_antidistrib _ _ /-- Symmetric statement to `Finset.image₂_image_left_anticomm`. -/ theorem image_image₂_antidistrib_left {g : γ → δ} {f' : β' → α → δ} {g' : β → β'} (h_antidistrib : ∀ a b, g (f a b) = f' (g' b) a) : (image₂ f s t).image g = image₂ f' (t.image g') s := coe_injective <| by push_cast exact image_image2_antidistrib_left h_antidistrib /-- Symmetric statement to `Finset.image_image₂_right_anticomm`. -/ theorem image_image₂_antidistrib_right {g : γ → δ} {f' : β → α' → δ} {g' : α → α'} (h_antidistrib : ∀ a b, g (f a b) = f' b (g' a)) : (image₂ f s t).image g = image₂ f' t (s.image g') := coe_injective <| by push_cast exact image_image2_antidistrib_right h_antidistrib /-- Symmetric statement to `Finset.image_image₂_antidistrib_left`. -/ theorem image₂_image_left_anticomm {f : α' → β → γ} {g : α → α'} {f' : β → α → δ} {g' : δ → γ} (h_left_anticomm : ∀ a b, f (g a) b = g' (f' b a)) : image₂ f (s.image g) t = (image₂ f' t s).image g' := (image_image₂_antidistrib_left fun a b => (h_left_anticomm b a).symm).symm /-- Symmetric statement to `Finset.image_image₂_antidistrib_right`. -/ theorem image_image₂_right_anticomm {f : α → β' → γ} {g : β → β'} {f' : β → α → δ} {g' : δ → γ} (h_right_anticomm : ∀ a b, f a (g b) = g' (f' b a)) : image₂ f s (t.image g) = (image₂ f' t s).image g' := (image_image₂_antidistrib_right fun a b => (h_right_anticomm b a).symm).symm /-- If `a` is a left identity for `f : α → β → β`, then `{a}` is a left identity for `Finset.image₂ f`. -/ theorem image₂_left_identity {f : α → γ → γ} {a : α} (h : ∀ b, f a b = b) (t : Finset γ) : image₂ f {a} t = t := coe_injective <| by rw [coe_image₂, coe_singleton, Set.image2_left_identity h] /-- If `b` is a right identity for `f : α → β → α`, then `{b}` is a right identity for `Finset.image₂ f`. -/ theorem image₂_right_identity {f : γ → β → γ} {b : β} (h : ∀ a, f a b = a) (s : Finset γ) : image₂ f s {b} = s := by rw [image₂_singleton_right, funext h, image_id'] /-- If each partial application of `f` is injective, and images of `s` under those partial applications are disjoint (but not necessarily distinct!), then the size of `t` divides the size of `Finset.image₂ f s t`. -/ theorem card_dvd_card_image₂_right (hf : ∀ a ∈ s, Injective (f a)) (hs : ((fun a => t.image <| f a) '' s).PairwiseDisjoint id) : t.card ∣ (image₂ f s t).card := by classical induction' s using Finset.induction with a s _ ih · simp specialize ih (forall_of_forall_insert hf) (hs.subset <| Set.image_subset _ <| coe_subset.2 <| subset_insert _ _) rw [image₂_insert_left] by_cases h : Disjoint (image (f a) t) (image₂ f s t) · rw [card_union_of_disjoint h] exact Nat.dvd_add (card_image_of_injective _ <| hf _ <| mem_insert_self _ _).symm.dvd ih simp_rw [← biUnion_image_left, disjoint_biUnion_right, not_forall] at h obtain ⟨b, hb, h⟩ := h rwa [union_eq_right.2] exact (hs.eq (Set.mem_image_of_mem _ <| mem_insert_self _ _) (Set.mem_image_of_mem _ <| mem_insert_of_mem hb) h).trans_subset (image_subset_image₂_right hb) /-- If each partial application of `f` is injective, and images of `t` under those partial applications are disjoint (but not necessarily distinct!), then the size of `s` divides the size of `Finset.image₂ f s t`. -/ theorem card_dvd_card_image₂_left (hf : ∀ b ∈ t, Injective fun a => f a b) (ht : ((fun b => s.image fun a => f a b) '' t).PairwiseDisjoint id) : s.card ∣ (image₂ f s t).card := by rw [← image₂_swap]; exact card_dvd_card_image₂_right hf ht /-- If a `Finset` is a subset of the image of two `Set`s under a binary operation, then it is a subset of the `Finset.image₂` of two `Finset` subsets of these `Set`s. -/ theorem subset_image₂ {s : Set α} {t : Set β} (hu : ↑u ⊆ image2 f s t) : ∃ (s' : Finset α) (t' : Finset β), ↑s' ⊆ s ∧ ↑t' ⊆ t ∧ u ⊆ image₂ f s' t' := by rw [← Set.image_prod, subset_image_iff] at hu rcases hu with ⟨u, hu, rfl⟩ classical use u.image Prod.fst, u.image Prod.snd simp only [coe_image, Set.image_subset_iff, image₂_image_left, image₂_image_right, image_subset_iff] exact ⟨fun _ h ↦ (hu h).1, fun _ h ↦ (hu h).2, fun x hx ↦ mem_image₂_of_mem hx hx⟩ end section UnionInter variable [DecidableEq α] [DecidableEq β] theorem image₂_inter_union_subset_union : image₂ f (s ∩ s') (t ∪ t') ⊆ image₂ f s t ∪ image₂ f s' t' := coe_subset.1 <| by push_cast exact Set.image2_inter_union_subset_union theorem image₂_union_inter_subset_union : image₂ f (s ∪ s') (t ∩ t') ⊆ image₂ f s t ∪ image₂ f s' t' := coe_subset.1 <| by push_cast exact Set.image2_union_inter_subset_union theorem image₂_inter_union_subset {f : α → α → β} {s t : Finset α} (hf : ∀ a b, f a b = f b a) : image₂ f (s ∩ t) (s ∪ t) ⊆ image₂ f s t := coe_subset.1 <| by push_cast exact image2_inter_union_subset hf theorem image₂_union_inter_subset {f : α → α → β} {s t : Finset α} (hf : ∀ a b, f a b = f b a) : image₂ f (s ∪ t) (s ∩ t) ⊆ image₂ f s t := coe_subset.1 <| by push_cast exact image2_union_inter_subset hf end UnionInter section SemilatticeSup variable [SemilatticeSup δ] @[simp (default + 1)] -- otherwise `simp` doesn't use `forall_image₂_iff` lemma sup'_image₂_le {g : γ → δ} {a : δ} (h : (image₂ f s t).Nonempty) : sup' (image₂ f s t) h g ≤ a ↔ ∀ x ∈ s, ∀ y ∈ t, g (f x y) ≤ a := by rw [sup'_le_iff, forall_image₂_iff] lemma sup'_image₂_left (g : γ → δ) (h : (image₂ f s t).Nonempty) : sup' (image₂ f s t) h g = sup' s h.of_image₂_left fun x ↦ sup' t h.of_image₂_right (g <| f x ·) := by simp only [image₂, sup'_image, sup'_product_left]; rfl lemma sup'_image₂_right (g : γ → δ) (h : (image₂ f s t).Nonempty) : sup' (image₂ f s t) h g = sup' t h.of_image₂_right fun y ↦ sup' s h.of_image₂_left (g <| f · y) := by simp only [image₂, sup'_image, sup'_product_right]; rfl variable [OrderBot δ] @[simp (default + 1)] -- otherwise `simp` doesn't use `forall_image₂_iff` lemma sup_image₂_le {g : γ → δ} {a : δ} : sup (image₂ f s t) g ≤ a ↔ ∀ x ∈ s, ∀ y ∈ t, g (f x y) ≤ a := by rw [Finset.sup_le_iff, forall_image₂_iff] variable (s t) lemma sup_image₂_left (g : γ → δ) : sup (image₂ f s t) g = sup s fun x ↦ sup t (g <| f x ·) := by simp only [image₂, sup_image, sup_product_left]; rfl lemma sup_image₂_right (g : γ → δ) : sup (image₂ f s t) g = sup t fun y ↦ sup s (g <| f · y) := by simp only [image₂, sup_image, sup_product_right]; rfl end SemilatticeSup section SemilatticeInf variable [SemilatticeInf δ] @[simp (default + 1)] -- otherwise `simp` doesn't use `forall_image₂_iff` lemma le_inf'_image₂ {g : γ → δ} {a : δ} (h : (image₂ f s t).Nonempty) : a ≤ inf' (image₂ f s t) h g ↔ ∀ x ∈ s, ∀ y ∈ t, a ≤ g (f x y) := by rw [le_inf'_iff, forall_image₂_iff] lemma inf'_image₂_left (g : γ → δ) (h : (image₂ f s t).Nonempty) : inf' (image₂ f s t) h g = inf' s h.of_image₂_left fun x ↦ inf' t h.of_image₂_right (g <| f x ·) := sup'_image₂_left (δ := δᵒᵈ) g h lemma inf'_image₂_right (g : γ → δ) (h : (image₂ f s t).Nonempty) : inf' (image₂ f s t) h g = inf' t h.of_image₂_right fun y ↦ inf' s h.of_image₂_left (g <| f · y) := sup'_image₂_right (δ := δᵒᵈ) g h variable [OrderTop δ] @[simp (default + 1)] -- otherwise `simp` doesn't use `forall_image₂_iff` lemma le_inf_image₂ {g : γ → δ} {a : δ} : a ≤ inf (image₂ f s t) g ↔ ∀ x ∈ s, ∀ y ∈ t, a ≤ g (f x y) := sup_image₂_le (δ := δᵒᵈ) variable (s t) lemma inf_image₂_left (g : γ → δ) : inf (image₂ f s t) g = inf s fun x ↦ inf t (g ∘ f x) := sup_image₂_left (δ := δᵒᵈ) .. lemma inf_image₂_right (g : γ → δ) : inf (image₂ f s t) g = inf t fun y ↦ inf s (g <| f · y) := sup_image₂_right (δ := δᵒᵈ) .. end SemilatticeInf end Finset open Finset namespace Fintype variable {ι : Type*} {α β γ : ι → Type*} [DecidableEq ι] [Fintype ι] [∀ i, DecidableEq (γ i)] lemma piFinset_image₂ (f : ∀ i, α i → β i → γ i) (s : ∀ i, Finset (α i)) (t : ∀ i, Finset (β i)) : piFinset (fun i ↦ image₂ (f i) (s i) (t i)) = image₂ (fun a b i ↦ f _ (a i) (b i)) (piFinset s) (piFinset t) := by ext; simp only [mem_piFinset, mem_image₂, Classical.skolem, forall_and, Function.funext_iff] end Fintype namespace Set variable [DecidableEq γ] {s : Set α} {t : Set β} @[simp] theorem toFinset_image2 (f : α → β → γ) (s : Set α) (t : Set β) [Fintype s] [Fintype t] [Fintype (image2 f s t)] : (image2 f s t).toFinset = Finset.image₂ f s.toFinset t.toFinset := Finset.coe_injective <| by simp theorem Finite.toFinset_image2 (f : α → β → γ) (hs : s.Finite) (ht : t.Finite) (hf := hs.image2 f ht) : hf.toFinset = Finset.image₂ f hs.toFinset ht.toFinset := Finset.coe_injective <| by simp end Set
Data\Finset\NatAntidiagonal.lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import Mathlib.Algebra.Order.Antidiag.Prod import Mathlib.Algebra.Order.Group.Nat import Mathlib.Data.Finset.Card import Mathlib.Data.Multiset.NatAntidiagonal /-! # Antidiagonals in ℕ × ℕ as finsets This file defines the antidiagonals of ℕ × ℕ as finsets: the `n`-th antidiagonal is the finset of pairs `(i, j)` such that `i + j = n`. This is useful for polynomial multiplication and more generally for sums going from `0` to `n`. ## Notes This refines files `Data.List.NatAntidiagonal` and `Data.Multiset.NatAntidiagonal`, providing an instance enabling `Finset.antidiagonal` on `Nat`. -/ open Function namespace Finset namespace Nat /-- The antidiagonal of a natural number `n` is the finset of pairs `(i, j)` such that `i + j = n`. -/ instance instHasAntidiagonal : HasAntidiagonal ℕ where antidiagonal n := ⟨Multiset.Nat.antidiagonal n, Multiset.Nat.nodup_antidiagonal n⟩ mem_antidiagonal {n} {xy} := by rw [mem_def, Multiset.Nat.mem_antidiagonal] lemma antidiagonal_eq_map (n : ℕ) : antidiagonal n = (range (n + 1)).map ⟨fun i ↦ (i, n - i), fun _ _ h ↦ (Prod.ext_iff.1 h).1⟩ := rfl lemma antidiagonal_eq_map' (n : ℕ) : antidiagonal n = (range (n + 1)).map ⟨fun i ↦ (n - i, i), fun _ _ h ↦ (Prod.ext_iff.1 h).2⟩ := by rw [← map_swap_antidiagonal, antidiagonal_eq_map, map_map]; rfl lemma antidiagonal_eq_image (n : ℕ) : antidiagonal n = (range (n + 1)).image fun i ↦ (i, n - i) := by simp only [antidiagonal_eq_map, map_eq_image, Function.Embedding.coeFn_mk] lemma antidiagonal_eq_image' (n : ℕ) : antidiagonal n = (range (n + 1)).image fun i ↦ (n - i, i) := by simp only [antidiagonal_eq_map', map_eq_image, Function.Embedding.coeFn_mk] /-- The cardinality of the antidiagonal of `n` is `n + 1`. -/ @[simp] theorem card_antidiagonal (n : ℕ) : (antidiagonal n).card = n + 1 := by simp [antidiagonal] /-- The antidiagonal of `0` is the list `[(0, 0)]` -/ @[simp] theorem antidiagonal_zero : antidiagonal 0 = {(0, 0)} := rfl theorem antidiagonal_succ (n : ℕ) : antidiagonal (n + 1) = cons (0, n + 1) ((antidiagonal n).map (Embedding.prodMap ⟨Nat.succ, Nat.succ_injective⟩ (Embedding.refl _))) (by simp) := by apply eq_of_veq rw [cons_val, map_val] apply Multiset.Nat.antidiagonal_succ theorem antidiagonal_succ' (n : ℕ) : antidiagonal (n + 1) = cons (n + 1, 0) ((antidiagonal n).map (Embedding.prodMap (Embedding.refl _) ⟨Nat.succ, Nat.succ_injective⟩)) (by simp) := by apply eq_of_veq rw [cons_val, map_val] exact Multiset.Nat.antidiagonal_succ' theorem antidiagonal_succ_succ' {n : ℕ} : antidiagonal (n + 2) = cons (0, n + 2) (cons (n + 2, 0) ((antidiagonal n).map (Embedding.prodMap ⟨Nat.succ, Nat.succ_injective⟩ ⟨Nat.succ, Nat.succ_injective⟩)) <| by simp) (by simp) := by simp_rw [antidiagonal_succ (n + 1), antidiagonal_succ', Finset.map_cons, map_map] rfl theorem antidiagonal.fst_lt {n : ℕ} {kl : ℕ × ℕ} (hlk : kl ∈ antidiagonal n) : kl.1 < n + 1 := Nat.lt_succ_of_le <| antidiagonal.fst_le hlk theorem antidiagonal.snd_lt {n : ℕ} {kl : ℕ × ℕ} (hlk : kl ∈ antidiagonal n) : kl.2 < n + 1 := Nat.lt_succ_of_le <| antidiagonal.snd_le hlk @[simp] lemma antidiagonal_filter_snd_le_of_le {n k : ℕ} (h : k ≤ n) : (antidiagonal n).filter (fun a ↦ a.snd ≤ k) = (antidiagonal k).map (Embedding.prodMap ⟨_, add_left_injective (n - k)⟩ (Embedding.refl ℕ)) := by ext ⟨i, j⟩ suffices i + j = n ∧ j ≤ k ↔ ∃ a, a + j = k ∧ a + (n - k) = i by simpa refine ⟨fun hi ↦ ⟨k - j, tsub_add_cancel_of_le hi.2, ?_⟩, ?_⟩ · rw [add_comm, tsub_add_eq_add_tsub h, ← hi.1, add_assoc, Nat.add_sub_of_le hi.2, add_tsub_cancel_right] · rintro ⟨l, hl, rfl⟩ refine ⟨?_, hl ▸ Nat.le_add_left j l⟩ rw [add_assoc, add_comm, add_assoc, add_comm j l, hl] exact Nat.sub_add_cancel h @[simp] lemma antidiagonal_filter_fst_le_of_le {n k : ℕ} (h : k ≤ n) : (antidiagonal n).filter (fun a ↦ a.fst ≤ k) = (antidiagonal k).map (Embedding.prodMap (Embedding.refl ℕ) ⟨_, add_left_injective (n - k)⟩) := by have aux₁ : fun a ↦ a.fst ≤ k = (fun a ↦ a.snd ≤ k) ∘ (Equiv.prodComm ℕ ℕ).symm := rfl have aux₂ : ∀ i j, (∃ a b, a + b = k ∧ b = i ∧ a + (n - k) = j) ↔ ∃ a b, a + b = k ∧ a = i ∧ b + (n - k) = j := fun i j ↦ by rw [exists_comm]; exact exists₂_congr (fun a b ↦ by rw [add_comm]) rw [← map_prodComm_antidiagonal] simp_rw [aux₁, ← map_filter, antidiagonal_filter_snd_le_of_le h, map_map] ext ⟨i, j⟩ simpa using aux₂ i j @[simp] lemma antidiagonal_filter_le_fst_of_le {n k : ℕ} (h : k ≤ n) : (antidiagonal n).filter (fun a ↦ k ≤ a.fst) = (antidiagonal (n - k)).map (Embedding.prodMap ⟨_, add_left_injective k⟩ (Embedding.refl ℕ)) := by ext ⟨i, j⟩ suffices i + j = n ∧ k ≤ i ↔ ∃ a, a + j = n - k ∧ a + k = i by simpa refine ⟨fun hi ↦ ⟨i - k, ?_, tsub_add_cancel_of_le hi.2⟩, ?_⟩ · rw [← Nat.sub_add_comm hi.2, hi.1] · rintro ⟨l, hl, rfl⟩ refine ⟨?_, Nat.le_add_left k l⟩ rw [add_right_comm, hl] exact tsub_add_cancel_of_le h @[simp] lemma antidiagonal_filter_le_snd_of_le {n k : ℕ} (h : k ≤ n) : (antidiagonal n).filter (fun a ↦ k ≤ a.snd) = (antidiagonal (n - k)).map (Embedding.prodMap (Embedding.refl ℕ) ⟨_, add_left_injective k⟩) := by have aux₁ : fun a ↦ k ≤ a.snd = (fun a ↦ k ≤ a.fst) ∘ (Equiv.prodComm ℕ ℕ).symm := rfl have aux₂ : ∀ i j, (∃ a b, a + b = n - k ∧ b = i ∧ a + k = j) ↔ ∃ a b, a + b = n - k ∧ a = i ∧ b + k = j := fun i j ↦ by rw [exists_comm]; exact exists₂_congr (fun a b ↦ by rw [add_comm]) rw [← map_prodComm_antidiagonal] simp_rw [aux₁, ← map_filter, antidiagonal_filter_le_fst_of_le h, map_map] ext ⟨i, j⟩ simpa using aux₂ i j /-- The set `antidiagonal n` is equivalent to `Fin (n+1)`, via the first projection. --/ @[simps] def antidiagonalEquivFin (n : ℕ) : antidiagonal n ≃ Fin (n + 1) where toFun := fun ⟨⟨i, j⟩, h⟩ ↦ ⟨i, antidiagonal.fst_lt h⟩ invFun := fun ⟨i, h⟩ ↦ ⟨⟨i, n - i⟩, by rw [mem_antidiagonal, add_comm, tsub_add_cancel_iff_le] exact Nat.le_of_lt_succ h⟩ left_inv := by rintro ⟨⟨i, j⟩, h⟩; ext; rfl right_inv x := rfl end Nat end Finset
Data\Finset\NatDivisors.lean
/- Copyright (c) 2023 Damiano Testa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Damiano Testa, Yury Kudryashov -/ import Mathlib.NumberTheory.Divisors import Mathlib.Data.Nat.Order.Lemmas import Mathlib.Data.Finset.Pointwise /-! # `Nat.divisors` as a multiplicative homomorpism The main definition of this file is `Nat.divisorsHom : ℕ →* Finset ℕ`, exhibiting `Nat.divisors` as a multiplicative homomorphism from `ℕ` to `Finset ℕ`. -/ open Nat Finset open scoped Pointwise /-- The divisors of a product of natural numbers are the pointwise product of the divisors of the factors. -/ lemma Nat.divisors_mul (m n : ℕ) : divisors (m * n) = divisors m * divisors n := by ext k simp_rw [mem_mul, mem_divisors, dvd_mul, mul_ne_zero_iff, ← exists_and_left, ← exists_and_right] simp only [and_assoc, and_comm, and_left_comm] /-- `Nat.divisors` as a `MonoidHom`. -/ @[simps] def Nat.divisorsHom : ℕ →* Finset ℕ where toFun := Nat.divisors map_mul' := divisors_mul map_one' := divisors_one lemma Nat.Prime.divisors_sq {p : ℕ} (hp : p.Prime) : (p ^ 2).divisors = {p ^ 2, p, 1} := by simp [divisors_prime_pow hp, range_succ] lemma List.nat_divisors_prod (l : List ℕ) : divisors l.prod = (l.map divisors).prod := map_list_prod Nat.divisorsHom l lemma Multiset.nat_divisors_prod (s : Multiset ℕ) : divisors s.prod = (s.map divisors).prod := map_multiset_prod Nat.divisorsHom s lemma Finset.nat_divisors_prod {ι : Type*} (s : Finset ι) (f : ι → ℕ) : divisors (∏ i ∈ s, f i) = ∏ i ∈ s, divisors (f i) := map_prod Nat.divisorsHom f s
Data\Finset\NoncommProd.lean
/- Copyright (c) 2021 Yakov Pechersky. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yakov Pechersky -/ import Mathlib.Algebra.BigOperators.Group.Finset import Mathlib.Algebra.Group.Commute.Hom import Mathlib.Data.Fintype.Card /-! # Products (respectively, sums) over a finset or a multiset. The regular `Finset.prod` and `Multiset.prod` require `[CommMonoid α]`. Often, there are collections `s : Finset α` where `[Monoid α]` and we know, in a dependent fashion, that for all the terms `∀ (x ∈ s) (y ∈ s), Commute x y`. This allows to still have a well-defined product over `s`. ## Main definitions - `Finset.noncommProd`, requiring a proof of commutativity of held terms - `Multiset.noncommProd`, requiring a proof of commutativity of held terms ## Implementation details While `List.prod` is defined via `List.foldl`, `noncommProd` is defined via `Multiset.foldr` for neater proofs and definitions. By the commutativity assumption, the two must be equal. TODO: Tidy up this file by using the fact that the submonoid generated by commuting elements is commutative and using the `Finset.prod` versions of lemmas to prove the `noncommProd` version. -/ variable {F ι α β γ : Type*} (f : α → β → β) (op : α → α → α) namespace Multiset /-- Fold of a `s : Multiset α` with `f : α → β → β`, given a proof that `LeftCommutative f` on all elements `x ∈ s`. -/ def noncommFoldr (s : Multiset α) (comm : { x | x ∈ s }.Pairwise fun x y => ∀ b, f x (f y b) = f y (f x b)) (b : β) : β := s.attach.foldr (f ∘ Subtype.val) (fun ⟨_, hx⟩ ⟨_, hy⟩ => haveI : IsRefl α fun x y => ∀ b, f x (f y b) = f y (f x b) := ⟨fun _ _ => rfl⟩ comm.of_refl hx hy) b @[simp] theorem noncommFoldr_coe (l : List α) (comm) (b : β) : noncommFoldr f (l : Multiset α) comm b = l.foldr f b := by simp only [noncommFoldr, coe_foldr, coe_attach, List.attach, List.attachWith, Function.comp] rw [← List.foldr_map] simp [List.map_pmap] @[simp] theorem noncommFoldr_empty (h) (b : β) : noncommFoldr f (0 : Multiset α) h b = b := rfl theorem noncommFoldr_cons (s : Multiset α) (a : α) (h h') (b : β) : noncommFoldr f (a ::ₘ s) h b = f a (noncommFoldr f s h' b) := by induction s using Quotient.inductionOn simp theorem noncommFoldr_eq_foldr (s : Multiset α) (h : LeftCommutative f) (b : β) : noncommFoldr f s (fun x _ y _ _ => h x y) b = foldr f h b s := by induction s using Quotient.inductionOn simp section assoc variable [assoc : Std.Associative op] /-- Fold of a `s : Multiset α` with an associative `op : α → α → α`, given a proofs that `op` is commutative on all elements `x ∈ s`. -/ def noncommFold (s : Multiset α) (comm : { x | x ∈ s }.Pairwise fun x y => op x y = op y x) : α → α := noncommFoldr op s fun x hx y hy h b => by rw [← assoc.assoc, comm hx hy h, assoc.assoc] @[simp] theorem noncommFold_coe (l : List α) (comm) (a : α) : noncommFold op (l : Multiset α) comm a = l.foldr op a := by simp [noncommFold] @[simp] theorem noncommFold_empty (h) (a : α) : noncommFold op (0 : Multiset α) h a = a := rfl theorem noncommFold_cons (s : Multiset α) (a : α) (h h') (x : α) : noncommFold op (a ::ₘ s) h x = op a (noncommFold op s h' x) := by induction s using Quotient.inductionOn simp theorem noncommFold_eq_fold (s : Multiset α) [Std.Commutative op] (a : α) : noncommFold op s (fun x _ y _ _ => Std.Commutative.comm x y) a = fold op a s := by induction s using Quotient.inductionOn simp end assoc variable [Monoid α] [Monoid β] /-- Product of a `s : Multiset α` with `[Monoid α]`, given a proof that `*` commutes on all elements `x ∈ s`. -/ @[to_additive "Sum of a `s : Multiset α` with `[AddMonoid α]`, given a proof that `+` commutes on all elements `x ∈ s`."] def noncommProd (s : Multiset α) (comm : { x | x ∈ s }.Pairwise Commute) : α := s.noncommFold (· * ·) comm 1 @[to_additive (attr := simp)] theorem noncommProd_coe (l : List α) (comm) : noncommProd (l : Multiset α) comm = l.prod := by rw [noncommProd] simp only [noncommFold_coe] induction' l with hd tl hl · simp · rw [List.prod_cons, List.foldr, hl] intro x hx y hy exact comm (List.mem_cons_of_mem _ hx) (List.mem_cons_of_mem _ hy) @[to_additive (attr := simp)] theorem noncommProd_empty (h) : noncommProd (0 : Multiset α) h = 1 := rfl @[to_additive (attr := simp)] theorem noncommProd_cons (s : Multiset α) (a : α) (comm) : noncommProd (a ::ₘ s) comm = a * noncommProd s (comm.mono fun _ => mem_cons_of_mem) := by induction s using Quotient.inductionOn simp @[to_additive] theorem noncommProd_cons' (s : Multiset α) (a : α) (comm) : noncommProd (a ::ₘ s) comm = noncommProd s (comm.mono fun _ => mem_cons_of_mem) * a := by induction' s using Quotient.inductionOn with s simp only [quot_mk_to_coe, cons_coe, noncommProd_coe, List.prod_cons] induction' s with hd tl IH · simp · rw [List.prod_cons, mul_assoc, ← IH, ← mul_assoc, ← mul_assoc] · congr 1 apply comm.of_refl <;> simp · intro x hx y hy simp only [quot_mk_to_coe, List.mem_cons, mem_coe, cons_coe] at hx hy apply comm · cases hx <;> simp [*] · cases hy <;> simp [*] @[to_additive] theorem noncommProd_add (s t : Multiset α) (comm) : noncommProd (s + t) comm = noncommProd s (comm.mono <| subset_of_le <| s.le_add_right t) * noncommProd t (comm.mono <| subset_of_le <| t.le_add_left s) := by rcases s with ⟨⟩ rcases t with ⟨⟩ simp @[to_additive] lemma noncommProd_induction (s : Multiset α) (comm) (p : α → Prop) (hom : ∀ a b, p a → p b → p (a * b)) (unit : p 1) (base : ∀ x ∈ s, p x) : p (s.noncommProd comm) := by induction' s using Quotient.inductionOn with l simp only [quot_mk_to_coe, noncommProd_coe, mem_coe] at base ⊢ exact l.prod_induction p hom unit base variable [FunLike F α β] @[to_additive] protected theorem map_noncommProd_aux [MonoidHomClass F α β] (s : Multiset α) (comm : { x | x ∈ s }.Pairwise Commute) (f : F) : { x | x ∈ s.map f }.Pairwise Commute := by simp only [Multiset.mem_map] rintro _ ⟨x, hx, rfl⟩ _ ⟨y, hy, rfl⟩ _ exact (comm.of_refl hx hy).map f @[to_additive] theorem map_noncommProd [MonoidHomClass F α β] (s : Multiset α) (comm) (f : F) : f (s.noncommProd comm) = (s.map f).noncommProd (Multiset.map_noncommProd_aux s comm f) := by induction s using Quotient.inductionOn simpa using map_list_prod f _ @[deprecated (since := "2024-07-23")] alias noncommProd_map := map_noncommProd @[deprecated (since := "2024-07-23")] alias noncommSum_map := map_noncommSum @[deprecated (since := "2024-07-23")] protected alias noncommProd_map_aux := Multiset.map_noncommProd_aux @[deprecated (since := "2024-07-23")] protected alias noncommSum_map_aux := Multiset.map_noncommSum_aux @[to_additive noncommSum_eq_card_nsmul] theorem noncommProd_eq_pow_card (s : Multiset α) (comm) (m : α) (h : ∀ x ∈ s, x = m) : s.noncommProd comm = m ^ Multiset.card s := by induction s using Quotient.inductionOn simp only [quot_mk_to_coe, noncommProd_coe, coe_card, mem_coe] at * exact List.prod_eq_pow_card _ m h @[to_additive] theorem noncommProd_eq_prod {α : Type*} [CommMonoid α] (s : Multiset α) : (noncommProd s fun _ _ _ _ _ => Commute.all _ _) = prod s := by induction s using Quotient.inductionOn simp @[to_additive] theorem noncommProd_commute (s : Multiset α) (comm) (y : α) (h : ∀ x ∈ s, Commute y x) : Commute y (s.noncommProd comm) := by induction s using Quotient.inductionOn simp only [quot_mk_to_coe, noncommProd_coe] exact Commute.list_prod_right _ _ h theorem mul_noncommProd_erase [DecidableEq α] (s : Multiset α) {a : α} (h : a ∈ s) (comm) (comm' := fun x hx y hy hxy ↦ comm (s.mem_of_mem_erase hx) (s.mem_of_mem_erase hy) hxy) : a * (s.erase a).noncommProd comm' = s.noncommProd comm := by induction' s using Quotient.inductionOn with l simp only [quot_mk_to_coe, mem_coe, coe_erase, noncommProd_coe] at comm h ⊢ suffices ∀ x ∈ l, ∀ y ∈ l, x * y = y * x by rw [List.prod_erase_of_comm h this] intro x hx y hy rcases eq_or_ne x y with rfl | hxy · rfl exact comm hx hy hxy theorem noncommProd_erase_mul [DecidableEq α] (s : Multiset α) {a : α} (h : a ∈ s) (comm) (comm' := fun x hx y hy hxy ↦ comm (s.mem_of_mem_erase hx) (s.mem_of_mem_erase hy) hxy) : (s.erase a).noncommProd comm' * a = s.noncommProd comm := by suffices ∀ b ∈ erase s a, Commute a b by rw [← (noncommProd_commute (s.erase a) comm' a this).eq, mul_noncommProd_erase s h comm comm'] intro b hb rcases eq_or_ne a b with rfl | hab · rfl exact comm h (mem_of_mem_erase hb) hab end Multiset namespace Finset variable [Monoid β] [Monoid γ] /-- Proof used in definition of `Finset.noncommProd` -/ @[to_additive] theorem noncommProd_lemma (s : Finset α) (f : α → β) (comm : (s : Set α).Pairwise fun a b => Commute (f a) (f b)) : Set.Pairwise { x | x ∈ Multiset.map f s.val } Commute := by simp_rw [Multiset.mem_map] rintro _ ⟨a, ha, rfl⟩ _ ⟨b, hb, rfl⟩ _ exact comm.of_refl ha hb /-- Product of a `s : Finset α` mapped with `f : α → β` with `[Monoid β]`, given a proof that `*` commutes on all elements `f x` for `x ∈ s`. -/ @[to_additive "Sum of a `s : Finset α` mapped with `f : α → β` with `[AddMonoid β]`, given a proof that `+` commutes on all elements `f x` for `x ∈ s`."] def noncommProd (s : Finset α) (f : α → β) (comm : (s : Set α).Pairwise fun a b => Commute (f a) (f b)) : β := (s.1.map f).noncommProd <| noncommProd_lemma s f comm @[to_additive] lemma noncommProd_induction (s : Finset α) (f : α → β) (comm) (p : β → Prop) (hom : ∀ a b, p a → p b → p (a * b)) (unit : p 1) (base : ∀ x ∈ s, p (f x)) : p (s.noncommProd f comm) := by refine Multiset.noncommProd_induction _ _ _ hom unit fun b hb ↦ ?_ obtain (⟨a, ha : a ∈ s, rfl : f a = b⟩) := by simpa using hb exact base a ha @[to_additive (attr := congr)] theorem noncommProd_congr {s₁ s₂ : Finset α} {f g : α → β} (h₁ : s₁ = s₂) (h₂ : ∀ x ∈ s₂, f x = g x) (comm) : noncommProd s₁ f comm = noncommProd s₂ g fun x hx y hy h => by dsimp only rw [← h₂ _ hx, ← h₂ _ hy] subst h₁ exact comm hx hy h := by simp_rw [noncommProd, Multiset.map_congr (congr_arg _ h₁) h₂] @[to_additive (attr := simp)] theorem noncommProd_toFinset [DecidableEq α] (l : List α) (f : α → β) (comm) (hl : l.Nodup) : noncommProd l.toFinset f comm = (l.map f).prod := by rw [← List.dedup_eq_self] at hl simp [noncommProd, hl] @[to_additive (attr := simp)] theorem noncommProd_empty (f : α → β) (h) : noncommProd (∅ : Finset α) f h = 1 := rfl @[to_additive (attr := simp)] theorem noncommProd_cons (s : Finset α) (a : α) (f : α → β) (ha : a ∉ s) (comm) : noncommProd (cons a s ha) f comm = f a * noncommProd s f (comm.mono fun _ => Finset.mem_cons.2 ∘ .inr) := by simp_rw [noncommProd, Finset.cons_val, Multiset.map_cons, Multiset.noncommProd_cons] @[to_additive] theorem noncommProd_cons' (s : Finset α) (a : α) (f : α → β) (ha : a ∉ s) (comm) : noncommProd (cons a s ha) f comm = noncommProd s f (comm.mono fun _ => Finset.mem_cons.2 ∘ .inr) * f a := by simp_rw [noncommProd, Finset.cons_val, Multiset.map_cons, Multiset.noncommProd_cons'] @[to_additive (attr := simp)] theorem noncommProd_insert_of_not_mem [DecidableEq α] (s : Finset α) (a : α) (f : α → β) (comm) (ha : a ∉ s) : noncommProd (insert a s) f comm = f a * noncommProd s f (comm.mono fun _ => mem_insert_of_mem) := by simp only [← cons_eq_insert _ _ ha, noncommProd_cons] @[to_additive] theorem noncommProd_insert_of_not_mem' [DecidableEq α] (s : Finset α) (a : α) (f : α → β) (comm) (ha : a ∉ s) : noncommProd (insert a s) f comm = noncommProd s f (comm.mono fun _ => mem_insert_of_mem) * f a := by simp only [← cons_eq_insert _ _ ha, noncommProd_cons'] @[to_additive (attr := simp)] theorem noncommProd_singleton (a : α) (f : α → β) : noncommProd ({a} : Finset α) f (by norm_cast exact Set.pairwise_singleton _ _) = f a := mul_one _ variable [FunLike F β γ] @[to_additive] theorem map_noncommProd [MonoidHomClass F β γ] (s : Finset α) (f : α → β) (comm) (g : F) : g (s.noncommProd f comm) = s.noncommProd (fun i => g (f i)) fun x hx y hy _ => (comm.of_refl hx hy).map g := by simp [noncommProd, Multiset.map_noncommProd] @[deprecated (since := "2024-07-23")] alias noncommProd_map := map_noncommProd @[deprecated (since := "2024-07-23")] alias noncommSum_map := map_noncommSum @[to_additive noncommSum_eq_card_nsmul] theorem noncommProd_eq_pow_card (s : Finset α) (f : α → β) (comm) (m : β) (h : ∀ x ∈ s, f x = m) : s.noncommProd f comm = m ^ s.card := by rw [noncommProd, Multiset.noncommProd_eq_pow_card _ _ m] · simp only [Finset.card_def, Multiset.card_map] · simpa using h @[to_additive] theorem noncommProd_commute (s : Finset α) (f : α → β) (comm) (y : β) (h : ∀ x ∈ s, Commute y (f x)) : Commute y (s.noncommProd f comm) := by apply Multiset.noncommProd_commute intro y rw [Multiset.mem_map] rintro ⟨x, ⟨hx, rfl⟩⟩ exact h x hx theorem mul_noncommProd_erase [DecidableEq α] (s : Finset α) {a : α} (h : a ∈ s) (f : α → β) (comm) (comm' := fun x hx y hy hxy ↦ comm (s.mem_of_mem_erase hx) (s.mem_of_mem_erase hy) hxy) : f a * (s.erase a).noncommProd f comm' = s.noncommProd f comm := by classical simpa only [← Multiset.map_erase_of_mem _ _ h] using Multiset.mul_noncommProd_erase (s.1.map f) (Multiset.mem_map_of_mem f h) _ theorem noncommProd_erase_mul [DecidableEq α] (s : Finset α) {a : α} (h : a ∈ s) (f : α → β) (comm) (comm' := fun x hx y hy hxy ↦ comm (s.mem_of_mem_erase hx) (s.mem_of_mem_erase hy) hxy) : (s.erase a).noncommProd f comm' * f a = s.noncommProd f comm := by classical simpa only [← Multiset.map_erase_of_mem _ _ h] using Multiset.noncommProd_erase_mul (s.1.map f) (Multiset.mem_map_of_mem f h) _ @[to_additive] theorem noncommProd_eq_prod {β : Type*} [CommMonoid β] (s : Finset α) (f : α → β) : (noncommProd s f fun _ _ _ _ _ => Commute.all _ _) = s.prod f := by induction' s using Finset.cons_induction_on with a s ha IH · simp · simp [ha, IH] /-- The non-commutative version of `Finset.prod_union` -/ @[to_additive "The non-commutative version of `Finset.sum_union`"] theorem noncommProd_union_of_disjoint [DecidableEq α] {s t : Finset α} (h : Disjoint s t) (f : α → β) (comm : { x | x ∈ s ∪ t }.Pairwise fun a b => Commute (f a) (f b)) : noncommProd (s ∪ t) f comm = noncommProd s f (comm.mono <| coe_subset.2 subset_union_left) * noncommProd t f (comm.mono <| coe_subset.2 subset_union_right) := by obtain ⟨sl, sl', rfl⟩ := exists_list_nodup_eq s obtain ⟨tl, tl', rfl⟩ := exists_list_nodup_eq t rw [List.disjoint_toFinset_iff_disjoint] at h calc noncommProd (List.toFinset sl ∪ List.toFinset tl) f comm = noncommProd ⟨↑(sl ++ tl), Multiset.coe_nodup.2 (sl'.append tl' h)⟩ f (by convert comm; simp [Set.ext_iff]) := noncommProd_congr (by ext; simp) (by simp) _ _ = noncommProd (List.toFinset sl) f (comm.mono <| coe_subset.2 subset_union_left) * noncommProd (List.toFinset tl) f (comm.mono <| coe_subset.2 subset_union_right) := by simp [noncommProd, List.dedup_eq_self.2 sl', List.dedup_eq_self.2 tl', h] @[to_additive] theorem noncommProd_mul_distrib_aux {s : Finset α} {f : α → β} {g : α → β} (comm_ff : (s : Set α).Pairwise fun x y => Commute (f x) (f y)) (comm_gg : (s : Set α).Pairwise fun x y => Commute (g x) (g y)) (comm_gf : (s : Set α).Pairwise fun x y => Commute (g x) (f y)) : (s : Set α).Pairwise fun x y => Commute ((f * g) x) ((f * g) y) := by intro x hx y hy h apply Commute.mul_left <;> apply Commute.mul_right · exact comm_ff.of_refl hx hy · exact (comm_gf hy hx h.symm).symm · exact comm_gf hx hy h · exact comm_gg.of_refl hx hy /-- The non-commutative version of `Finset.prod_mul_distrib` -/ @[to_additive "The non-commutative version of `Finset.sum_add_distrib`"] theorem noncommProd_mul_distrib {s : Finset α} (f : α → β) (g : α → β) (comm_ff comm_gg comm_gf) : noncommProd s (f * g) (noncommProd_mul_distrib_aux comm_ff comm_gg comm_gf) = noncommProd s f comm_ff * noncommProd s g comm_gg := by induction' s using Finset.cons_induction_on with x s hnmem ih · simp rw [Finset.noncommProd_cons, Finset.noncommProd_cons, Finset.noncommProd_cons, Pi.mul_apply, ih (comm_ff.mono fun _ => mem_cons_of_mem) (comm_gg.mono fun _ => mem_cons_of_mem) (comm_gf.mono fun _ => mem_cons_of_mem), (noncommProd_commute _ _ _ _ fun y hy => ?_).mul_mul_mul_comm] exact comm_gf (mem_cons_self x s) (mem_cons_of_mem hy) (ne_of_mem_of_not_mem hy hnmem).symm section FinitePi variable {M : ι → Type*} [∀ i, Monoid (M i)] @[to_additive] theorem noncommProd_mul_single [Fintype ι] [DecidableEq ι] (x : ∀ i, M i) : (univ.noncommProd (fun i => Pi.mulSingle i (x i)) fun i _ j _ _ => Pi.mulSingle_apply_commute x i j) = x := by ext i apply (univ.map_noncommProd (fun i ↦ MonoidHom.mulSingle M i (x i)) ?a (Pi.evalMonoidHom M i)).trans case a => intro i _ j _ _ exact Pi.mulSingle_apply_commute x i j convert (noncommProd_congr (insert_erase (mem_univ i)).symm _ _).trans _ · intro j exact Pi.mulSingle j (x j) i · intro j _; dsimp · rw [noncommProd_insert_of_not_mem _ _ _ _ (not_mem_erase _ _), noncommProd_eq_pow_card (univ.erase i), one_pow, mul_one] · simp only [MonoidHom.mulSingle_apply, ne_eq, Pi.mulSingle_eq_same] · intro j hj simp? at hj says simp only [mem_erase, ne_eq, mem_univ, and_true] at hj simp only [MonoidHom.mulSingle_apply, Pi.mulSingle, Function.update, Eq.ndrec, Pi.one_apply, ne_eq, dite_eq_right_iff] intro h simp [*] at * @[to_additive] theorem _root_.MonoidHom.pi_ext [Finite ι] [DecidableEq ι] {f g : (∀ i, M i) →* γ} (h : ∀ i x, f (Pi.mulSingle i x) = g (Pi.mulSingle i x)) : f = g := by cases nonempty_fintype ι ext x rw [← noncommProd_mul_single x, univ.map_noncommProd, univ.map_noncommProd] congr 1 with i; exact h i (x i) end FinitePi end Finset
Data\Finset\Option.lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Mario Carneiro, Sean Leather -/ import Mathlib.Data.Finset.Card /-! # Finite sets in `Option α` In this file we define * `Option.toFinset`: construct an empty or singleton `Finset α` from an `Option α`; * `Finset.insertNone`: given `s : Finset α`, lift it to a finset on `Option α` using `Option.some` and then insert `Option.none`; * `Finset.eraseNone`: given `s : Finset (Option α)`, returns `t : Finset α` such that `x ∈ t ↔ some x ∈ s`. Then we prove some basic lemmas about these definitions. ## Tags finset, option -/ variable {α β : Type*} open Function namespace Option /-- Construct an empty or singleton finset from an `Option` -/ def toFinset (o : Option α) : Finset α := o.elim ∅ singleton @[simp] theorem toFinset_none : none.toFinset = (∅ : Finset α) := rfl @[simp] theorem toFinset_some {a : α} : (some a).toFinset = {a} := rfl @[simp] theorem mem_toFinset {a : α} {o : Option α} : a ∈ o.toFinset ↔ a ∈ o := by cases o <;> simp [eq_comm] theorem card_toFinset (o : Option α) : o.toFinset.card = o.elim 0 1 := by cases o <;> rfl end Option namespace Finset /-- Given a finset on `α`, lift it to being a finset on `Option α` using `Option.some` and then insert `Option.none`. -/ def insertNone : Finset α ↪o Finset (Option α) := (OrderEmbedding.ofMapLEIff fun s => cons none (s.map Embedding.some) <| by simp) fun s t => by rw [le_iff_subset, cons_subset_cons, map_subset_map, le_iff_subset] @[simp] theorem mem_insertNone {s : Finset α} : ∀ {o : Option α}, o ∈ insertNone s ↔ ∀ a ∈ o, a ∈ s | none => iff_of_true (Multiset.mem_cons_self _ _) fun a h => by cases h | some a => Multiset.mem_cons.trans <| by simp lemma forall_mem_insertNone {s : Finset α} {p : Option α → Prop} : (∀ a ∈ insertNone s, p a) ↔ p none ∧ ∀ a ∈ s, p a := by simp [Option.forall] theorem some_mem_insertNone {s : Finset α} {a : α} : some a ∈ insertNone s ↔ a ∈ s := by simp lemma none_mem_insertNone {s : Finset α} : none ∈ insertNone s := by simp @[aesop safe apply (rule_sets := [finsetNonempty])] lemma insertNone_nonempty {s : Finset α} : insertNone s |>.Nonempty := ⟨none, none_mem_insertNone⟩ @[simp] theorem card_insertNone (s : Finset α) : s.insertNone.card = s.card + 1 := by simp [insertNone] /-- Given `s : Finset (Option α)`, `eraseNone s : Finset α` is the set of `x : α` such that `some x ∈ s`. -/ def eraseNone : Finset (Option α) →o Finset α := (Finset.mapEmbedding (Equiv.optionIsSomeEquiv α).toEmbedding).toOrderHom.comp ⟨Finset.subtype _, subtype_mono⟩ @[simp] theorem mem_eraseNone {s : Finset (Option α)} {x : α} : x ∈ eraseNone s ↔ some x ∈ s := by simp [eraseNone] lemma forall_mem_eraseNone {s : Finset (Option α)} {p : Option α → Prop} : (∀ a ∈ eraseNone s, p a) ↔ ∀ a : α, (a : Option α) ∈ s → p a := by simp [Option.forall] theorem eraseNone_eq_biUnion [DecidableEq α] (s : Finset (Option α)) : eraseNone s = s.biUnion Option.toFinset := by ext simp @[simp] theorem eraseNone_map_some (s : Finset α) : eraseNone (s.map Embedding.some) = s := by ext simp @[simp] theorem eraseNone_image_some [DecidableEq (Option α)] (s : Finset α) : eraseNone (s.image some) = s := by simpa only [map_eq_image] using eraseNone_map_some s @[simp] theorem coe_eraseNone (s : Finset (Option α)) : (eraseNone s : Set α) = some ⁻¹' s := Set.ext fun _ => mem_eraseNone @[simp] theorem eraseNone_union [DecidableEq (Option α)] [DecidableEq α] (s t : Finset (Option α)) : eraseNone (s ∪ t) = eraseNone s ∪ eraseNone t := by ext simp @[simp] theorem eraseNone_inter [DecidableEq (Option α)] [DecidableEq α] (s t : Finset (Option α)) : eraseNone (s ∩ t) = eraseNone s ∩ eraseNone t := by ext simp @[simp] theorem eraseNone_empty : eraseNone (∅ : Finset (Option α)) = ∅ := by ext simp @[simp] theorem eraseNone_none : eraseNone ({none} : Finset (Option α)) = ∅ := by ext simp @[simp] theorem image_some_eraseNone [DecidableEq (Option α)] (s : Finset (Option α)) : (eraseNone s).image some = s.erase none := by ext (_ | x) <;> simp @[simp] theorem map_some_eraseNone [DecidableEq (Option α)] (s : Finset (Option α)) : (eraseNone s).map Embedding.some = s.erase none := by rw [map_eq_image, Embedding.some_apply, image_some_eraseNone] @[simp] theorem insertNone_eraseNone [DecidableEq (Option α)] (s : Finset (Option α)) : insertNone (eraseNone s) = insert none s := by ext (_ | x) <;> simp @[simp] theorem eraseNone_insertNone (s : Finset α) : eraseNone (insertNone s) = s := by ext simp end Finset
Data\Finset\Order.lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Kenny Lau -/ import Mathlib.Data.Finset.Basic /-! # Finsets of ordered types -/ universe u v w variable {α : Type u} theorem Directed.finset_le {r : α → α → Prop} [IsTrans α r] {ι} [hι : Nonempty ι] {f : ι → α} (D : Directed r f) (s : Finset ι) : ∃ z, ∀ i ∈ s, r (f i) (f z) := show ∃ z, ∀ i ∈ s.1, r (f i) (f z) from Multiset.induction_on s.1 (let ⟨z⟩ := hι; ⟨z, fun _ ↦ by simp⟩) fun i s ⟨j, H⟩ ↦ let ⟨k, h₁, h₂⟩ := D i j ⟨k, fun a h ↦ (Multiset.mem_cons.1 h).casesOn (fun h ↦ h.symm ▸ h₁) fun h ↦ _root_.trans (H _ h) h₂⟩ theorem Finset.exists_le [Nonempty α] [Preorder α] [IsDirected α (· ≤ ·)] (s : Finset α) : ∃ M, ∀ i ∈ s, i ≤ M := directed_id.finset_le _
Data\Finset\Pairwise.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.Lattice /-! # Relations holding pairwise on finite sets In this file we prove a few results about the interaction of `Set.PairwiseDisjoint` and `Finset`, as well as the interaction of `List.Pairwise Disjoint` and the condition of `Disjoint` on `List.toFinset`, in `Set` form. -/ open Finset variable {α ι ι' : Type*} instance [DecidableEq α] {r : α → α → Prop} [DecidableRel r] {s : Finset α} : Decidable ((s : Set α).Pairwise r) := decidable_of_iff' (∀ a ∈ s, ∀ b ∈ s, a ≠ b → r a b) Iff.rfl theorem Finset.pairwiseDisjoint_range_singleton : (Set.range (singleton : α → Finset α)).PairwiseDisjoint id := by rintro _ ⟨a, rfl⟩ _ ⟨b, rfl⟩ h exact disjoint_singleton.2 (ne_of_apply_ne _ h) namespace Set theorem PairwiseDisjoint.elim_finset {s : Set ι} {f : ι → Finset α} (hs : s.PairwiseDisjoint f) {i j : ι} (hi : i ∈ s) (hj : j ∈ s) (a : α) (hai : a ∈ f i) (haj : a ∈ f j) : i = j := hs.elim hi hj (Finset.not_disjoint_iff.2 ⟨a, hai, haj⟩) section SemilatticeInf variable [SemilatticeInf α] [OrderBot α] {s : Finset ι} {f : ι → α} theorem PairwiseDisjoint.image_finset_of_le [DecidableEq ι] {s : Finset ι} {f : ι → α} (hs : (s : Set ι).PairwiseDisjoint f) {g : ι → ι} (hf : ∀ a, f (g a) ≤ f a) : (s.image g : Set ι).PairwiseDisjoint f := by rw [coe_image] exact hs.image_of_le hf theorem PairwiseDisjoint.attach (hs : (s : Set ι).PairwiseDisjoint f) : (s.attach : Set { x // x ∈ s }).PairwiseDisjoint (f ∘ Subtype.val) := fun i _ j _ hij => hs i.2 j.2 <| mt Subtype.ext_val hij end SemilatticeInf variable [Lattice α] [OrderBot α] /-- Bind operation for `Set.PairwiseDisjoint`. In a complete lattice, you can use `Set.PairwiseDisjoint.biUnion`. -/ theorem PairwiseDisjoint.biUnion_finset {s : Set ι'} {g : ι' → Finset ι} {f : ι → α} (hs : s.PairwiseDisjoint fun i' : ι' => (g i').sup f) (hg : ∀ i ∈ s, (g i : Set ι).PairwiseDisjoint f) : (⋃ i ∈ s, ↑(g i)).PairwiseDisjoint f := by rintro a ha b hb hab simp_rw [Set.mem_iUnion] at ha hb obtain ⟨c, hc, ha⟩ := ha obtain ⟨d, hd, hb⟩ := hb obtain hcd | hcd := eq_or_ne (g c) (g d) · exact hg d hd (by rwa [hcd] at ha) hb hab · exact (hs hc hd (ne_of_apply_ne _ hcd)).mono (Finset.le_sup ha) (Finset.le_sup hb) end Set namespace List variable {β : Type*} [DecidableEq α] {r : α → α → Prop} {l : List α} theorem pairwise_of_coe_toFinset_pairwise (hl : (l.toFinset : Set α).Pairwise r) (hn : l.Nodup) : l.Pairwise r := by rw [coe_toFinset] at hl exact hn.pairwise_of_set_pairwise hl theorem pairwise_iff_coe_toFinset_pairwise (hn : l.Nodup) (hs : Symmetric r) : (l.toFinset : Set α).Pairwise r ↔ l.Pairwise r := by letI : IsSymm α r := ⟨hs⟩ rw [coe_toFinset, hn.pairwise_coe] theorem pairwise_disjoint_of_coe_toFinset_pairwiseDisjoint {α ι} [SemilatticeInf α] [OrderBot α] [DecidableEq ι] {l : List ι} {f : ι → α} (hl : (l.toFinset : Set ι).PairwiseDisjoint f) (hn : l.Nodup) : l.Pairwise (_root_.Disjoint on f) := pairwise_of_coe_toFinset_pairwise hl hn theorem pairwiseDisjoint_iff_coe_toFinset_pairwise_disjoint {α ι} [SemilatticeInf α] [OrderBot α] [DecidableEq ι] {l : List ι} {f : ι → α} (hn : l.Nodup) : (l.toFinset : Set ι).PairwiseDisjoint f ↔ l.Pairwise (_root_.Disjoint on f) := pairwise_iff_coe_toFinset_pairwise hn (symmetric_disjoint.comap f) end List
Data\Finset\Pi.lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import Mathlib.Data.Finset.Card import Mathlib.Data.Multiset.Pi /-! # The cartesian product of finsets ## Main definitions * `Finset.pi`: Cartesian product of finsets indexed by a finset. -/ open Function namespace Finset open Multiset /-! ### pi -/ section Pi variable {α : Type*} /-- The empty dependent product function, defined on the empty set. The assumption `a ∈ ∅` is never satisfied. -/ def Pi.empty (β : α → Sort*) (a : α) (h : a ∈ (∅ : Finset α)) : β a := Multiset.Pi.empty β a h universe u v variable {β : α → Type u} {δ : α → Sort v} {s : Finset α} {t : ∀ a, Finset (β a)} section variable [DecidableEq α] /-- Given a finset `s` of `α` and for all `a : α` a finset `t a` of `δ a`, then one can define the finset `s.pi t` of all functions defined on elements of `s` taking values in `t a` for `a ∈ s`. Note that the elements of `s.pi t` are only partially defined, on `s`. -/ def pi (s : Finset α) (t : ∀ a, Finset (β a)) : Finset (∀ a ∈ s, β a) := ⟨s.1.pi fun a => (t a).1, s.nodup.pi fun a _ => (t a).nodup⟩ @[simp] theorem pi_val (s : Finset α) (t : ∀ a, Finset (β a)) : (s.pi t).1 = s.1.pi fun a => (t a).1 := rfl @[simp] theorem mem_pi {s : Finset α} {t : ∀ a, Finset (β a)} {f : ∀ a ∈ s, β a} : f ∈ s.pi t ↔ ∀ (a) (h : a ∈ s), f a h ∈ t a := Multiset.mem_pi _ _ _ /-- Given a function `f` defined on a finset `s`, define a new function on the finset `s ∪ {a}`, equal to `f` on `s` and sending `a` to a given value `b`. This function is denoted `s.Pi.cons a b f`. If `a` already belongs to `s`, the new function takes the value `b` at `a` anyway. -/ def Pi.cons (s : Finset α) (a : α) (b : δ a) (f : ∀ a, a ∈ s → δ a) (a' : α) (h : a' ∈ insert a s) : δ a' := Multiset.Pi.cons s.1 a b f _ (Multiset.mem_cons.2 <| mem_insert.symm.2 h) @[simp] theorem Pi.cons_same (s : Finset α) (a : α) (b : δ a) (f : ∀ a, a ∈ s → δ a) (h : a ∈ insert a s) : Pi.cons s a b f a h = b := Multiset.Pi.cons_same _ theorem Pi.cons_ne {s : Finset α} {a a' : α} {b : δ a} {f : ∀ a, a ∈ s → δ a} {h : a' ∈ insert a s} (ha : a ≠ a') : Pi.cons s a b f a' h = f a' ((mem_insert.1 h).resolve_left ha.symm) := Multiset.Pi.cons_ne _ (Ne.symm ha) theorem Pi.cons_injective {a : α} {b : δ a} {s : Finset α} (hs : a ∉ s) : Function.Injective (Pi.cons s a b) := fun e₁ e₂ eq => @Multiset.Pi.cons_injective α _ δ a b s.1 hs _ _ <| funext fun e => funext fun h => have : Pi.cons s a b e₁ e (by simpa only [Multiset.mem_cons, mem_insert] using h) = Pi.cons s a b e₂ e (by simpa only [Multiset.mem_cons, mem_insert] using h) := by rw [eq] this @[simp] theorem pi_empty {t : ∀ a : α, Finset (β a)} : pi (∅ : Finset α) t = singleton (Pi.empty β) := rfl @[simp, aesop safe apply (rule_sets := [finsetNonempty])] lemma pi_nonempty : (s.pi t).Nonempty ↔ ∀ a ∈ s, (t a).Nonempty := by simp [Finset.Nonempty, Classical.skolem] @[simp] theorem pi_insert [∀ a, DecidableEq (β a)] {s : Finset α} {t : ∀ a : α, Finset (β a)} {a : α} (ha : a ∉ s) : pi (insert a s) t = (t a).biUnion fun b => (pi s t).image (Pi.cons s a b) := by apply eq_of_veq rw [← (pi (insert a s) t).2.dedup] refine (fun s' (h : s' = a ::ₘ s.1) => (?_ : dedup (Multiset.pi s' fun a => (t a).1) = dedup ((t a).1.bind fun b => dedup <| (Multiset.pi s.1 fun a : α => (t a).val).map fun f a' h' => Multiset.Pi.cons s.1 a b f a' (h ▸ h')))) _ (insert_val_of_not_mem ha) subst s'; rw [pi_cons] congr; funext b exact ((pi s t).nodup.map <| Multiset.Pi.cons_injective ha).dedup.symm theorem pi_singletons {β : Type*} (s : Finset α) (f : α → β) : (s.pi fun a => ({f a} : Finset β)) = {fun a _ => f a} := by rw [eq_singleton_iff_unique_mem] constructor · simp intro a ha ext i hi rw [mem_pi] at ha simpa using ha i hi theorem pi_const_singleton {β : Type*} (s : Finset α) (i : β) : (s.pi fun _ => ({i} : Finset β)) = {fun _ _ => i} := pi_singletons s fun _ => i theorem pi_subset {s : Finset α} (t₁ t₂ : ∀ a, Finset (β a)) (h : ∀ a ∈ s, t₁ a ⊆ t₂ a) : s.pi t₁ ⊆ s.pi t₂ := fun _ hg => mem_pi.2 fun a ha => h a ha (mem_pi.mp hg a ha) theorem pi_disjoint_of_disjoint {δ : α → Type*} {s : Finset α} (t₁ t₂ : ∀ a, Finset (δ a)) {a : α} (ha : a ∈ s) (h : Disjoint (t₁ a) (t₂ a)) : Disjoint (s.pi t₁) (s.pi t₂) := disjoint_iff_ne.2 fun f₁ hf₁ f₂ hf₂ eq₁₂ => disjoint_iff_ne.1 h (f₁ a ha) (mem_pi.mp hf₁ a ha) (f₂ a ha) (mem_pi.mp hf₂ a ha) <| congr_fun (congr_fun eq₁₂ a) ha end /-! ### Diagonal -/ variable {ι : Type*} [DecidableEq (ι → α)] {s : Finset α} {f : ι → α} /-- The diagonal of a finset `s : Finset α` as a finset of functions `ι → α`, namely the set of constant functions valued in `s`. -/ def piDiag (s : Finset α) (ι : Type*) [DecidableEq (ι → α)] : Finset (ι → α) := s.image (const ι) @[simp] lemma mem_piDiag : f ∈ s.piDiag ι ↔ ∃ a ∈ s, const ι a = f := mem_image @[simp] lemma card_piDiag (s : Finset α) (ι : Type*) [DecidableEq (ι → α)] [Nonempty ι] : (s.piDiag ι).card = s.card := by rw [piDiag, card_image_of_injective _ const_injective] end Pi end Finset
Data\Finset\Piecewise.lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import Mathlib.Data.Fintype.Basic import Mathlib.Order.Interval.Set.Basic /-! # Functions defined piecewise on a finset This file defines `Finset.piecewise`: Given two functions `f`, `g`, `s.piecewise f g` is a function which is equal to `f` on `s` and `g` on the complement. ## TODO Should we deduplicate this from `Set.piecewise`? -/ open Function namespace Finset variable {ι : Type*} {π : ι → Sort*} (s : Finset ι) (f g : ∀ i, π i) /-- `s.piecewise f g` is the function equal to `f` on the finset `s`, and to `g` on its complement. -/ def piecewise [∀ j, Decidable (j ∈ s)] : ∀ i, π i := fun i ↦ if i ∈ s then f i else g i -- Porting note (#10618): @[simp] can prove this lemma piecewise_insert_self [DecidableEq ι] {j : ι} [∀ i, Decidable (i ∈ insert j s)] : (insert j s).piecewise f g j = f j := by simp [piecewise] @[simp] lemma piecewise_empty [∀ i : ι, Decidable (i ∈ (∅ : Finset ι))] : piecewise ∅ f g = g := by ext i simp [piecewise] variable [∀ j, Decidable (j ∈ s)] -- TODO: fix this in norm_cast @[norm_cast move] lemma piecewise_coe [∀ j, Decidable (j ∈ (s : Set ι))] : (s : Set ι).piecewise f g = s.piecewise f g := by ext congr @[simp] lemma piecewise_eq_of_mem {i : ι} (hi : i ∈ s) : s.piecewise f g i = f i := by simp [piecewise, hi] @[simp] lemma piecewise_eq_of_not_mem {i : ι} (hi : i ∉ s) : s.piecewise f g i = g i := by simp [piecewise, hi] lemma piecewise_congr {f f' g g' : ∀ i, π i} (hf : ∀ i ∈ s, f i = f' i) (hg : ∀ i ∉ s, g i = g' i) : s.piecewise f g = s.piecewise f' g' := funext fun i => if_ctx_congr Iff.rfl (hf i) (hg i) @[simp] lemma piecewise_insert_of_ne [DecidableEq ι] {i j : ι} [∀ i, Decidable (i ∈ insert j s)] (h : i ≠ j) : (insert j s).piecewise f g i = s.piecewise f g i := by simp [piecewise, h] lemma piecewise_insert [DecidableEq ι] (j : ι) [∀ i, Decidable (i ∈ insert j s)] : (insert j s).piecewise f g = update (s.piecewise f g) j (f j) := by classical simp only [← piecewise_coe, coe_insert, ← Set.piecewise_insert] ext congr simp lemma piecewise_cases {i} (p : π i → Prop) (hf : p (f i)) (hg : p (g i)) : p (s.piecewise f g i) := by by_cases hi : i ∈ s <;> simpa [hi] lemma piecewise_singleton [DecidableEq ι] (i : ι) : piecewise {i} f g = update g i (f i) := by rw [← insert_emptyc_eq, piecewise_insert, piecewise_empty] lemma piecewise_piecewise_of_subset_left {s t : Finset ι} [∀ i, Decidable (i ∈ s)] [∀ i, Decidable (i ∈ t)] (h : s ⊆ t) (f₁ f₂ g : ∀ a, π a) : s.piecewise (t.piecewise f₁ f₂) g = s.piecewise f₁ g := s.piecewise_congr (fun _i hi => piecewise_eq_of_mem _ _ _ (h hi)) fun _ _ => rfl @[simp] lemma piecewise_idem_left (f₁ f₂ g : ∀ a, π a) : s.piecewise (s.piecewise f₁ f₂) g = s.piecewise f₁ g := piecewise_piecewise_of_subset_left (Subset.refl _) _ _ _ lemma piecewise_piecewise_of_subset_right {s t : Finset ι} [∀ i, Decidable (i ∈ s)] [∀ i, Decidable (i ∈ t)] (h : t ⊆ s) (f g₁ g₂ : ∀ a, π a) : s.piecewise f (t.piecewise g₁ g₂) = s.piecewise f g₂ := s.piecewise_congr (fun _ _ => rfl) fun _i hi => t.piecewise_eq_of_not_mem _ _ (mt (@h _) hi) @[simp] lemma piecewise_idem_right (f g₁ g₂ : ∀ a, π a) : s.piecewise f (s.piecewise g₁ g₂) = s.piecewise f g₂ := piecewise_piecewise_of_subset_right (Subset.refl _) f g₁ g₂ lemma update_eq_piecewise {β : Type*} [DecidableEq ι] (f : ι → β) (i : ι) (v : β) : update f i v = piecewise (singleton i) (fun _ => v) f := (piecewise_singleton (fun _ => v) _ _).symm lemma update_piecewise [DecidableEq ι] (i : ι) (v : π i) : update (s.piecewise f g) i v = s.piecewise (update f i v) (update g i v) := by ext j rcases em (j = i) with (rfl | hj) <;> by_cases hs : j ∈ s <;> simp [*] lemma update_piecewise_of_mem [DecidableEq ι] {i : ι} (hi : i ∈ s) (v : π i) : update (s.piecewise f g) i v = s.piecewise (update f i v) g := by rw [update_piecewise] refine s.piecewise_congr (fun _ _ => rfl) fun j hj => update_noteq ?_ _ _ exact fun h => hj (h.symm ▸ hi) lemma update_piecewise_of_not_mem [DecidableEq ι] {i : ι} (hi : i ∉ s) (v : π i) : update (s.piecewise f g) i v = s.piecewise f (update g i v) := by rw [update_piecewise] refine s.piecewise_congr (fun j hj => update_noteq ?_ _ _) fun _ _ => rfl exact fun h => hi (h ▸ hj) lemma piecewise_same : s.piecewise f f = f := by ext i by_cases h : i ∈ s <;> simp [h] section Fintype variable [Fintype ι] @[simp] lemma piecewise_univ [∀ i, Decidable (i ∈ (univ : Finset ι))] (f g : ∀ i, π i) : univ.piecewise f g = f := by ext i simp [piecewise] lemma piecewise_compl [DecidableEq ι] (s : Finset ι) [∀ i, Decidable (i ∈ s)] [∀ i, Decidable (i ∈ sᶜ)] (f g : ∀ i, π i) : sᶜ.piecewise f g = s.piecewise g f := by ext i simp [piecewise] @[simp] lemma piecewise_erase_univ [DecidableEq ι] (i : ι) (f g : ∀ i, π i) : (Finset.univ.erase i).piecewise f g = Function.update f i (g i) := by rw [← compl_singleton, piecewise_compl, piecewise_singleton] end Fintype variable {π : ι → Type*} {t : Set ι} {t' : ∀ i, Set (π i)} {f g f' g' h : ∀ i, π i} lemma piecewise_mem_set_pi (hf : f ∈ Set.pi t t') (hg : g ∈ Set.pi t t') : s.piecewise f g ∈ Set.pi t t' := by classical rw [← piecewise_coe]; exact Set.piecewise_mem_pi (↑s) hf hg variable [∀ i, Preorder (π i)] lemma piecewise_le_of_le_of_le (hf : f ≤ h) (hg : g ≤ h) : s.piecewise f g ≤ h := fun x => piecewise_cases s f g (· ≤ h x) (hf x) (hg x) lemma le_piecewise_of_le_of_le (hf : h ≤ f) (hg : h ≤ g) : h ≤ s.piecewise f g := fun x => piecewise_cases s f g (fun y => h x ≤ y) (hf x) (hg x) lemma piecewise_le_piecewise' (hf : ∀ x ∈ s, f x ≤ f' x) (hg : ∀ x ∉ s, g x ≤ g' x) : s.piecewise f g ≤ s.piecewise f' g' := fun x => by by_cases hx : x ∈ s <;> simp [hx, *] lemma piecewise_le_piecewise (hf : f ≤ f') (hg : g ≤ g') : s.piecewise f g ≤ s.piecewise f' g' := s.piecewise_le_piecewise' (fun x _ => hf x) fun x _ => hg x lemma piecewise_mem_Icc_of_mem_of_mem (hf : f ∈ Set.Icc f' g') (hg : g ∈ Set.Icc f' g') : s.piecewise f g ∈ Set.Icc f' g' := ⟨le_piecewise_of_le_of_le _ hf.1 hg.1, piecewise_le_of_le_of_le _ hf.2 hg.2⟩ lemma piecewise_mem_Icc (h : f ≤ g) : s.piecewise f g ∈ Set.Icc f g := piecewise_mem_Icc_of_mem_of_mem _ (Set.left_mem_Icc.2 h) (Set.right_mem_Icc.2 h) lemma piecewise_mem_Icc' (h : g ≤ f) : s.piecewise f g ∈ Set.Icc g f := piecewise_mem_Icc_of_mem_of_mem _ (Set.right_mem_Icc.2 h) (Set.left_mem_Icc.2 h) end Finset
Data\Finset\PiInduction.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.Data.Finset.Sigma import Mathlib.Data.Fintype.Card /-! # Induction principles for `∀ i, Finset (α i)` In this file we prove a few induction principles for functions `Π i : ι, Finset (α i)` defined on a finite type. * `Finset.induction_on_pi` is a generic lemma that requires only `[Finite ι]`, `[DecidableEq ι]`, and `[∀ i, DecidableEq (α i)]`; this version can be seen as a direct generalization of `Finset.induction_on`. * `Finset.induction_on_pi_max` and `Finset.induction_on_pi_min`: generalizations of `Finset.induction_on_max`; these versions require `∀ i, LinearOrder (α i)` but assume `∀ y ∈ g i, y < x` and `∀ y ∈ g i, x < y` respectively in the induction step. ## Tags finite set, finite type, induction, function -/ open Function variable {ι : Type*} {α : ι → Type*} [Finite ι] [DecidableEq ι] [∀ i, DecidableEq (α i)] namespace Finset /-- General theorem for `Finset.induction_on_pi`-style induction principles. -/ theorem induction_on_pi_of_choice (r : ∀ i, α i → Finset (α i) → Prop) (H_ex : ∀ (i) (s : Finset (α i)), s.Nonempty → ∃ x ∈ s, r i x (s.erase x)) {p : (∀ i, Finset (α i)) → Prop} (f : ∀ i, Finset (α i)) (h0 : p fun _ ↦ ∅) (step : ∀ (g : ∀ i, Finset (α i)) (i : ι) (x : α i), r i x (g i) → p g → p (update g i (insert x (g i)))) : p f := by cases nonempty_fintype ι induction' hs : univ.sigma f using Finset.strongInductionOn with s ihs generalizing f; subst s rcases eq_empty_or_nonempty (univ.sigma f) with he | hne · convert h0 using 1 simpa [funext_iff] using he · rcases sigma_nonempty.1 hne with ⟨i, -, hi⟩ rcases H_ex i (f i) hi with ⟨x, x_mem, hr⟩ set g := update f i ((f i).erase x) with hg clear_value g have hx' : x ∉ g i := by rw [hg, update_same] apply not_mem_erase rw [show f = update g i (insert x (g i)) by rw [hg, update_idem, update_same, insert_erase x_mem, update_eq_self]] at hr ihs ⊢ clear hg rw [update_same, erase_insert hx'] at hr refine step _ _ _ hr (ihs (univ.sigma g) ?_ _ rfl) rw [ssubset_iff_of_subset (sigma_mono (Subset.refl _) _)] exacts [⟨⟨i, x⟩, mem_sigma.2 ⟨mem_univ _, by simp⟩, by simp [hx']⟩, (@le_update_iff _ _ _ _ g g i _).2 ⟨subset_insert _ _, fun _ _ ↦ le_rfl⟩] /-- Given a predicate on functions `∀ i, Finset (α i)` defined on a finite type, it is true on all maps provided that it is true on `fun _ ↦ ∅` and for any function `g : ∀ i, Finset (α i)`, an index `i : ι`, and `x ∉ g i`, `p g` implies `p (update g i (insert x (g i)))`. See also `Finset.induction_on_pi_max` and `Finset.induction_on_pi_min` for specialized versions that require `∀ i, LinearOrder (α i)`. -/ theorem induction_on_pi {p : (∀ i, Finset (α i)) → Prop} (f : ∀ i, Finset (α i)) (h0 : p fun _ ↦ ∅) (step : ∀ (g : ∀ i, Finset (α i)) (i : ι), ∀ x ∉ g i, p g → p (update g i (insert x (g i)))) : p f := induction_on_pi_of_choice (fun _ x s ↦ x ∉ s) (fun _ s ⟨x, hx⟩ ↦ ⟨x, hx, not_mem_erase x s⟩) f h0 step -- Porting note: this docstring is the exact translation of the one from mathlib3 but -- the last sentence (here and in the next lemma) does make much sense to me... /-- Given a predicate on functions `∀ i, Finset (α i)` defined on a finite type, it is true on all maps provided that it is true on `fun _ ↦ ∅` and for any function `g : ∀ i, Finset (α i)`, an index `i : ι`, and an element`x : α i` that is strictly greater than all elements of `g i`, `p g` implies `p (update g i (insert x (g i)))`. This lemma requires `LinearOrder` instances on all `α i`. See also `Finset.induction_on_pi` for a version that `x ∉ g i` instead of ` does not need `∀ i, LinearOrder (α i)`. -/ theorem induction_on_pi_max [∀ i, LinearOrder (α i)] {p : (∀ i, Finset (α i)) → Prop} (f : ∀ i, Finset (α i)) (h0 : p fun _ ↦ ∅) (step : ∀ (g : ∀ i, Finset (α i)) (i : ι) (x : α i), (∀ y ∈ g i, y < x) → p g → p (update g i (insert x (g i)))) : p f := induction_on_pi_of_choice (fun _ x s ↦ ∀ y ∈ s, y < x) (fun _ s hs ↦ ⟨s.max' hs, s.max'_mem hs, fun _ ↦ s.lt_max'_of_mem_erase_max' _⟩) f h0 step /-- Given a predicate on functions `∀ i, Finset (α i)` defined on a finite type, it is true on all maps provided that it is true on `fun _ ↦ ∅` and for any function `g : ∀ i, Finset (α i)`, an index `i : ι`, and an element`x : α i` that is strictly less than all elements of `g i`, `p g` implies `p (update g i (insert x (g i)))`. This lemma requires `LinearOrder` instances on all `α i`. See also `Finset.induction_on_pi` for a version that `x ∉ g i` instead of ` does not need `∀ i, LinearOrder (α i)`. -/ theorem induction_on_pi_min [∀ i, LinearOrder (α i)] {p : (∀ i, Finset (α i)) → Prop} (f : ∀ i, Finset (α i)) (h0 : p fun _ ↦ ∅) (step : ∀ (g : ∀ i, Finset (α i)) (i : ι) (x : α i), (∀ y ∈ g i, x < y) → p g → p (update g i (insert x (g i)))) : p f := induction_on_pi_max (α := fun i ↦ (α i)ᵒᵈ) _ h0 step end Finset
Data\Finset\PImage.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.Data.Finset.Option import Mathlib.Data.PFun import Mathlib.Data.Part /-! # Image of a `Finset α` under a partially defined function In this file we define `Part.toFinset` and `Finset.pimage`. We also prove some trivial lemmas about these definitions. ## Tags finite set, image, partial function -/ variable {α β : Type*} namespace Part /-- Convert an `o : Part α` with decidable `Part.Dom o` to `Finset α`. -/ def toFinset (o : Part α) [Decidable o.Dom] : Finset α := o.toOption.toFinset @[simp] theorem mem_toFinset {o : Part α} [Decidable o.Dom] {x : α} : x ∈ o.toFinset ↔ x ∈ o := by simp [toFinset] @[simp] theorem toFinset_none [Decidable (none : Part α).Dom] : none.toFinset = (∅ : Finset α) := by simp [toFinset] @[simp] theorem toFinset_some {a : α} [Decidable (some a).Dom] : (some a).toFinset = {a} := by simp [toFinset] @[simp] theorem coe_toFinset (o : Part α) [Decidable o.Dom] : (o.toFinset : Set α) = { x | x ∈ o } := Set.ext fun _ => mem_toFinset end Part namespace Finset variable [DecidableEq β] {f g : α →. β} [∀ x, Decidable (f x).Dom] [∀ x, Decidable (g x).Dom] {s t : Finset α} {b : β} /-- Image of `s : Finset α` under a partially defined function `f : α →. β`. -/ def pimage (f : α →. β) [∀ x, Decidable (f x).Dom] (s : Finset α) : Finset β := s.biUnion fun x => (f x).toFinset @[simp] theorem mem_pimage : b ∈ s.pimage f ↔ ∃ a ∈ s, b ∈ f a := by simp [pimage] @[simp, norm_cast] theorem coe_pimage : (s.pimage f : Set β) = f.image s := Set.ext fun _ => mem_pimage @[simp] theorem pimage_some (s : Finset α) (f : α → β) [∀ x, Decidable (Part.some <| f x).Dom] : (s.pimage fun x => Part.some (f x)) = s.image f := by ext simp [eq_comm] theorem pimage_congr (h₁ : s = t) (h₂ : ∀ x ∈ t, f x = g x) : s.pimage f = t.pimage g := by subst s ext y -- Porting note: `← exists_prop` required because `∃ x ∈ s, p x` is defined differently simp (config := { contextual := true }) only [mem_pimage, ← exists_prop, h₂] /-- Rewrite `s.pimage f` in terms of `Finset.filter`, `Finset.attach`, and `Finset.image`. -/ theorem pimage_eq_image_filter : s.pimage f = (filter (fun x => (f x).Dom) s).attach.image fun x : { x // x ∈ filter (fun x => (f x).Dom) s } => (f x).get (mem_filter.mp x.coe_prop).2 := by ext x simp [Part.mem_eq, And.exists] -- Porting note: `← exists_prop` required because `∃ x ∈ s, p x` is defined differently simp only [← exists_prop] theorem pimage_union [DecidableEq α] : (s ∪ t).pimage f = s.pimage f ∪ t.pimage f := coe_inj.1 <| by simp only [coe_pimage, coe_union, ← PFun.image_union] @[simp] theorem pimage_empty : pimage f ∅ = ∅ := by ext simp theorem pimage_subset {t : Finset β} : s.pimage f ⊆ t ↔ ∀ x ∈ s, ∀ y ∈ f x, y ∈ t := by simp [subset_iff, @forall_swap _ β] @[mono] theorem pimage_mono (h : s ⊆ t) : s.pimage f ⊆ t.pimage f := pimage_subset.2 fun x hx _ hy => mem_pimage.2 ⟨x, h hx, hy⟩ theorem pimage_inter [DecidableEq α] : (s ∩ t).pimage f ⊆ s.pimage f ∩ t.pimage f := by simp only [← coe_subset, coe_pimage, coe_inter, PFun.image_inter] end Finset
Data\Finset\Pointwise.lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Yaël Dillies -/ import Mathlib.Algebra.Group.Action.Pi import Mathlib.Data.Finset.NAry import Mathlib.Data.Finset.Preimage import Mathlib.Data.Set.Pointwise.Finite import Mathlib.Data.Set.Pointwise.SMul import Mathlib.Data.Set.Pointwise.ListOfFn import Mathlib.SetTheory.Cardinal.Finite /-! # Pointwise operations of finsets This file defines pointwise algebraic operations on finsets. ## Main declarations For finsets `s` and `t`: * `0` (`Finset.zero`): The singleton `{0}`. * `1` (`Finset.one`): The singleton `{1}`. * `-s` (`Finset.neg`): Negation, finset of all `-x` where `x ∈ s`. * `s⁻¹` (`Finset.inv`): Inversion, finset of all `x⁻¹` where `x ∈ s`. * `s + t` (`Finset.add`): Addition, finset of all `x + y` where `x ∈ s` and `y ∈ t`. * `s * t` (`Finset.mul`): Multiplication, finset of all `x * y` where `x ∈ s` and `y ∈ t`. * `s - t` (`Finset.sub`): Subtraction, finset of all `x - y` where `x ∈ s` and `y ∈ t`. * `s / t` (`Finset.div`): Division, finset of all `x / y` where `x ∈ s` and `y ∈ t`. * `s +ᵥ t` (`Finset.vadd`): Scalar addition, finset of all `x +ᵥ y` where `x ∈ s` and `y ∈ t`. * `s • t` (`Finset.smul`): Scalar multiplication, finset of all `x • y` where `x ∈ s` and `y ∈ t`. * `s -ᵥ t` (`Finset.vsub`): Scalar subtraction, finset of all `x -ᵥ y` where `x ∈ s` and `y ∈ t`. * `a • s` (`Finset.smulFinset`): Scaling, finset of all `a • x` where `x ∈ s`. * `a +ᵥ s` (`Finset.vaddFinset`): Translation, finset of all `a +ᵥ x` where `x ∈ s`. For `α` a semigroup/monoid, `Finset α` is a semigroup/monoid. As an unfortunate side effect, this means that `n • s`, where `n : ℕ`, is ambiguous between pointwise scaling and repeated pointwise addition; the former has `(2 : ℕ) • {1, 2} = {2, 4}`, while the latter has `(2 : ℕ) • {1, 2} = {2, 3, 4}`. See note [pointwise nat action]. ## Implementation notes We put all instances in the locale `Pointwise`, so that these instances are not available by default. Note that we do not mark them as reducible (as argued by note [reducible non-instances]) since we expect the locale to be open whenever the instances are actually used (and making the instances reducible changes the behavior of `simp`. ## Tags finset multiplication, finset addition, pointwise addition, pointwise multiplication, pointwise subtraction -/ open Function MulOpposite open scoped Pointwise variable {F α β γ : Type*} namespace Finset /-! ### `0`/`1` as finsets -/ section One variable [One α] {s : Finset α} {a : α} /-- The finset `1 : Finset α` is defined as `{1}` in locale `Pointwise`. -/ @[to_additive "The finset `0 : Finset α` is defined as `{0}` in locale `Pointwise`."] protected def one : One (Finset α) := ⟨{1}⟩ scoped[Pointwise] attribute [instance] Finset.one Finset.zero @[to_additive (attr := simp)] theorem mem_one : a ∈ (1 : Finset α) ↔ a = 1 := mem_singleton @[to_additive (attr := simp, norm_cast)] theorem coe_one : ↑(1 : Finset α) = (1 : Set α) := coe_singleton 1 @[to_additive (attr := simp, norm_cast)] lemma coe_eq_one : (s : Set α) = 1 ↔ s = 1 := coe_eq_singleton @[to_additive (attr := simp)] theorem one_subset : (1 : Finset α) ⊆ s ↔ (1 : α) ∈ s := singleton_subset_iff @[to_additive] theorem singleton_one : ({1} : Finset α) = 1 := rfl @[to_additive] theorem one_mem_one : (1 : α) ∈ (1 : Finset α) := mem_singleton_self _ @[to_additive (attr := simp, aesop safe apply (rule_sets := [finsetNonempty]))] theorem one_nonempty : (1 : Finset α).Nonempty := ⟨1, one_mem_one⟩ @[to_additive (attr := simp)] protected theorem map_one {f : α ↪ β} : map f 1 = {f 1} := map_singleton f 1 @[to_additive (attr := simp)] theorem image_one [DecidableEq β] {f : α → β} : image f 1 = {f 1} := image_singleton _ _ @[to_additive] theorem subset_one_iff_eq : s ⊆ 1 ↔ s = ∅ ∨ s = 1 := subset_singleton_iff @[to_additive] theorem Nonempty.subset_one_iff (h : s.Nonempty) : s ⊆ 1 ↔ s = 1 := h.subset_singleton_iff @[to_additive (attr := simp)] theorem card_one : (1 : Finset α).card = 1 := card_singleton _ /-- The singleton operation as a `OneHom`. -/ @[to_additive "The singleton operation as a `ZeroHom`."] def singletonOneHom : OneHom α (Finset α) where toFun := singleton; map_one' := singleton_one @[to_additive (attr := simp)] theorem coe_singletonOneHom : (singletonOneHom : α → Finset α) = singleton := rfl @[to_additive (attr := simp)] theorem singletonOneHom_apply (a : α) : singletonOneHom a = {a} := rfl /-- Lift a `OneHom` to `Finset` via `image`. -/ @[to_additive (attr := simps) "Lift a `ZeroHom` to `Finset` via `image`"] def imageOneHom [DecidableEq β] [One β] [FunLike F α β] [OneHomClass F α β] (f : F) : OneHom (Finset α) (Finset β) where toFun := Finset.image f map_one' := by rw [image_one, map_one, singleton_one] @[to_additive (attr := simp)] lemma sup_one [SemilatticeSup β] [OrderBot β] (f : α → β) : sup 1 f = f 1 := sup_singleton @[to_additive (attr := simp)] lemma sup'_one [SemilatticeSup β] (f : α → β) : sup' 1 one_nonempty f = f 1 := rfl @[to_additive (attr := simp)] lemma inf_one [SemilatticeInf β] [OrderTop β] (f : α → β) : inf 1 f = f 1 := inf_singleton @[to_additive (attr := simp)] lemma inf'_one [SemilatticeInf β] (f : α → β) : inf' 1 one_nonempty f = f 1 := rfl @[to_additive (attr := simp)] lemma max_one [LinearOrder α] : (1 : Finset α).max = 1 := rfl @[to_additive (attr := simp)] lemma min_one [LinearOrder α] : (1 : Finset α).min = 1 := rfl @[to_additive (attr := simp)] lemma max'_one [LinearOrder α] : (1 : Finset α).max' one_nonempty = 1 := rfl @[to_additive (attr := simp)] lemma min'_one [LinearOrder α] : (1 : Finset α).min' one_nonempty = 1 := rfl end One /-! ### Finset negation/inversion -/ section Inv variable [DecidableEq α] [Inv α] {s s₁ s₂ t t₁ t₂ u : Finset α} {a b : α} /-- The pointwise inversion of finset `s⁻¹` is defined as `{x⁻¹ | x ∈ s}` in locale `Pointwise`. -/ @[to_additive "The pointwise negation of finset `-s` is defined as `{-x | x ∈ s}` in locale `Pointwise`."] protected def inv : Inv (Finset α) := ⟨image Inv.inv⟩ scoped[Pointwise] attribute [instance] Finset.inv Finset.neg @[to_additive] theorem inv_def : s⁻¹ = s.image fun x => x⁻¹ := rfl @[to_additive] theorem image_inv : (s.image fun x => x⁻¹) = s⁻¹ := rfl @[to_additive] theorem mem_inv {x : α} : x ∈ s⁻¹ ↔ ∃ y ∈ s, y⁻¹ = x := mem_image @[to_additive] theorem inv_mem_inv (ha : a ∈ s) : a⁻¹ ∈ s⁻¹ := mem_image_of_mem _ ha @[to_additive] theorem card_inv_le : s⁻¹.card ≤ s.card := card_image_le @[to_additive (attr := simp)] theorem inv_empty : (∅ : Finset α)⁻¹ = ∅ := image_empty _ @[to_additive (attr := simp, aesop safe apply (rule_sets := [finsetNonempty]))] theorem inv_nonempty_iff : s⁻¹.Nonempty ↔ s.Nonempty := image_nonempty alias ⟨Nonempty.of_inv, Nonempty.inv⟩ := inv_nonempty_iff attribute [to_additive] Nonempty.inv Nonempty.of_inv @[to_additive (attr := simp)] theorem inv_eq_empty : s⁻¹ = ∅ ↔ s = ∅ := image_eq_empty @[to_additive (attr := mono)] theorem inv_subset_inv (h : s ⊆ t) : s⁻¹ ⊆ t⁻¹ := image_subset_image h @[to_additive (attr := simp)] theorem inv_singleton (a : α) : ({a} : Finset α)⁻¹ = {a⁻¹} := image_singleton _ _ @[to_additive (attr := simp)] theorem inv_insert (a : α) (s : Finset α) : (insert a s)⁻¹ = insert a⁻¹ s⁻¹ := image_insert _ _ _ @[to_additive (attr := simp)] lemma sup_inv [SemilatticeSup β] [OrderBot β] (s : Finset α) (f : α → β) : sup s⁻¹ f = sup s (f ·⁻¹) := sup_image .. @[to_additive (attr := simp)] lemma sup'_inv [SemilatticeSup β] {s : Finset α} (hs : s⁻¹.Nonempty) (f : α → β) : sup' s⁻¹ hs f = sup' s hs.of_inv (f ·⁻¹) := sup'_image .. @[to_additive (attr := simp)] lemma inf_inv [SemilatticeInf β] [OrderTop β] (s : Finset α) (f : α → β) : inf s⁻¹ f = inf s (f ·⁻¹) := inf_image .. @[to_additive (attr := simp)] lemma inf'_inv [SemilatticeInf β] {s : Finset α} (hs : s⁻¹.Nonempty) (f : α → β) : inf' s⁻¹ hs f = inf' s hs.of_inv (f ·⁻¹) := inf'_image .. @[to_additive] lemma image_op_inv (s : Finset α) : s⁻¹.image op = (s.image op)⁻¹ := image_comm op_inv end Inv open Pointwise section InvolutiveInv variable [DecidableEq α] [InvolutiveInv α] {s : Finset α} {a : α} @[to_additive (attr := simp)] lemma mem_inv' : a ∈ s⁻¹ ↔ a⁻¹ ∈ s := by simp [mem_inv, inv_eq_iff_eq_inv] @[to_additive (attr := simp, norm_cast)] theorem coe_inv (s : Finset α) : ↑s⁻¹ = (s : Set α)⁻¹ := coe_image.trans Set.image_inv @[to_additive (attr := simp)] theorem card_inv (s : Finset α) : s⁻¹.card = s.card := card_image_of_injective _ inv_injective @[to_additive (attr := simp)] theorem preimage_inv (s : Finset α) : s.preimage (·⁻¹) inv_injective.injOn = s⁻¹ := coe_injective <| by rw [coe_preimage, Set.inv_preimage, coe_inv] @[to_additive (attr := simp)] lemma inv_univ [Fintype α] : (univ : Finset α)⁻¹ = univ := by ext; simp @[to_additive (attr := simp)] lemma inv_inter (s t : Finset α) : (s ∩ t)⁻¹ = s⁻¹ ∩ t⁻¹ := coe_injective <| by simp end InvolutiveInv /-! ### Finset addition/multiplication -/ section Mul variable [DecidableEq α] [Mul α] [Mul β] [FunLike F α β] [MulHomClass F α β] (f : F) {s s₁ s₂ t t₁ t₂ u : Finset α} {a b : α} /-- The pointwise multiplication of finsets `s * t` and `t` is defined as `{x * y | x ∈ s, y ∈ t}` in locale `Pointwise`. -/ @[to_additive "The pointwise addition of finsets `s + t` is defined as `{x + y | x ∈ s, y ∈ t}` in locale `Pointwise`."] protected def mul : Mul (Finset α) := ⟨image₂ (· * ·)⟩ scoped[Pointwise] attribute [instance] Finset.mul Finset.add @[to_additive] theorem mul_def : s * t = (s ×ˢ t).image fun p : α × α => p.1 * p.2 := rfl @[to_additive] theorem image_mul_product : ((s ×ˢ t).image fun x : α × α => x.fst * x.snd) = s * t := rfl @[to_additive] theorem mem_mul {x : α} : x ∈ s * t ↔ ∃ y ∈ s, ∃ z ∈ t, y * z = x := mem_image₂ @[to_additive (attr := simp, norm_cast)] theorem coe_mul (s t : Finset α) : (↑(s * t) : Set α) = ↑s * ↑t := coe_image₂ _ _ _ @[to_additive] theorem mul_mem_mul : a ∈ s → b ∈ t → a * b ∈ s * t := mem_image₂_of_mem @[to_additive] theorem card_mul_le : (s * t).card ≤ s.card * t.card := card_image₂_le _ _ _ @[to_additive] theorem card_mul_iff : (s * t).card = s.card * t.card ↔ (s ×ˢ t : Set (α × α)).InjOn fun p => p.1 * p.2 := card_image₂_iff @[to_additive (attr := simp)] theorem empty_mul (s : Finset α) : ∅ * s = ∅ := image₂_empty_left @[to_additive (attr := simp)] theorem mul_empty (s : Finset α) : s * ∅ = ∅ := image₂_empty_right @[to_additive (attr := simp)] theorem mul_eq_empty : s * t = ∅ ↔ s = ∅ ∨ t = ∅ := image₂_eq_empty_iff @[to_additive (attr := simp, aesop safe apply (rule_sets := [finsetNonempty]))] theorem mul_nonempty : (s * t).Nonempty ↔ s.Nonempty ∧ t.Nonempty := image₂_nonempty_iff @[to_additive] theorem Nonempty.mul : s.Nonempty → t.Nonempty → (s * t).Nonempty := Nonempty.image₂ @[to_additive] theorem Nonempty.of_mul_left : (s * t).Nonempty → s.Nonempty := Nonempty.of_image₂_left @[to_additive] theorem Nonempty.of_mul_right : (s * t).Nonempty → t.Nonempty := Nonempty.of_image₂_right @[to_additive] theorem mul_singleton (a : α) : s * {a} = s.image (· * a) := image₂_singleton_right @[to_additive] theorem singleton_mul (a : α) : {a} * s = s.image (a * ·) := image₂_singleton_left @[to_additive (attr := simp)] theorem singleton_mul_singleton (a b : α) : ({a} : Finset α) * {b} = {a * b} := image₂_singleton @[to_additive (attr := mono)] theorem mul_subset_mul : s₁ ⊆ s₂ → t₁ ⊆ t₂ → s₁ * t₁ ⊆ s₂ * t₂ := image₂_subset @[to_additive] theorem mul_subset_mul_left : t₁ ⊆ t₂ → s * t₁ ⊆ s * t₂ := image₂_subset_left @[to_additive] theorem mul_subset_mul_right : s₁ ⊆ s₂ → s₁ * t ⊆ s₂ * t := image₂_subset_right @[to_additive] theorem mul_subset_iff : s * t ⊆ u ↔ ∀ x ∈ s, ∀ y ∈ t, x * y ∈ u := image₂_subset_iff @[to_additive] theorem union_mul : (s₁ ∪ s₂) * t = s₁ * t ∪ s₂ * t := image₂_union_left @[to_additive] theorem mul_union : s * (t₁ ∪ t₂) = s * t₁ ∪ s * t₂ := image₂_union_right @[to_additive] theorem inter_mul_subset : s₁ ∩ s₂ * t ⊆ s₁ * t ∩ (s₂ * t) := image₂_inter_subset_left @[to_additive] theorem mul_inter_subset : s * (t₁ ∩ t₂) ⊆ s * t₁ ∩ (s * t₂) := image₂_inter_subset_right @[to_additive] theorem inter_mul_union_subset_union : s₁ ∩ s₂ * (t₁ ∪ t₂) ⊆ s₁ * t₁ ∪ s₂ * t₂ := image₂_inter_union_subset_union @[to_additive] theorem union_mul_inter_subset_union : (s₁ ∪ s₂) * (t₁ ∩ t₂) ⊆ s₁ * t₁ ∪ s₂ * t₂ := image₂_union_inter_subset_union /-- If a finset `u` is contained in the product of two sets `s * t`, we can find two finsets `s'`, `t'` such that `s' ⊆ s`, `t' ⊆ t` and `u ⊆ s' * t'`. -/ @[to_additive "If a finset `u` is contained in the sum of two sets `s + t`, we can find two finsets `s'`, `t'` such that `s' ⊆ s`, `t' ⊆ t` and `u ⊆ s' + t'`."] theorem subset_mul {s t : Set α} : ↑u ⊆ s * t → ∃ s' t' : Finset α, ↑s' ⊆ s ∧ ↑t' ⊆ t ∧ u ⊆ s' * t' := subset_image₂ @[to_additive] theorem image_mul [DecidableEq β] : (s * t).image (f : α → β) = s.image f * t.image f := image_image₂_distrib <| map_mul f /-- The singleton operation as a `MulHom`. -/ @[to_additive "The singleton operation as an `AddHom`."] def singletonMulHom : α →ₙ* Finset α where toFun := singleton; map_mul' _ _ := (singleton_mul_singleton _ _).symm @[to_additive (attr := simp)] theorem coe_singletonMulHom : (singletonMulHom : α → Finset α) = singleton := rfl @[to_additive (attr := simp)] theorem singletonMulHom_apply (a : α) : singletonMulHom a = {a} := rfl /-- Lift a `MulHom` to `Finset` via `image`. -/ @[to_additive (attr := simps) "Lift an `AddHom` to `Finset` via `image`"] def imageMulHom [DecidableEq β] : Finset α →ₙ* Finset β where toFun := Finset.image f map_mul' _ _ := image_mul _ @[to_additive (attr := simp (default + 1))] lemma sup_mul_le {β} [SemilatticeSup β] [OrderBot β] {s t : Finset α} {f : α → β} {a : β} : sup (s * t) f ≤ a ↔ ∀ x ∈ s, ∀ y ∈ t, f (x * y) ≤ a := sup_image₂_le @[to_additive] lemma sup_mul_left {β} [SemilatticeSup β] [OrderBot β] (s t : Finset α) (f : α → β) : sup (s * t) f = sup s fun x ↦ sup t (f <| x * ·) := sup_image₂_left .. @[to_additive] lemma sup_mul_right {β} [SemilatticeSup β] [OrderBot β] (s t : Finset α) (f : α → β) : sup (s * t) f = sup t fun y ↦ sup s (f <| · * y) := sup_image₂_right .. @[to_additive (attr := simp (default + 1))] lemma le_inf_mul {β} [SemilatticeInf β] [OrderTop β] {s t : Finset α} {f : α → β} {a : β} : a ≤ inf (s * t) f ↔ ∀ x ∈ s, ∀ y ∈ t, a ≤ f (x * y) := le_inf_image₂ @[to_additive] lemma inf_mul_left {β} [SemilatticeInf β] [OrderTop β] (s t : Finset α) (f : α → β) : inf (s * t) f = inf s fun x ↦ inf t (f <| x * ·) := inf_image₂_left .. @[to_additive] lemma inf_mul_right {β} [SemilatticeInf β] [OrderTop β] (s t : Finset α) (f : α → β) : inf (s * t) f = inf t fun y ↦ inf s (f <| · * y) := inf_image₂_right .. end Mul /-! ### Finset subtraction/division -/ section Div variable [DecidableEq α] [Div α] {s s₁ s₂ t t₁ t₂ u : Finset α} {a b : α} /-- The pointwise division of finsets `s / t` is defined as `{x / y | x ∈ s, y ∈ t}` in locale `Pointwise`. -/ @[to_additive "The pointwise subtraction of finsets `s - t` is defined as `{x - y | x ∈ s, y ∈ t}` in locale `Pointwise`."] protected def div : Div (Finset α) := ⟨image₂ (· / ·)⟩ scoped[Pointwise] attribute [instance] Finset.div Finset.sub @[to_additive] theorem div_def : s / t = (s ×ˢ t).image fun p : α × α => p.1 / p.2 := rfl @[to_additive] theorem image_div_product : ((s ×ˢ t).image fun x : α × α => x.fst / x.snd) = s / t := rfl @[to_additive] theorem mem_div : a ∈ s / t ↔ ∃ b ∈ s, ∃ c ∈ t, b / c = a := mem_image₂ @[to_additive (attr := simp, norm_cast)] theorem coe_div (s t : Finset α) : (↑(s / t) : Set α) = ↑s / ↑t := coe_image₂ _ _ _ @[to_additive] theorem div_mem_div : a ∈ s → b ∈ t → a / b ∈ s / t := mem_image₂_of_mem @[to_additive] theorem div_card_le : (s / t).card ≤ s.card * t.card := card_image₂_le _ _ _ @[to_additive (attr := simp)] theorem empty_div (s : Finset α) : ∅ / s = ∅ := image₂_empty_left @[to_additive (attr := simp)] theorem div_empty (s : Finset α) : s / ∅ = ∅ := image₂_empty_right @[to_additive (attr := simp)] theorem div_eq_empty : s / t = ∅ ↔ s = ∅ ∨ t = ∅ := image₂_eq_empty_iff @[to_additive (attr := simp, aesop safe apply (rule_sets := [finsetNonempty]))] theorem div_nonempty : (s / t).Nonempty ↔ s.Nonempty ∧ t.Nonempty := image₂_nonempty_iff @[to_additive] theorem Nonempty.div : s.Nonempty → t.Nonempty → (s / t).Nonempty := Nonempty.image₂ @[to_additive] theorem Nonempty.of_div_left : (s / t).Nonempty → s.Nonempty := Nonempty.of_image₂_left @[to_additive] theorem Nonempty.of_div_right : (s / t).Nonempty → t.Nonempty := Nonempty.of_image₂_right @[to_additive (attr := simp)] theorem div_singleton (a : α) : s / {a} = s.image (· / a) := image₂_singleton_right @[to_additive (attr := simp)] theorem singleton_div (a : α) : {a} / s = s.image (a / ·) := image₂_singleton_left -- @[to_additive (attr := simp)] -- Porting note (#10618): simp can prove this & the additive version @[to_additive] theorem singleton_div_singleton (a b : α) : ({a} : Finset α) / {b} = {a / b} := image₂_singleton @[to_additive (attr := mono)] theorem div_subset_div : s₁ ⊆ s₂ → t₁ ⊆ t₂ → s₁ / t₁ ⊆ s₂ / t₂ := image₂_subset @[to_additive] theorem div_subset_div_left : t₁ ⊆ t₂ → s / t₁ ⊆ s / t₂ := image₂_subset_left @[to_additive] theorem div_subset_div_right : s₁ ⊆ s₂ → s₁ / t ⊆ s₂ / t := image₂_subset_right @[to_additive] theorem div_subset_iff : s / t ⊆ u ↔ ∀ x ∈ s, ∀ y ∈ t, x / y ∈ u := image₂_subset_iff @[to_additive] theorem union_div : (s₁ ∪ s₂) / t = s₁ / t ∪ s₂ / t := image₂_union_left @[to_additive] theorem div_union : s / (t₁ ∪ t₂) = s / t₁ ∪ s / t₂ := image₂_union_right @[to_additive] theorem inter_div_subset : s₁ ∩ s₂ / t ⊆ s₁ / t ∩ (s₂ / t) := image₂_inter_subset_left @[to_additive] theorem div_inter_subset : s / (t₁ ∩ t₂) ⊆ s / t₁ ∩ (s / t₂) := image₂_inter_subset_right @[to_additive] theorem inter_div_union_subset_union : s₁ ∩ s₂ / (t₁ ∪ t₂) ⊆ s₁ / t₁ ∪ s₂ / t₂ := image₂_inter_union_subset_union @[to_additive] theorem union_div_inter_subset_union : (s₁ ∪ s₂) / (t₁ ∩ t₂) ⊆ s₁ / t₁ ∪ s₂ / t₂ := image₂_union_inter_subset_union /-- If a finset `u` is contained in the product of two sets `s / t`, we can find two finsets `s'`, `t'` such that `s' ⊆ s`, `t' ⊆ t` and `u ⊆ s' / t'`. -/ @[to_additive "If a finset `u` is contained in the sum of two sets `s - t`, we can find two finsets `s'`, `t'` such that `s' ⊆ s`, `t' ⊆ t` and `u ⊆ s' - t'`."] theorem subset_div {s t : Set α} : ↑u ⊆ s / t → ∃ s' t' : Finset α, ↑s' ⊆ s ∧ ↑t' ⊆ t ∧ u ⊆ s' / t' := subset_image₂ @[to_additive (attr := simp (default + 1))] lemma sup_div_le [SemilatticeSup β] [OrderBot β] {s t : Finset α} {f : α → β} {a : β} : sup (s / t) f ≤ a ↔ ∀ x ∈ s, ∀ y ∈ t, f (x / y) ≤ a := sup_image₂_le @[to_additive] lemma sup_div_left [SemilatticeSup β] [OrderBot β] (s t : Finset α) (f : α → β) : sup (s / t) f = sup s fun x ↦ sup t (f <| x / ·) := sup_image₂_left .. @[to_additive] lemma sup_div_right [SemilatticeSup β] [OrderBot β] (s t : Finset α) (f : α → β) : sup (s / t) f = sup t fun y ↦ sup s (f <| · / y) := sup_image₂_right .. @[to_additive (attr := simp (default + 1))] lemma le_inf_div [SemilatticeInf β] [OrderTop β] {s t : Finset α} {f : α → β} {a : β} : a ≤ inf (s / t) f ↔ ∀ x ∈ s, ∀ y ∈ t, a ≤ f (x / y) := le_inf_image₂ @[to_additive] lemma inf_div_left [SemilatticeInf β] [OrderTop β] (s t : Finset α) (f : α → β) : inf (s / t) f = inf s fun x ↦ inf t (f <| x / ·) := inf_image₂_left .. @[to_additive] lemma inf_div_right [SemilatticeInf β] [OrderTop β] (s t : Finset α) (f : α → β) : inf (s / t) f = inf t fun y ↦ inf s (f <| · / y) := inf_image₂_right .. end Div /-! ### Instances -/ open Pointwise section Instances variable [DecidableEq α] [DecidableEq β] /-- Repeated pointwise addition (not the same as pointwise repeated addition!) of a `Finset`. See note [pointwise nat action]. -/ protected def nsmul [Zero α] [Add α] : SMul ℕ (Finset α) := ⟨nsmulRec⟩ /-- Repeated pointwise multiplication (not the same as pointwise repeated multiplication!) of a `Finset`. See note [pointwise nat action]. -/ protected def npow [One α] [Mul α] : Pow (Finset α) ℕ := ⟨fun s n => npowRec n s⟩ attribute [to_additive existing] Finset.npow /-- Repeated pointwise addition/subtraction (not the same as pointwise repeated addition/subtraction!) of a `Finset`. See note [pointwise nat action]. -/ protected def zsmul [Zero α] [Add α] [Neg α] : SMul ℤ (Finset α) := ⟨zsmulRec⟩ /-- Repeated pointwise multiplication/division (not the same as pointwise repeated multiplication/division!) of a `Finset`. See note [pointwise nat action]. -/ @[to_additive existing] protected def zpow [One α] [Mul α] [Inv α] : Pow (Finset α) ℤ := ⟨fun s n => zpowRec npowRec n s⟩ scoped[Pointwise] attribute [instance] Finset.nsmul Finset.npow Finset.zsmul Finset.zpow /-- `Finset α` is a `Semigroup` under pointwise operations if `α` is. -/ @[to_additive "`Finset α` is an `AddSemigroup` under pointwise operations if `α` is. "] protected def semigroup [Semigroup α] : Semigroup (Finset α) := coe_injective.semigroup _ coe_mul section CommSemigroup variable [CommSemigroup α] {s t : Finset α} /-- `Finset α` is a `CommSemigroup` under pointwise operations if `α` is. -/ @[to_additive "`Finset α` is an `AddCommSemigroup` under pointwise operations if `α` is. "] protected def commSemigroup : CommSemigroup (Finset α) := coe_injective.commSemigroup _ coe_mul @[to_additive] theorem inter_mul_union_subset : s ∩ t * (s ∪ t) ⊆ s * t := image₂_inter_union_subset mul_comm @[to_additive] theorem union_mul_inter_subset : (s ∪ t) * (s ∩ t) ⊆ s * t := image₂_union_inter_subset mul_comm end CommSemigroup section MulOneClass variable [MulOneClass α] /-- `Finset α` is a `MulOneClass` under pointwise operations if `α` is. -/ @[to_additive "`Finset α` is an `AddZeroClass` under pointwise operations if `α` is."] protected def mulOneClass : MulOneClass (Finset α) := coe_injective.mulOneClass _ (coe_singleton 1) coe_mul scoped[Pointwise] attribute [instance] Finset.semigroup Finset.addSemigroup Finset.commSemigroup Finset.addCommSemigroup Finset.mulOneClass Finset.addZeroClass @[to_additive] theorem subset_mul_left (s : Finset α) {t : Finset α} (ht : (1 : α) ∈ t) : s ⊆ s * t := fun a ha => mem_mul.2 ⟨a, ha, 1, ht, mul_one _⟩ @[to_additive] theorem subset_mul_right {s : Finset α} (t : Finset α) (hs : (1 : α) ∈ s) : t ⊆ s * t := fun a ha => mem_mul.2 ⟨1, hs, a, ha, one_mul _⟩ /-- The singleton operation as a `MonoidHom`. -/ @[to_additive "The singleton operation as an `AddMonoidHom`."] def singletonMonoidHom : α →* Finset α := { singletonMulHom, singletonOneHom with } @[to_additive (attr := simp)] theorem coe_singletonMonoidHom : (singletonMonoidHom : α → Finset α) = singleton := rfl @[to_additive (attr := simp)] theorem singletonMonoidHom_apply (a : α) : singletonMonoidHom a = {a} := rfl /-- The coercion from `Finset` to `Set` as a `MonoidHom`. -/ @[to_additive "The coercion from `Finset` to `set` as an `AddMonoidHom`."] noncomputable def coeMonoidHom : Finset α →* Set α where toFun := CoeTC.coe map_one' := coe_one map_mul' := coe_mul @[to_additive (attr := simp)] theorem coe_coeMonoidHom : (coeMonoidHom : Finset α → Set α) = CoeTC.coe := rfl @[to_additive (attr := simp)] theorem coeMonoidHom_apply (s : Finset α) : coeMonoidHom s = s := rfl /-- Lift a `MonoidHom` to `Finset` via `image`. -/ @[to_additive (attr := simps) "Lift an `add_monoid_hom` to `Finset` via `image`"] def imageMonoidHom [MulOneClass β] [FunLike F α β] [MonoidHomClass F α β] (f : F) : Finset α →* Finset β := { imageMulHom f, imageOneHom f with } end MulOneClass section Monoid variable [Monoid α] {s t : Finset α} {a : α} {m n : ℕ} @[to_additive (attr := simp, norm_cast)] theorem coe_pow (s : Finset α) (n : ℕ) : ↑(s ^ n) = (s : Set α) ^ n := by change ↑(npowRec n s) = (s : Set α) ^ n induction' n with n ih · rw [npowRec, pow_zero, coe_one] · rw [npowRec, pow_succ, coe_mul, ih] /-- `Finset α` is a `Monoid` under pointwise operations if `α` is. -/ @[to_additive "`Finset α` is an `AddMonoid` under pointwise operations if `α` is. "] protected def monoid : Monoid (Finset α) := coe_injective.monoid _ coe_one coe_mul coe_pow scoped[Pointwise] attribute [instance] Finset.monoid Finset.addMonoid @[to_additive] theorem pow_mem_pow (ha : a ∈ s) : ∀ n : ℕ, a ^ n ∈ s ^ n | 0 => by rw [pow_zero] exact one_mem_one | n + 1 => by rw [pow_succ] exact mul_mem_mul (pow_mem_pow ha n) ha @[to_additive] theorem pow_subset_pow (hst : s ⊆ t) : ∀ n : ℕ, s ^ n ⊆ t ^ n | 0 => by simp [pow_zero] | n + 1 => by rw [pow_succ] exact mul_subset_mul (pow_subset_pow hst n) hst @[to_additive] theorem pow_subset_pow_of_one_mem (hs : (1 : α) ∈ s) : m ≤ n → s ^ m ⊆ s ^ n := by apply Nat.le_induction · exact fun _ hn => hn · intro n _ hmn rw [pow_succ] exact hmn.trans (subset_mul_left (s ^ n) hs) @[to_additive (attr := simp, norm_cast)] theorem coe_list_prod (s : List (Finset α)) : (↑s.prod : Set α) = (s.map (↑)).prod := map_list_prod (coeMonoidHom : Finset α →* Set α) _ @[to_additive] theorem mem_prod_list_ofFn {a : α} {s : Fin n → Finset α} : a ∈ (List.ofFn s).prod ↔ ∃ f : ∀ i : Fin n, s i, (List.ofFn fun i => (f i : α)).prod = a := by rw [← mem_coe, coe_list_prod, List.map_ofFn, Set.mem_prod_list_ofFn] rfl @[to_additive] theorem mem_pow {a : α} {n : ℕ} : a ∈ s ^ n ↔ ∃ f : Fin n → s, (List.ofFn fun i => ↑(f i)).prod = a := by -- Also compiles without the option, but much slower. set_option tactic.skipAssignedInstances false in simp [← mem_coe, coe_pow, Set.mem_pow] @[to_additive (attr := simp)] theorem empty_pow (hn : n ≠ 0) : (∅ : Finset α) ^ n = ∅ := by rw [← tsub_add_cancel_of_le (Nat.succ_le_of_lt <| Nat.pos_of_ne_zero hn), pow_succ', empty_mul] @[to_additive] theorem mul_univ_of_one_mem [Fintype α] (hs : (1 : α) ∈ s) : s * univ = univ := eq_univ_iff_forall.2 fun _ => mem_mul.2 ⟨_, hs, _, mem_univ _, one_mul _⟩ @[to_additive] theorem univ_mul_of_one_mem [Fintype α] (ht : (1 : α) ∈ t) : univ * t = univ := eq_univ_iff_forall.2 fun _ => mem_mul.2 ⟨_, mem_univ _, _, ht, mul_one _⟩ @[to_additive (attr := simp)] theorem univ_mul_univ [Fintype α] : (univ : Finset α) * univ = univ := mul_univ_of_one_mem <| mem_univ _ @[to_additive (attr := simp) nsmul_univ] theorem univ_pow [Fintype α] (hn : n ≠ 0) : (univ : Finset α) ^ n = univ := coe_injective <| by rw [coe_pow, coe_univ, Set.univ_pow hn] @[to_additive] protected theorem _root_.IsUnit.finset : IsUnit a → IsUnit ({a} : Finset α) := IsUnit.map (singletonMonoidHom : α →* Finset α) end Monoid section CommMonoid variable [CommMonoid α] /-- `Finset α` is a `CommMonoid` under pointwise operations if `α` is. -/ @[to_additive "`Finset α` is an `AddCommMonoid` under pointwise operations if `α` is. "] protected def commMonoid : CommMonoid (Finset α) := coe_injective.commMonoid _ coe_one coe_mul coe_pow scoped[Pointwise] attribute [instance] Finset.commMonoid Finset.addCommMonoid @[to_additive (attr := simp, norm_cast)] theorem coe_prod {ι : Type*} (s : Finset ι) (f : ι → Finset α) : ↑(∏ i ∈ s, f i) = ∏ i ∈ s, (f i : Set α) := map_prod ((coeMonoidHom) : Finset α →* Set α) _ _ end CommMonoid open Pointwise section DivisionMonoid variable [DivisionMonoid α] {s t : Finset α} @[to_additive (attr := simp)] theorem coe_zpow (s : Finset α) : ∀ n : ℤ, ↑(s ^ n) = (s : Set α) ^ n | Int.ofNat n => coe_pow _ _ | Int.negSucc n => by refine (coe_inv _).trans ?_ exact congr_arg Inv.inv (coe_pow _ _) @[to_additive] protected theorem mul_eq_one_iff : s * t = 1 ↔ ∃ a b, s = {a} ∧ t = {b} ∧ a * b = 1 := by simp_rw [← coe_inj, coe_mul, coe_one, Set.mul_eq_one_iff, coe_singleton] /-- `Finset α` is a division monoid under pointwise operations if `α` is. -/ @[to_additive subtractionMonoid "`Finset α` is a subtraction monoid under pointwise operations if `α` is."] protected def divisionMonoid : DivisionMonoid (Finset α) := coe_injective.divisionMonoid _ coe_one coe_mul coe_inv coe_div coe_pow coe_zpow scoped[Pointwise] attribute [instance] Finset.divisionMonoid Finset.subtractionMonoid @[to_additive (attr := simp)] theorem isUnit_iff : IsUnit s ↔ ∃ a, s = {a} ∧ IsUnit a := by constructor · rintro ⟨u, rfl⟩ obtain ⟨a, b, ha, hb, h⟩ := Finset.mul_eq_one_iff.1 u.mul_inv refine ⟨a, ha, ⟨a, b, h, singleton_injective ?_⟩, rfl⟩ rw [← singleton_mul_singleton, ← ha, ← hb] exact u.inv_mul · rintro ⟨a, rfl, ha⟩ exact ha.finset @[to_additive (attr := simp)] theorem isUnit_coe : IsUnit (s : Set α) ↔ IsUnit s := by simp_rw [isUnit_iff, Set.isUnit_iff, coe_eq_singleton] @[to_additive (attr := simp)] lemma univ_div_univ [Fintype α] : (univ / univ : Finset α) = univ := by simp [div_eq_mul_inv] end DivisionMonoid /-- `Finset α` is a commutative division monoid under pointwise operations if `α` is. -/ @[to_additive subtractionCommMonoid "`Finset α` is a commutative subtraction monoid under pointwise operations if `α` is."] protected def divisionCommMonoid [DivisionCommMonoid α] : DivisionCommMonoid (Finset α) := coe_injective.divisionCommMonoid _ coe_one coe_mul coe_inv coe_div coe_pow coe_zpow /-- `Finset α` has distributive negation if `α` has. -/ protected def distribNeg [Mul α] [HasDistribNeg α] : HasDistribNeg (Finset α) := coe_injective.hasDistribNeg _ coe_neg coe_mul scoped[Pointwise] attribute [instance] Finset.divisionCommMonoid Finset.subtractionCommMonoid Finset.distribNeg section Distrib variable [Distrib α] (s t u : Finset α) /-! Note that `Finset α` is not a `Distrib` because `s * t + s * u` has cross terms that `s * (t + u)` lacks. ```lean -- {10, 16, 18, 20, 8, 9} #eval {1, 2} * ({3, 4} + {5, 6} : Finset ℕ) -- {10, 11, 12, 13, 14, 15, 16, 18, 20, 8, 9} #eval ({1, 2} : Finset ℕ) * {3, 4} + {1, 2} * {5, 6} ``` -/ theorem mul_add_subset : s * (t + u) ⊆ s * t + s * u := image₂_distrib_subset_left mul_add theorem add_mul_subset : (s + t) * u ⊆ s * u + t * u := image₂_distrib_subset_right add_mul end Distrib section MulZeroClass variable [MulZeroClass α] {s t : Finset α} /-! Note that `Finset` is not a `MulZeroClass` because `0 * ∅ ≠ 0`. -/ theorem mul_zero_subset (s : Finset α) : s * 0 ⊆ 0 := by simp [subset_iff, mem_mul] theorem zero_mul_subset (s : Finset α) : 0 * s ⊆ 0 := by simp [subset_iff, mem_mul] theorem Nonempty.mul_zero (hs : s.Nonempty) : s * 0 = 0 := s.mul_zero_subset.antisymm <| by simpa [mem_mul] using hs theorem Nonempty.zero_mul (hs : s.Nonempty) : 0 * s = 0 := s.zero_mul_subset.antisymm <| by simpa [mem_mul] using hs end MulZeroClass section Group variable [Group α] [DivisionMonoid β] [FunLike F α β] [MonoidHomClass F α β] variable (f : F) {s t : Finset α} {a b : α} /-! Note that `Finset` is not a `Group` because `s / s ≠ 1` in general. -/ @[to_additive (attr := simp)] theorem one_mem_div_iff : (1 : α) ∈ s / t ↔ ¬Disjoint s t := by rw [← mem_coe, ← disjoint_coe, coe_div, Set.one_mem_div_iff] @[to_additive] theorem not_one_mem_div_iff : (1 : α) ∉ s / t ↔ Disjoint s t := one_mem_div_iff.not_left @[to_additive] theorem Nonempty.one_mem_div (h : s.Nonempty) : (1 : α) ∈ s / s := let ⟨a, ha⟩ := h mem_div.2 ⟨a, ha, a, ha, div_self' _⟩ @[to_additive] theorem isUnit_singleton (a : α) : IsUnit ({a} : Finset α) := (Group.isUnit a).finset /- Porting note: not in simp nf; Added non-simpable part as `isUnit_iff_singleton_aux` below Left-hand side simplifies from IsUnit s to ∃ a, s = {a} ∧ IsUnit a -/ -- @[simp] theorem isUnit_iff_singleton : IsUnit s ↔ ∃ a, s = {a} := by simp only [isUnit_iff, Group.isUnit, and_true_iff] @[simp] theorem isUnit_iff_singleton_aux {α} [Group α] {s : Finset α} : (∃ a, s = {a} ∧ IsUnit a) ↔ ∃ a, s = {a} := by simp only [Group.isUnit, and_true_iff] @[to_additive (attr := simp)] theorem image_mul_left : image (fun b => a * b) t = preimage t (fun b => a⁻¹ * b) (mul_right_injective _).injOn := coe_injective <| by simp @[to_additive (attr := simp)] theorem image_mul_right : image (· * b) t = preimage t (· * b⁻¹) (mul_left_injective _).injOn := coe_injective <| by simp @[to_additive] theorem image_mul_left' : image (fun b => a⁻¹ * b) t = preimage t (fun b => a * b) (mul_right_injective _).injOn := by simp @[to_additive] theorem image_mul_right' : image (· * b⁻¹) t = preimage t (· * b) (mul_left_injective _).injOn := by simp theorem image_div : (s / t).image (f : α → β) = s.image f / t.image f := image_image₂_distrib <| map_div f end Group section GroupWithZero variable [GroupWithZero α] {s t : Finset α} theorem div_zero_subset (s : Finset α) : s / 0 ⊆ 0 := by simp [subset_iff, mem_div] theorem zero_div_subset (s : Finset α) : 0 / s ⊆ 0 := by simp [subset_iff, mem_div] theorem Nonempty.div_zero (hs : s.Nonempty) : s / 0 = 0 := s.div_zero_subset.antisymm <| by simpa [mem_div] using hs theorem Nonempty.zero_div (hs : s.Nonempty) : 0 / s = 0 := s.zero_div_subset.antisymm <| by simpa [mem_div] using hs end GroupWithZero end Instances section Group variable [Group α] {s t : Finset α} {a b : α} @[to_additive (attr := simp)] theorem preimage_mul_left_singleton : preimage {b} (a * ·) (mul_right_injective _).injOn = {a⁻¹ * b} := by classical rw [← image_mul_left', image_singleton] @[to_additive (attr := simp)] theorem preimage_mul_right_singleton : preimage {b} (· * a) (mul_left_injective _).injOn = {b * a⁻¹} := by classical rw [← image_mul_right', image_singleton] @[to_additive (attr := simp)] theorem preimage_mul_left_one : preimage 1 (a * ·) (mul_right_injective _).injOn = {a⁻¹} := by classical rw [← image_mul_left', image_one, mul_one] @[to_additive (attr := simp)] theorem preimage_mul_right_one : preimage 1 (· * b) (mul_left_injective _).injOn = {b⁻¹} := by classical rw [← image_mul_right', image_one, one_mul] @[to_additive] theorem preimage_mul_left_one' : preimage 1 (a⁻¹ * ·) (mul_right_injective _).injOn = {a} := by rw [preimage_mul_left_one, inv_inv] @[to_additive] theorem preimage_mul_right_one' : preimage 1 (· * b⁻¹) (mul_left_injective _).injOn = {b} := by rw [preimage_mul_right_one, inv_inv] end Group /-! ### Scalar addition/multiplication of finsets -/ section SMul variable [DecidableEq β] [SMul α β] {s s₁ s₂ : Finset α} {t t₁ t₂ u : Finset β} {a : α} {b : β} /-- The pointwise product of two finsets `s` and `t`: `s • t = {x • y | x ∈ s, y ∈ t}`. -/ @[to_additive "The pointwise sum of two finsets `s` and `t`: `s +ᵥ t = {x +ᵥ y | x ∈ s, y ∈ t}`."] protected def smul : SMul (Finset α) (Finset β) := ⟨image₂ (· • ·)⟩ scoped[Pointwise] attribute [instance] Finset.smul Finset.vadd @[to_additive] theorem smul_def : s • t = (s ×ˢ t).image fun p : α × β => p.1 • p.2 := rfl @[to_additive] theorem image_smul_product : ((s ×ˢ t).image fun x : α × β => x.fst • x.snd) = s • t := rfl @[to_additive] theorem mem_smul {x : β} : x ∈ s • t ↔ ∃ y ∈ s, ∃ z ∈ t, y • z = x := mem_image₂ @[to_additive (attr := simp, norm_cast)] theorem coe_smul (s : Finset α) (t : Finset β) : ↑(s • t) = (s : Set α) • (t : Set β) := coe_image₂ _ _ _ @[to_additive] theorem smul_mem_smul : a ∈ s → b ∈ t → a • b ∈ s • t := mem_image₂_of_mem @[to_additive] theorem smul_card_le : (s • t).card ≤ s.card • t.card := card_image₂_le _ _ _ @[to_additive (attr := simp)] theorem empty_smul (t : Finset β) : (∅ : Finset α) • t = ∅ := image₂_empty_left @[to_additive (attr := simp)] theorem smul_empty (s : Finset α) : s • (∅ : Finset β) = ∅ := image₂_empty_right @[to_additive (attr := simp)] theorem smul_eq_empty : s • t = ∅ ↔ s = ∅ ∨ t = ∅ := image₂_eq_empty_iff @[to_additive (attr := simp, aesop safe apply (rule_sets := [finsetNonempty]))] theorem smul_nonempty_iff : (s • t).Nonempty ↔ s.Nonempty ∧ t.Nonempty := image₂_nonempty_iff @[to_additive] theorem Nonempty.smul : s.Nonempty → t.Nonempty → (s • t).Nonempty := Nonempty.image₂ @[to_additive] theorem Nonempty.of_smul_left : (s • t).Nonempty → s.Nonempty := Nonempty.of_image₂_left @[to_additive] theorem Nonempty.of_smul_right : (s • t).Nonempty → t.Nonempty := Nonempty.of_image₂_right @[to_additive] theorem smul_singleton (b : β) : s • ({b} : Finset β) = s.image (· • b) := image₂_singleton_right @[to_additive] theorem singleton_smul_singleton (a : α) (b : β) : ({a} : Finset α) • ({b} : Finset β) = {a • b} := image₂_singleton @[to_additive (attr := mono)] theorem smul_subset_smul : s₁ ⊆ s₂ → t₁ ⊆ t₂ → s₁ • t₁ ⊆ s₂ • t₂ := image₂_subset @[to_additive] theorem smul_subset_smul_left : t₁ ⊆ t₂ → s • t₁ ⊆ s • t₂ := image₂_subset_left @[to_additive] theorem smul_subset_smul_right : s₁ ⊆ s₂ → s₁ • t ⊆ s₂ • t := image₂_subset_right @[to_additive] theorem smul_subset_iff : s • t ⊆ u ↔ ∀ a ∈ s, ∀ b ∈ t, a • b ∈ u := image₂_subset_iff @[to_additive] theorem union_smul [DecidableEq α] : (s₁ ∪ s₂) • t = s₁ • t ∪ s₂ • t := image₂_union_left @[to_additive] theorem smul_union : s • (t₁ ∪ t₂) = s • t₁ ∪ s • t₂ := image₂_union_right @[to_additive] theorem inter_smul_subset [DecidableEq α] : (s₁ ∩ s₂) • t ⊆ s₁ • t ∩ s₂ • t := image₂_inter_subset_left @[to_additive] theorem smul_inter_subset : s • (t₁ ∩ t₂) ⊆ s • t₁ ∩ s • t₂ := image₂_inter_subset_right @[to_additive] theorem inter_smul_union_subset_union [DecidableEq α] : (s₁ ∩ s₂) • (t₁ ∪ t₂) ⊆ s₁ • t₁ ∪ s₂ • t₂ := image₂_inter_union_subset_union @[to_additive] theorem union_smul_inter_subset_union [DecidableEq α] : (s₁ ∪ s₂) • (t₁ ∩ t₂) ⊆ s₁ • t₁ ∪ s₂ • t₂ := image₂_union_inter_subset_union /-- If a finset `u` is contained in the scalar product of two sets `s • t`, we can find two finsets `s'`, `t'` such that `s' ⊆ s`, `t' ⊆ t` and `u ⊆ s' • t'`. -/ @[to_additive "If a finset `u` is contained in the scalar sum of two sets `s +ᵥ t`, we can find two finsets `s'`, `t'` such that `s' ⊆ s`, `t' ⊆ t` and `u ⊆ s' +ᵥ t'`."] theorem subset_smul {s : Set α} {t : Set β} : ↑u ⊆ s • t → ∃ (s' : Finset α) (t' : Finset β), ↑s' ⊆ s ∧ ↑t' ⊆ t ∧ u ⊆ s' • t' := subset_image₂ end SMul /-! ### Scalar subtraction of finsets -/ section VSub -- Porting note: Reordered [VSub α β] and [DecidableEq α] to make vsub less dangerous. Bad? variable [VSub α β] [DecidableEq α] {s s₁ s₂ t t₁ t₂ : Finset β} {u : Finset α} {a : α} {b c : β} /-- The pointwise subtraction of two finsets `s` and `t`: `s -ᵥ t = {x -ᵥ y | x ∈ s, y ∈ t}`. -/ protected def vsub : VSub (Finset α) (Finset β) := ⟨image₂ (· -ᵥ ·)⟩ scoped[Pointwise] attribute [instance] Finset.vsub theorem vsub_def : s -ᵥ t = image₂ (· -ᵥ ·) s t := rfl @[simp] theorem image_vsub_product : image₂ (· -ᵥ ·) s t = s -ᵥ t := rfl theorem mem_vsub : a ∈ s -ᵥ t ↔ ∃ b ∈ s, ∃ c ∈ t, b -ᵥ c = a := mem_image₂ @[simp, norm_cast] theorem coe_vsub (s t : Finset β) : (↑(s -ᵥ t) : Set α) = (s : Set β) -ᵥ t := coe_image₂ _ _ _ theorem vsub_mem_vsub : b ∈ s → c ∈ t → b -ᵥ c ∈ s -ᵥ t := mem_image₂_of_mem theorem vsub_card_le : (s -ᵥ t : Finset α).card ≤ s.card * t.card := card_image₂_le _ _ _ @[simp] theorem empty_vsub (t : Finset β) : (∅ : Finset β) -ᵥ t = ∅ := image₂_empty_left @[simp] theorem vsub_empty (s : Finset β) : s -ᵥ (∅ : Finset β) = ∅ := image₂_empty_right @[simp] theorem vsub_eq_empty : s -ᵥ t = ∅ ↔ s = ∅ ∨ t = ∅ := image₂_eq_empty_iff @[simp, aesop safe apply (rule_sets := [finsetNonempty])] theorem vsub_nonempty : (s -ᵥ t : Finset α).Nonempty ↔ s.Nonempty ∧ t.Nonempty := image₂_nonempty_iff theorem Nonempty.vsub : s.Nonempty → t.Nonempty → (s -ᵥ t : Finset α).Nonempty := Nonempty.image₂ theorem Nonempty.of_vsub_left : (s -ᵥ t : Finset α).Nonempty → s.Nonempty := Nonempty.of_image₂_left theorem Nonempty.of_vsub_right : (s -ᵥ t : Finset α).Nonempty → t.Nonempty := Nonempty.of_image₂_right @[simp] theorem vsub_singleton (b : β) : s -ᵥ ({b} : Finset β) = s.image (· -ᵥ b) := image₂_singleton_right theorem singleton_vsub (a : β) : ({a} : Finset β) -ᵥ t = t.image (a -ᵥ ·) := image₂_singleton_left -- @[simp] -- Porting note (#10618): simp can prove this theorem singleton_vsub_singleton (a b : β) : ({a} : Finset β) -ᵥ {b} = {a -ᵥ b} := image₂_singleton @[mono] theorem vsub_subset_vsub : s₁ ⊆ s₂ → t₁ ⊆ t₂ → s₁ -ᵥ t₁ ⊆ s₂ -ᵥ t₂ := image₂_subset theorem vsub_subset_vsub_left : t₁ ⊆ t₂ → s -ᵥ t₁ ⊆ s -ᵥ t₂ := image₂_subset_left theorem vsub_subset_vsub_right : s₁ ⊆ s₂ → s₁ -ᵥ t ⊆ s₂ -ᵥ t := image₂_subset_right theorem vsub_subset_iff : s -ᵥ t ⊆ u ↔ ∀ x ∈ s, ∀ y ∈ t, x -ᵥ y ∈ u := image₂_subset_iff section variable [DecidableEq β] theorem union_vsub : s₁ ∪ s₂ -ᵥ t = s₁ -ᵥ t ∪ (s₂ -ᵥ t) := image₂_union_left theorem vsub_union : s -ᵥ (t₁ ∪ t₂) = s -ᵥ t₁ ∪ (s -ᵥ t₂) := image₂_union_right theorem inter_vsub_subset : s₁ ∩ s₂ -ᵥ t ⊆ (s₁ -ᵥ t) ∩ (s₂ -ᵥ t) := image₂_inter_subset_left theorem vsub_inter_subset : s -ᵥ t₁ ∩ t₂ ⊆ (s -ᵥ t₁) ∩ (s -ᵥ t₂) := image₂_inter_subset_right end /-- If a finset `u` is contained in the pointwise subtraction of two sets `s -ᵥ t`, we can find two finsets `s'`, `t'` such that `s' ⊆ s`, `t' ⊆ t` and `u ⊆ s' -ᵥ t'`. -/ theorem subset_vsub {s t : Set β} : ↑u ⊆ s -ᵥ t → ∃ s' t' : Finset β, ↑s' ⊆ s ∧ ↑t' ⊆ t ∧ u ⊆ s' -ᵥ t' := subset_image₂ end VSub open Pointwise /-! ### Translation/scaling of finsets -/ section SMul variable [DecidableEq β] [SMul α β] {s s₁ s₂ t u : Finset β} {a : α} {b : β} /-- The scaling of a finset `s` by a scalar `a`: `a • s = {a • x | x ∈ s}`. -/ @[to_additive "The translation of a finset `s` by a vector `a`: `a +ᵥ s = {a +ᵥ x | x ∈ s}`."] protected def smulFinset : SMul α (Finset β) := ⟨fun a => image <| (a • ·)⟩ scoped[Pointwise] attribute [instance] Finset.smulFinset Finset.vaddFinset @[to_additive] theorem smul_finset_def : a • s = s.image (a • ·) := rfl @[to_additive] theorem image_smul : (s.image fun x => a • x) = a • s := rfl @[to_additive] theorem mem_smul_finset {x : β} : x ∈ a • s ↔ ∃ y, y ∈ s ∧ a • y = x := by simp only [Finset.smul_finset_def, and_assoc, mem_image, exists_prop, Prod.exists, mem_product] @[to_additive (attr := simp, norm_cast)] theorem coe_smul_finset (a : α) (s : Finset β) : ↑(a • s) = a • (↑s : Set β) := coe_image @[to_additive] theorem smul_mem_smul_finset : b ∈ s → a • b ∈ a • s := mem_image_of_mem _ @[to_additive] theorem smul_finset_card_le : (a • s).card ≤ s.card := card_image_le @[to_additive (attr := simp)] theorem smul_finset_empty (a : α) : a • (∅ : Finset β) = ∅ := image_empty _ @[to_additive (attr := simp)] theorem smul_finset_eq_empty : a • s = ∅ ↔ s = ∅ := image_eq_empty @[to_additive (attr := simp, aesop safe apply (rule_sets := [finsetNonempty]))] theorem smul_finset_nonempty : (a • s).Nonempty ↔ s.Nonempty := image_nonempty @[to_additive] theorem Nonempty.smul_finset (hs : s.Nonempty) : (a • s).Nonempty := hs.image _ @[to_additive (attr := simp)] theorem singleton_smul (a : α) : ({a} : Finset α) • t = a • t := image₂_singleton_left @[to_additive (attr := mono)] theorem smul_finset_subset_smul_finset : s ⊆ t → a • s ⊆ a • t := image_subset_image @[to_additive (attr := simp)] theorem smul_finset_singleton (b : β) : a • ({b} : Finset β) = {a • b} := image_singleton _ _ @[to_additive] theorem smul_finset_union : a • (s₁ ∪ s₂) = a • s₁ ∪ a • s₂ := image_union _ _ @[to_additive] theorem smul_finset_inter_subset : a • (s₁ ∩ s₂) ⊆ a • s₁ ∩ a • s₂ := image_inter_subset _ _ _ @[to_additive] theorem smul_finset_subset_smul {s : Finset α} : a ∈ s → a • t ⊆ s • t := image_subset_image₂_right @[to_additive (attr := simp)] theorem biUnion_smul_finset (s : Finset α) (t : Finset β) : s.biUnion (· • t) = s • t := biUnion_image_left end SMul open Pointwise section Instances variable [DecidableEq γ] @[to_additive] instance smulCommClass_finset [SMul α γ] [SMul β γ] [SMulCommClass α β γ] : SMulCommClass α β (Finset γ) := ⟨fun _ _ => Commute.finset_image <| smul_comm _ _⟩ @[to_additive] instance smulCommClass_finset' [SMul α γ] [SMul β γ] [SMulCommClass α β γ] : SMulCommClass α (Finset β) (Finset γ) := ⟨fun a s t => coe_injective <| by simp only [coe_smul_finset, coe_smul, smul_comm]⟩ @[to_additive] instance smulCommClass_finset'' [SMul α γ] [SMul β γ] [SMulCommClass α β γ] : SMulCommClass (Finset α) β (Finset γ) := haveI := SMulCommClass.symm α β γ SMulCommClass.symm _ _ _ @[to_additive] instance smulCommClass [SMul α γ] [SMul β γ] [SMulCommClass α β γ] : SMulCommClass (Finset α) (Finset β) (Finset γ) := ⟨fun s t u => coe_injective <| by simp_rw [coe_smul, smul_comm]⟩ @[to_additive vaddAssocClass] instance isScalarTower [SMul α β] [SMul α γ] [SMul β γ] [IsScalarTower α β γ] : IsScalarTower α β (Finset γ) := ⟨fun a b s => by simp only [← image_smul, image_image, smul_assoc, Function.comp]⟩ variable [DecidableEq β] @[to_additive vaddAssocClass'] instance isScalarTower' [SMul α β] [SMul α γ] [SMul β γ] [IsScalarTower α β γ] : IsScalarTower α (Finset β) (Finset γ) := ⟨fun a s t => coe_injective <| by simp only [coe_smul_finset, coe_smul, smul_assoc]⟩ @[to_additive vaddAssocClass''] instance isScalarTower'' [SMul α β] [SMul α γ] [SMul β γ] [IsScalarTower α β γ] : IsScalarTower (Finset α) (Finset β) (Finset γ) := ⟨fun a s t => coe_injective <| by simp only [coe_smul_finset, coe_smul, smul_assoc]⟩ @[to_additive] instance isCentralScalar [SMul α β] [SMul αᵐᵒᵖ β] [IsCentralScalar α β] : IsCentralScalar α (Finset β) := ⟨fun a s => coe_injective <| by simp only [coe_smul_finset, coe_smul, op_smul_eq_smul]⟩ /-- A multiplicative action of a monoid `α` on a type `β` gives a multiplicative action of `Finset α` on `Finset β`. -/ @[to_additive "An additive action of an additive monoid `α` on a type `β` gives an additive action of `Finset α` on `Finset β`"] protected def mulAction [DecidableEq α] [Monoid α] [MulAction α β] : MulAction (Finset α) (Finset β) where mul_smul _ _ _ := image₂_assoc mul_smul one_smul s := image₂_singleton_left.trans <| by simp_rw [one_smul, image_id'] /-- A multiplicative action of a monoid on a type `β` gives a multiplicative action on `Finset β`. -/ @[to_additive "An additive action of an additive monoid on a type `β` gives an additive action on `Finset β`."] protected def mulActionFinset [Monoid α] [MulAction α β] : MulAction α (Finset β) := coe_injective.mulAction _ coe_smul_finset scoped[Pointwise] attribute [instance] Finset.mulActionFinset Finset.addActionFinset Finset.mulAction Finset.addAction /-- If scalar multiplication by elements of `α` sends `(0 : β)` to zero, then the same is true for `(0 : Finset β)`. -/ protected def smulZeroClassFinset [Zero β] [SMulZeroClass α β] : SMulZeroClass α (Finset β) := coe_injective.smulZeroClass ⟨(↑), coe_zero⟩ coe_smul_finset scoped[Pointwise] attribute [instance] Finset.smulZeroClassFinset /-- If the scalar multiplication `(· • ·) : α → β → β` is distributive, then so is `(· • ·) : α → Finset β → Finset β`. -/ protected def distribSMulFinset [AddZeroClass β] [DistribSMul α β] : DistribSMul α (Finset β) := coe_injective.distribSMul coeAddMonoidHom coe_smul_finset scoped[Pointwise] attribute [instance] Finset.distribSMulFinset /-- A distributive multiplicative action of a monoid on an additive monoid `β` gives a distributive multiplicative action on `Finset β`. -/ protected def distribMulActionFinset [Monoid α] [AddMonoid β] [DistribMulAction α β] : DistribMulAction α (Finset β) := Function.Injective.distribMulAction coeAddMonoidHom coe_injective coe_smul_finset /-- A multiplicative action of a monoid on a monoid `β` gives a multiplicative action on `Set β`. -/ protected def mulDistribMulActionFinset [Monoid α] [Monoid β] [MulDistribMulAction α β] : MulDistribMulAction α (Finset β) := Function.Injective.mulDistribMulAction coeMonoidHom coe_injective coe_smul_finset scoped[Pointwise] attribute [instance] Finset.distribMulActionFinset Finset.mulDistribMulActionFinset instance [DecidableEq α] [Zero α] [Mul α] [NoZeroDivisors α] : NoZeroDivisors (Finset α) := Function.Injective.noZeroDivisors (↑) coe_injective coe_zero coe_mul instance noZeroSMulDivisors [Zero α] [Zero β] [SMul α β] [NoZeroSMulDivisors α β] : NoZeroSMulDivisors (Finset α) (Finset β) where eq_zero_or_eq_zero_of_smul_eq_zero {s t} := by exact_mod_cast eq_zero_or_eq_zero_of_smul_eq_zero (c := s.toSet) (x := t.toSet) instance noZeroSMulDivisors_finset [Zero α] [Zero β] [SMul α β] [NoZeroSMulDivisors α β] : NoZeroSMulDivisors α (Finset β) := Function.Injective.noZeroSMulDivisors (↑) coe_injective coe_zero coe_smul_finset end Instances section SMul variable [DecidableEq β] [DecidableEq γ] [SMul αᵐᵒᵖ β] [SMul β γ] [SMul α γ] -- TODO: replace hypothesis and conclusion with a typeclass @[to_additive] theorem op_smul_finset_smul_eq_smul_smul_finset (a : α) (s : Finset β) (t : Finset γ) (h : ∀ (a : α) (b : β) (c : γ), (op a • b) • c = b • a • c) : (op a • s) • t = s • a • t := by ext simp [mem_smul, mem_smul_finset, h] end SMul section Mul variable [Mul α] [DecidableEq α] {s t u : Finset α} {a : α} @[to_additive] theorem op_smul_finset_subset_mul : a ∈ t → op a • s ⊆ s * t := image_subset_image₂_left @[to_additive (attr := simp)] theorem biUnion_op_smul_finset (s t : Finset α) : (t.biUnion fun a => op a • s) = s * t := biUnion_image_right @[to_additive] theorem mul_subset_iff_left : s * t ⊆ u ↔ ∀ a ∈ s, a • t ⊆ u := image₂_subset_iff_left @[to_additive] theorem mul_subset_iff_right : s * t ⊆ u ↔ ∀ b ∈ t, op b • s ⊆ u := image₂_subset_iff_right end Mul section Semigroup variable [Semigroup α] [DecidableEq α] @[to_additive] theorem op_smul_finset_mul_eq_mul_smul_finset (a : α) (s : Finset α) (t : Finset α) : op a • s * t = s * a • t := op_smul_finset_smul_eq_smul_smul_finset _ _ _ fun _ _ _ => mul_assoc _ _ _ end Semigroup section IsLeftCancelMul variable [Mul α] [IsLeftCancelMul α] [DecidableEq α] (s t : Finset α) (a : α) @[to_additive] theorem pairwiseDisjoint_smul_iff {s : Set α} {t : Finset α} : s.PairwiseDisjoint (· • t) ↔ (s ×ˢ t : Set (α × α)).InjOn fun p => p.1 * p.2 := by simp_rw [← pairwiseDisjoint_coe, coe_smul_finset, Set.pairwiseDisjoint_smul_iff] @[to_additive (attr := simp)] theorem card_singleton_mul : ({a} * t).card = t.card := card_image₂_singleton_left _ <| mul_right_injective _ @[to_additive] theorem singleton_mul_inter : {a} * (s ∩ t) = {a} * s ∩ ({a} * t) := image₂_singleton_inter _ _ <| mul_right_injective _ @[to_additive] theorem card_le_card_mul_left {s : Finset α} (hs : s.Nonempty) : t.card ≤ (s * t).card := card_le_card_image₂_left _ hs mul_right_injective end IsLeftCancelMul section variable [Mul α] [IsRightCancelMul α] [DecidableEq α] (s t : Finset α) (a : α) @[to_additive (attr := simp)] theorem card_mul_singleton : (s * {a}).card = s.card := card_image₂_singleton_right _ <| mul_left_injective _ @[to_additive] theorem inter_mul_singleton : s ∩ t * {a} = s * {a} ∩ (t * {a}) := image₂_inter_singleton _ _ <| mul_left_injective _ @[to_additive] theorem card_le_card_mul_right {t : Finset α} (ht : t.Nonempty) : s.card ≤ (s * t).card := card_le_card_image₂_right _ ht mul_left_injective end section Group variable [Group α] [DecidableEq α] {s t : Finset α} @[to_additive] lemma card_le_card_div_left (hs : s.Nonempty) : t.card ≤ (s / t).card := card_le_card_image₂_left _ hs fun _ ↦ div_right_injective @[to_additive] lemma card_le_card_div_right (ht : t.Nonempty) : s.card ≤ (s / t).card := card_le_card_image₂_right _ ht fun _ ↦ div_left_injective end Group open Pointwise @[to_additive] theorem image_smul_comm [DecidableEq β] [DecidableEq γ] [SMul α β] [SMul α γ] (f : β → γ) (a : α) (s : Finset β) : (∀ b, f (a • b) = a • f b) → (a • s).image f = a • s.image f := image_comm @[to_additive] theorem image_smul_distrib [DecidableEq α] [DecidableEq β] [Monoid α] [Monoid β] [FunLike F α β] [MonoidHomClass F α β] (f : F) (a : α) (s : Finset α) : (a • s).image f = f a • s.image f := image_comm <| map_mul _ _ section Group variable [DecidableEq β] [Group α] [MulAction α β] {s t : Finset β} {a : α} {b : β} @[to_additive (attr := simp)] theorem smul_mem_smul_finset_iff (a : α) : a • b ∈ a • s ↔ b ∈ s := (MulAction.injective _).mem_finset_image @[to_additive] theorem inv_smul_mem_iff : a⁻¹ • b ∈ s ↔ b ∈ a • s := by rw [← smul_mem_smul_finset_iff a, smul_inv_smul] @[to_additive] theorem mem_inv_smul_finset_iff : b ∈ a⁻¹ • s ↔ a • b ∈ s := by rw [← smul_mem_smul_finset_iff a, smul_inv_smul] @[to_additive (attr := simp)] theorem smul_finset_subset_smul_finset_iff : a • s ⊆ a • t ↔ s ⊆ t := image_subset_image_iff <| MulAction.injective _ @[to_additive] theorem smul_finset_subset_iff : a • s ⊆ t ↔ s ⊆ a⁻¹ • t := by simp_rw [← coe_subset] push_cast exact Set.set_smul_subset_iff @[to_additive] theorem subset_smul_finset_iff : s ⊆ a • t ↔ a⁻¹ • s ⊆ t := by simp_rw [← coe_subset] push_cast exact Set.subset_set_smul_iff @[to_additive] theorem smul_finset_inter : a • (s ∩ t) = a • s ∩ a • t := image_inter _ _ <| MulAction.injective a @[to_additive] theorem smul_finset_sdiff : a • (s \ t) = a • s \ a • t := image_sdiff _ _ <| MulAction.injective a open scoped symmDiff in @[to_additive] theorem smul_finset_symmDiff : a • s ∆ t = (a • s) ∆ (a • t) := image_symmDiff _ _ <| MulAction.injective a @[to_additive (attr := simp)] theorem smul_finset_univ [Fintype β] : a • (univ : Finset β) = univ := image_univ_of_surjective <| MulAction.surjective a @[to_additive (attr := simp)] theorem smul_univ [Fintype β] {s : Finset α} (hs : s.Nonempty) : s • (univ : Finset β) = univ := coe_injective <| by push_cast exact Set.smul_univ hs @[to_additive (attr := simp)] theorem card_smul_finset (a : α) (s : Finset β) : (a • s).card = s.card := card_image_of_injective _ <| MulAction.injective _ /-- If the left cosets of `t` by elements of `s` are disjoint (but not necessarily distinct!), then the size of `t` divides the size of `s • t`. -/ @[to_additive "If the left cosets of `t` by elements of `s` are disjoint (but not necessarily distinct!), then the size of `t` divides the size of `s +ᵥ t`."] theorem card_dvd_card_smul_right {s : Finset α} : ((· • t) '' (s : Set α)).PairwiseDisjoint id → t.card ∣ (s • t).card := card_dvd_card_image₂_right fun _ _ => MulAction.injective _ variable [DecidableEq α] /-- If the right cosets of `s` by elements of `t` are disjoint (but not necessarily distinct!), then the size of `s` divides the size of `s * t`. -/ @[to_additive "If the right cosets of `s` by elements of `t` are disjoint (but not necessarily distinct!), then the size of `s` divides the size of `s + t`."] theorem card_dvd_card_mul_left {s t : Finset α} : ((fun b => s.image fun a => a * b) '' (t : Set α)).PairwiseDisjoint id → s.card ∣ (s * t).card := card_dvd_card_image₂_left fun _ _ => mul_left_injective _ /-- If the left cosets of `t` by elements of `s` are disjoint (but not necessarily distinct!), then the size of `t` divides the size of `s * t`. -/ @[to_additive "If the left cosets of `t` by elements of `s` are disjoint (but not necessarily distinct!), then the size of `t` divides the size of `s + t`."] theorem card_dvd_card_mul_right {s t : Finset α} : ((· • t) '' (s : Set α)).PairwiseDisjoint id → t.card ∣ (s * t).card := card_dvd_card_image₂_right fun _ _ => mul_right_injective _ @[to_additive (attr := simp)] lemma inv_smul_finset_distrib (a : α) (s : Finset α) : (a • s)⁻¹ = op a⁻¹ • s⁻¹ := by ext; simp [← inv_smul_mem_iff] @[to_additive (attr := simp)] lemma inv_op_smul_finset_distrib (a : α) (s : Finset α) : (op a • s)⁻¹ = a⁻¹ • s⁻¹ := by ext; simp [← inv_smul_mem_iff] end Group section SMulZeroClass variable [Zero β] [SMulZeroClass α β] [DecidableEq β] {s : Finset α} {t : Finset β} {a : α} theorem smul_zero_subset (s : Finset α) : s • (0 : Finset β) ⊆ 0 := by simp [subset_iff, mem_smul] theorem Nonempty.smul_zero (hs : s.Nonempty) : s • (0 : Finset β) = 0 := s.smul_zero_subset.antisymm <| by simpa [mem_smul] using hs theorem zero_mem_smul_finset (h : (0 : β) ∈ t) : (0 : β) ∈ a • t := mem_smul_finset.2 ⟨0, h, smul_zero _⟩ variable [Zero α] [NoZeroSMulDivisors α β] theorem zero_mem_smul_finset_iff (ha : a ≠ 0) : (0 : β) ∈ a • t ↔ (0 : β) ∈ t := by rw [← mem_coe, coe_smul_finset, Set.zero_mem_smul_set_iff ha, mem_coe] end SMulZeroClass section SMulWithZero variable [Zero α] [Zero β] [SMulWithZero α β] [DecidableEq β] {s : Finset α} {t : Finset β} /-! Note that we have neither `SMulWithZero α (Finset β)` nor `SMulWithZero (Finset α) (Finset β)` because `0 • ∅ ≠ 0`. -/ lemma zero_smul_subset (t : Finset β) : (0 : Finset α) • t ⊆ 0 := by simp [subset_iff, mem_smul] lemma Nonempty.zero_smul (ht : t.Nonempty) : (0 : Finset α) • t = 0 := t.zero_smul_subset.antisymm <| by simpa [mem_smul] using ht /-- A nonempty set is scaled by zero to the singleton set containing zero. -/ @[simp] lemma zero_smul_finset {s : Finset β} (h : s.Nonempty) : (0 : α) • s = (0 : Finset β) := coe_injective <| by simpa using @Set.zero_smul_set α _ _ _ _ _ h lemma zero_smul_finset_subset (s : Finset β) : (0 : α) • s ⊆ 0 := image_subset_iff.2 fun x _ ↦ mem_zero.2 <| zero_smul α x variable [NoZeroSMulDivisors α β] {a : α} lemma zero_mem_smul_iff : (0 : β) ∈ s • t ↔ (0 : α) ∈ s ∧ t.Nonempty ∨ (0 : β) ∈ t ∧ s.Nonempty := by rw [← mem_coe, coe_smul, Set.zero_mem_smul_iff]; rfl end SMulWithZero section GroupWithZero variable [DecidableEq β] [GroupWithZero α] [MulAction α β] {s t : Finset β} {a : α} {b : β} @[simp] theorem smul_mem_smul_finset_iff₀ (ha : a ≠ 0) : a • b ∈ a • s ↔ b ∈ s := smul_mem_smul_finset_iff (Units.mk0 a ha) theorem inv_smul_mem_iff₀ (ha : a ≠ 0) : a⁻¹ • b ∈ s ↔ b ∈ a • s := show _ ↔ _ ∈ Units.mk0 a ha • _ from inv_smul_mem_iff theorem mem_inv_smul_finset_iff₀ (ha : a ≠ 0) : b ∈ a⁻¹ • s ↔ a • b ∈ s := show _ ∈ (Units.mk0 a ha)⁻¹ • _ ↔ _ from mem_inv_smul_finset_iff @[simp] theorem smul_finset_subset_smul_finset_iff₀ (ha : a ≠ 0) : a • s ⊆ a • t ↔ s ⊆ t := show Units.mk0 a ha • _ ⊆ _ ↔ _ from smul_finset_subset_smul_finset_iff theorem smul_finset_subset_iff₀ (ha : a ≠ 0) : a • s ⊆ t ↔ s ⊆ a⁻¹ • t := show Units.mk0 a ha • _ ⊆ _ ↔ _ from smul_finset_subset_iff theorem subset_smul_finset_iff₀ (ha : a ≠ 0) : s ⊆ a • t ↔ a⁻¹ • s ⊆ t := show _ ⊆ Units.mk0 a ha • _ ↔ _ from subset_smul_finset_iff theorem smul_finset_inter₀ (ha : a ≠ 0) : a • (s ∩ t) = a • s ∩ a • t := image_inter _ _ <| MulAction.injective₀ ha theorem smul_finset_sdiff₀ (ha : a ≠ 0) : a • (s \ t) = a • s \ a • t := image_sdiff _ _ <| MulAction.injective₀ ha open scoped symmDiff in theorem smul_finset_symmDiff₀ (ha : a ≠ 0) : a • s ∆ t = (a • s) ∆ (a • t) := image_symmDiff _ _ <| MulAction.injective₀ ha lemma smul_finset_univ₀ [Fintype β] (ha : a ≠ 0) : a • (univ : Finset β) = univ := coe_injective <| by push_cast; exact Set.smul_set_univ₀ ha theorem smul_univ₀ [Fintype β] {s : Finset α} (hs : ¬s ⊆ 0) : s • (univ : Finset β) = univ := coe_injective <| by rw [← coe_subset] at hs push_cast at hs ⊢ exact Set.smul_univ₀ hs lemma smul_univ₀' [Fintype β] {s : Finset α} (hs : s.Nontrivial) : s • (univ : Finset β) = univ := coe_injective <| by push_cast; exact Set.smul_univ₀' hs variable [DecidableEq α] @[simp] protected lemma inv_zero : (0 : Finset α)⁻¹ = 0 := by ext; simp @[simp] lemma inv_smul_finset_distrib₀ (a : α) (s : Finset α) : (a • s)⁻¹ = op a⁻¹ • s⁻¹ := by obtain rfl | ha := eq_or_ne a 0 · obtain rfl | hs := s.eq_empty_or_nonempty <;> simp [*] · ext; simp [← inv_smul_mem_iff₀, *] @[simp] lemma inv_op_smul_finset_distrib₀ (a : α) (s : Finset α) : (op a • s)⁻¹ = a⁻¹ • s⁻¹ := by obtain rfl | ha := eq_or_ne a 0 · obtain rfl | hs := s.eq_empty_or_nonempty <;> simp [*] · ext; simp [← inv_smul_mem_iff₀, *] end GroupWithZero section Monoid variable [Monoid α] [AddGroup β] [DistribMulAction α β] [DecidableEq β] (a : α) (s : Finset α) (t : Finset β) @[simp] theorem smul_finset_neg : a • -t = -(a • t) := by simp only [← image_smul, ← image_neg, Function.comp, image_image, smul_neg] @[simp] protected theorem smul_neg : s • -t = -(s • t) := by simp_rw [← image_neg] exact image_image₂_right_comm smul_neg end Monoid section Ring variable [Ring α] [AddCommGroup β] [Module α β] [DecidableEq β] {s : Finset α} {t : Finset β} {a : α} @[simp] theorem neg_smul_finset : -a • t = -(a • t) := by simp only [← image_smul, ← image_neg, image_image, neg_smul, Function.comp] @[simp] protected theorem neg_smul [DecidableEq α] : -s • t = -(s • t) := by simp_rw [← image_neg] exact image₂_image_left_comm neg_smul end Ring section BigOps section CommMonoid variable [CommMonoid α] {ι : Type*} [DecidableEq ι] @[to_additive (attr := simp)] lemma prod_inv_index [InvolutiveInv ι] (s : Finset ι) (f : ι → α) : ∏ i ∈ s⁻¹, f i = ∏ i ∈ s, f i⁻¹ := prod_image inv_injective.injOn @[to_additive existing, simp] lemma prod_neg_index [InvolutiveNeg ι] (s : Finset ι) (f : ι → α) : ∏ i ∈ -s, f i = ∏ i ∈ s, f (-i) := prod_image neg_injective.injOn end CommMonoid section AddCommMonoid variable [AddCommMonoid α] {ι : Type*} [DecidableEq ι] @[to_additive existing, simp] lemma sum_inv_index [InvolutiveInv ι] (s : Finset ι) (f : ι → α) : ∑ i ∈ s⁻¹, f i = ∑ i ∈ s, f i⁻¹ := sum_image inv_injective.injOn end AddCommMonoid end BigOps end Finset namespace Fintype variable {ι : Type*} {α β : ι → Type*} [Fintype ι] [DecidableEq ι] [∀ i, DecidableEq (β i)] @[to_additive] lemma piFinset_smul [∀ i, SMul (α i) (β i)] (s : ∀ i, Finset (α i)) (t : ∀ i, Finset (β i)) : piFinset (fun i ↦ s i • t i) = piFinset s • piFinset t := piFinset_image₂ _ _ _ @[to_additive] lemma piFinset_smul_finset [∀ i, SMul (α i) (β i)] (a : ∀ i, α i) (s : ∀ i, Finset (β i)) : piFinset (fun i ↦ a i • s i) = a • piFinset s := piFinset_image _ _ variable [∀ i, DecidableEq (α i)] @[to_additive] lemma piFinset_mul [∀ i, Mul (α i)] (s t : ∀ i, Finset (α i)) : piFinset (fun i ↦ s i * t i) = piFinset s * piFinset t := piFinset_image₂ _ _ _ @[to_additive] lemma piFinset_div [∀ i, Div (α i)] (s t : ∀ i, Finset (α i)) : piFinset (fun i ↦ s i / t i) = piFinset s / piFinset t := piFinset_image₂ _ _ _ @[to_additive (attr := simp)] lemma piFinset_inv [∀ i, Inv (α i)] (s : ∀ i, Finset (α i)) : piFinset (fun i ↦ (s i)⁻¹) = (piFinset s)⁻¹ := piFinset_image _ _ -- Note: We don't currently state `piFinset_vsub` because there's no -- `[∀ i, VSub (β i) (α i)] → VSub (∀ i, β i) (∀ i, α i)` instance end Fintype open Pointwise namespace Set section One variable [One α] @[to_additive (attr := simp)] theorem toFinset_one : (1 : Set α).toFinset = 1 := rfl -- Porting note: should take priority over `Finite.toFinset_singleton` @[to_additive (attr := simp high)] theorem Finite.toFinset_one (h : (1 : Set α).Finite := finite_one) : h.toFinset = 1 := Finite.toFinset_singleton _ end One section Mul variable [DecidableEq α] [Mul α] {s t : Set α} @[to_additive (attr := simp)] theorem toFinset_mul (s t : Set α) [Fintype s] [Fintype t] [Fintype ↑(s * t)] : (s * t).toFinset = s.toFinset * t.toFinset := toFinset_image2 _ _ _ @[to_additive] theorem Finite.toFinset_mul (hs : s.Finite) (ht : t.Finite) (hf := hs.mul ht) : hf.toFinset = hs.toFinset * ht.toFinset := Finite.toFinset_image2 _ _ _ end Mul section SMul variable [SMul α β] [DecidableEq β] {a : α} {s : Set α} {t : Set β} @[to_additive (attr := simp)] theorem toFinset_smul (s : Set α) (t : Set β) [Fintype s] [Fintype t] [Fintype ↑(s • t)] : (s • t).toFinset = s.toFinset • t.toFinset := toFinset_image2 _ _ _ @[to_additive] theorem Finite.toFinset_smul (hs : s.Finite) (ht : t.Finite) (hf := hs.smul ht) : hf.toFinset = hs.toFinset • ht.toFinset := Finite.toFinset_image2 _ _ _ end SMul section SMul variable [DecidableEq β] [SMul α β] {a : α} {s : Set β} @[to_additive (attr := simp)] theorem toFinset_smul_set (a : α) (s : Set β) [Fintype s] [Fintype ↑(a • s)] : (a • s).toFinset = a • s.toFinset := toFinset_image _ _ @[to_additive] theorem Finite.toFinset_smul_set (hs : s.Finite) (hf : (a • s).Finite := hs.smul_set) : hf.toFinset = a • hs.toFinset := Finite.toFinset_image _ _ _ end SMul section VSub variable [DecidableEq α] [VSub α β] {s t : Set β} @[simp] theorem toFinset_vsub (s t : Set β) [Fintype s] [Fintype t] [Fintype ↑(s -ᵥ t)] : (s -ᵥ t : Set α).toFinset = s.toFinset -ᵥ t.toFinset := toFinset_image2 _ _ _ theorem Finite.toFinset_vsub (hs : s.Finite) (ht : t.Finite) (hf := hs.vsub ht) : hf.toFinset = hs.toFinset -ᵥ ht.toFinset := Finite.toFinset_image2 _ _ _ end VSub section MulAction variable [Group α] [MulAction α β] @[to_additive (attr := simp)] lemma card_smul_set (a : α) (s : Set β) : Nat.card ↥(a • s) = Nat.card s := Nat.card_image_of_injective (MulAction.injective a) _ end MulAction section IsCancelMul variable [Mul α] [IsCancelMul α] {s t : Set α} @[to_additive] lemma card_mul_le : Nat.card (s * t) ≤ Nat.card s * Nat.card t := by classical obtain h | h := (s * t).infinite_or_finite · simp [Set.Infinite.card_eq_zero h] obtain ⟨hs, ht⟩ | rfl | rfl := finite_mul.1 h · lift s to Finset α using hs lift t to Finset α using ht rw [← Finset.coe_mul] simpa [-Finset.coe_mul] using Finset.card_mul_le all_goals simp end IsCancelMul section InvolutiveInv variable [InvolutiveInv α] {s t : Set α} @[to_additive (attr := simp)] lemma card_inv (s : Set α) : Nat.card ↥(s⁻¹) = Nat.card s := by rw [← image_inv, Nat.card_image_of_injective inv_injective] end InvolutiveInv section Group variable [Group α] {s t : Set α} @[to_additive] lemma card_div_le : Nat.card (s / t) ≤ Nat.card s * Nat.card t := by rw [div_eq_mul_inv, ← card_inv t]; exact card_mul_le end Group end Set instance Nat.decidablePred_mem_vadd_set {s : Set ℕ} [DecidablePred (· ∈ s)] (a : ℕ) : DecidablePred (· ∈ a +ᵥ s) := fun n ↦ decidable_of_iff' (a ≤ n ∧ n - a ∈ s) <| by simp only [Set.mem_vadd_set, vadd_eq_add]; aesop
Data\Finset\Powerset.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.Finset.Lattice import Mathlib.Data.Multiset.Powerset /-! # The powerset of a finset -/ namespace Finset open Function Multiset variable {α : Type*} {s t : Finset α} /-! ### powerset -/ section Powerset /-- When `s` is a finset, `s.powerset` is the finset of all subsets of `s` (seen as finsets). -/ def powerset (s : Finset α) : Finset (Finset α) := ⟨(s.1.powerset.pmap Finset.mk) fun _t h => nodup_of_le (mem_powerset.1 h) s.nodup, s.nodup.powerset.pmap fun _a _ha _b _hb => congr_arg Finset.val⟩ @[simp] theorem mem_powerset {s t : Finset α} : s ∈ powerset t ↔ s ⊆ t := by cases s simp [powerset, mem_mk, mem_pmap, mk.injEq, mem_powerset, exists_prop, exists_eq_right, ← val_le_iff] @[simp, norm_cast] theorem coe_powerset (s : Finset α) : (s.powerset : Set (Finset α)) = ((↑) : Finset α → Set α) ⁻¹' (s : Set α).powerset := by ext simp -- Porting note: remove @[simp], simp can prove it theorem empty_mem_powerset (s : Finset α) : ∅ ∈ powerset s := mem_powerset.2 (empty_subset _) -- Porting note: remove @[simp], simp can prove it theorem mem_powerset_self (s : Finset α) : s ∈ powerset s := mem_powerset.2 Subset.rfl @[aesop safe apply (rule_sets := [finsetNonempty])] theorem powerset_nonempty (s : Finset α) : s.powerset.Nonempty := ⟨∅, empty_mem_powerset _⟩ @[simp] theorem powerset_mono {s t : Finset α} : powerset s ⊆ powerset t ↔ s ⊆ t := ⟨fun h => mem_powerset.1 <| h <| mem_powerset_self _, fun st _u h => mem_powerset.2 <| Subset.trans (mem_powerset.1 h) st⟩ theorem powerset_injective : Injective (powerset : Finset α → Finset (Finset α)) := (injective_of_le_imp_le _) powerset_mono.1 @[simp] theorem powerset_inj : powerset s = powerset t ↔ s = t := powerset_injective.eq_iff @[simp] theorem powerset_empty : (∅ : Finset α).powerset = {∅} := rfl @[simp] theorem powerset_eq_singleton_empty : s.powerset = {∅} ↔ s = ∅ := by rw [← powerset_empty, powerset_inj] /-- **Number of Subsets of a Set** -/ @[simp] theorem card_powerset (s : Finset α) : card (powerset s) = 2 ^ card s := (card_pmap _ _ _).trans (Multiset.card_powerset s.1) theorem not_mem_of_mem_powerset_of_not_mem {s t : Finset α} {a : α} (ht : t ∈ s.powerset) (h : a ∉ s) : a ∉ t := by apply mt _ h apply mem_powerset.1 ht theorem powerset_insert [DecidableEq α] (s : Finset α) (a : α) : powerset (insert a s) = s.powerset ∪ s.powerset.image (insert a) := by ext t simp only [exists_prop, mem_powerset, mem_image, mem_union, subset_insert_iff] by_cases h : a ∈ t · constructor · exact fun H => Or.inr ⟨_, H, insert_erase h⟩ · intro H cases' H with H H · exact Subset.trans (erase_subset a t) H · rcases H with ⟨u, hu⟩ rw [← hu.2] exact Subset.trans (erase_insert_subset a u) hu.1 · have : ¬∃ u : Finset α, u ⊆ s ∧ insert a u = t := by simp [Ne.symm (ne_insert_of_not_mem _ _ h)] simp [Finset.erase_eq_of_not_mem h, this] /-- For predicate `p` decidable on subsets, it is decidable whether `p` holds for any subset. -/ instance decidableExistsOfDecidableSubsets {s : Finset α} {p : ∀ t ⊆ s, Prop} [∀ (t) (h : t ⊆ s), Decidable (p t h)] : Decidable (∃ (t : _) (h : t ⊆ s), p t h) := decidable_of_iff (∃ (t : _) (hs : t ∈ s.powerset), p t (mem_powerset.1 hs)) ⟨fun ⟨t, _, hp⟩ => ⟨t, _, hp⟩, fun ⟨t, hs, hp⟩ => ⟨t, mem_powerset.2 hs, hp⟩⟩ /-- For predicate `p` decidable on subsets, it is decidable whether `p` holds for every subset. -/ instance decidableForallOfDecidableSubsets {s : Finset α} {p : ∀ t ⊆ s, Prop} [∀ (t) (h : t ⊆ s), Decidable (p t h)] : Decidable (∀ (t) (h : t ⊆ s), p t h) := decidable_of_iff (∀ (t) (h : t ∈ s.powerset), p t (mem_powerset.1 h)) ⟨fun h t hs => h t (mem_powerset.2 hs), fun h _ _ => h _ _⟩ /-- For predicate `p` decidable on subsets, it is decidable whether `p` holds for any subset. -/ instance decidableExistsOfDecidableSubsets' {s : Finset α} {p : Finset α → Prop} [∀ t, Decidable (p t)] : Decidable (∃ t ⊆ s, p t) := decidable_of_iff (∃ (t : _) (_h : t ⊆ s), p t) $ by simp /-- For predicate `p` decidable on subsets, it is decidable whether `p` holds for every subset. -/ instance decidableForallOfDecidableSubsets' {s : Finset α} {p : Finset α → Prop} [∀ t, Decidable (p t)] : Decidable (∀ t ⊆ s, p t) := decidable_of_iff (∀ (t : _) (_h : t ⊆ s), p t) $ by simp end Powerset section SSubsets variable [DecidableEq α] /-- For `s` a finset, `s.ssubsets` is the finset comprising strict subsets of `s`. -/ def ssubsets (s : Finset α) : Finset (Finset α) := erase (powerset s) s @[simp] theorem mem_ssubsets {s t : Finset α} : t ∈ s.ssubsets ↔ t ⊂ s := by rw [ssubsets, mem_erase, mem_powerset, ssubset_iff_subset_ne, and_comm] theorem empty_mem_ssubsets {s : Finset α} (h : s.Nonempty) : ∅ ∈ s.ssubsets := by rw [mem_ssubsets, ssubset_iff_subset_ne] exact ⟨empty_subset s, h.ne_empty.symm⟩ /-- For predicate `p` decidable on ssubsets, it is decidable whether `p` holds for any ssubset. -/ def decidableExistsOfDecidableSSubsets {s : Finset α} {p : ∀ t ⊂ s, Prop} [∀ t h, Decidable (p t h)] : Decidable (∃ t h, p t h) := decidable_of_iff (∃ (t : _) (hs : t ∈ s.ssubsets), p t (mem_ssubsets.1 hs)) ⟨fun ⟨t, _, hp⟩ => ⟨t, _, hp⟩, fun ⟨t, hs, hp⟩ => ⟨t, mem_ssubsets.2 hs, hp⟩⟩ /-- For predicate `p` decidable on ssubsets, it is decidable whether `p` holds for every ssubset. -/ def decidableForallOfDecidableSSubsets {s : Finset α} {p : ∀ t ⊂ s, Prop} [∀ t h, Decidable (p t h)] : Decidable (∀ t h, p t h) := decidable_of_iff (∀ (t) (h : t ∈ s.ssubsets), p t (mem_ssubsets.1 h)) ⟨fun h t hs => h t (mem_ssubsets.2 hs), fun h _ _ => h _ _⟩ /-- A version of `Finset.decidableExistsOfDecidableSSubsets` with a non-dependent `p`. Typeclass inference cannot find `hu` here, so this is not an instance. -/ def decidableExistsOfDecidableSSubsets' {s : Finset α} {p : Finset α → Prop} (hu : ∀ t ⊂ s, Decidable (p t)) : Decidable (∃ (t : _) (_h : t ⊂ s), p t) := @Finset.decidableExistsOfDecidableSSubsets _ _ _ _ hu /-- A version of `Finset.decidableForallOfDecidableSSubsets` with a non-dependent `p`. Typeclass inference cannot find `hu` here, so this is not an instance. -/ def decidableForallOfDecidableSSubsets' {s : Finset α} {p : Finset α → Prop} (hu : ∀ t ⊂ s, Decidable (p t)) : Decidable (∀ t ⊂ s, p t) := @Finset.decidableForallOfDecidableSSubsets _ _ _ _ hu end SSubsets section powersetCard variable {n} {s t : Finset α} /-- Given an integer `n` and a finset `s`, then `powersetCard n s` is the finset of subsets of `s` of cardinality `n`. -/ def powersetCard (n : ℕ) (s : Finset α) : Finset (Finset α) := ⟨((s.1.powersetCard n).pmap Finset.mk) fun _t h => nodup_of_le (mem_powersetCard.1 h).1 s.2, s.2.powersetCard.pmap fun _a _ha _b _hb => congr_arg Finset.val⟩ @[simp] lemma mem_powersetCard : s ∈ powersetCard n t ↔ s ⊆ t ∧ card s = n := by cases s; simp [powersetCard, val_le_iff.symm] @[simp] theorem powersetCard_mono {n} {s t : Finset α} (h : s ⊆ t) : powersetCard n s ⊆ powersetCard n t := fun _u h' => mem_powersetCard.2 <| And.imp (fun h₂ => Subset.trans h₂ h) id (mem_powersetCard.1 h') /-- **Formula for the Number of Combinations** -/ @[simp] theorem card_powersetCard (n : ℕ) (s : Finset α) : card (powersetCard n s) = Nat.choose (card s) n := (card_pmap _ _ _).trans (Multiset.card_powersetCard n s.1) @[simp] theorem powersetCard_zero (s : Finset α) : s.powersetCard 0 = {∅} := by ext; rw [mem_powersetCard, mem_singleton, card_eq_zero] refine ⟨fun h => h.2, fun h => by rw [h] exact ⟨empty_subset s, rfl⟩⟩ lemma powersetCard_empty_subsingleton (n : ℕ) : (powersetCard n (∅ : Finset α) : Set $ Finset α).Subsingleton := by simp [Set.Subsingleton, subset_empty] @[simp] theorem map_val_val_powersetCard (s : Finset α) (i : ℕ) : (s.powersetCard i).val.map Finset.val = s.1.powersetCard i := by simp [Finset.powersetCard, map_pmap, pmap_eq_map, map_id'] theorem powersetCard_one (s : Finset α) : s.powersetCard 1 = s.map ⟨_, Finset.singleton_injective⟩ := eq_of_veq <| Multiset.map_injective val_injective <| by simp [Multiset.powersetCard_one] @[simp] lemma powersetCard_eq_empty : powersetCard n s = ∅ ↔ s.card < n := by refine ⟨?_, fun h ↦ card_eq_zero.1 $ by rw [card_powersetCard, Nat.choose_eq_zero_of_lt h]⟩ contrapose! exact fun h ↦ nonempty_iff_ne_empty.1 $ (exists_subset_card_eq h).imp $ by simp @[simp] lemma powersetCard_card_add (s : Finset α) (hn : 0 < n) : s.powersetCard (s.card + n) = ∅ := by simpa theorem powersetCard_eq_filter {n} {s : Finset α} : powersetCard n s = (powerset s).filter fun x => x.card = n := by ext simp [mem_powersetCard] theorem powersetCard_succ_insert [DecidableEq α] {x : α} {s : Finset α} (h : x ∉ s) (n : ℕ) : powersetCard n.succ (insert x s) = powersetCard n.succ s ∪ (powersetCard n s).image (insert x) := by rw [powersetCard_eq_filter, powerset_insert, filter_union, ← powersetCard_eq_filter] congr rw [powersetCard_eq_filter, filter_image] congr 1 ext t simp only [mem_powerset, mem_filter, Function.comp_apply, and_congr_right_iff] intro ht have : x ∉ t := fun H => h (ht H) simp [card_insert_of_not_mem this, Nat.succ_inj'] @[simp, aesop safe apply (rule_sets := [finsetNonempty])] lemma powersetCard_nonempty : (powersetCard n s).Nonempty ↔ n ≤ s.card := by aesop (add simp [Finset.Nonempty, exists_subset_card_eq, card_le_card]) @[simp] theorem powersetCard_self (s : Finset α) : powersetCard s.card s = {s} := by ext rw [mem_powersetCard, mem_singleton] constructor · exact fun ⟨hs, hc⟩ => eq_of_subset_of_card_le hs hc.ge · rintro rfl simp theorem pairwise_disjoint_powersetCard (s : Finset α) : Pairwise fun i j => Disjoint (s.powersetCard i) (s.powersetCard j) := fun _i _j hij => Finset.disjoint_left.mpr fun _x hi hj => hij <| (mem_powersetCard.mp hi).2.symm.trans (mem_powersetCard.mp hj).2 theorem powerset_card_disjiUnion (s : Finset α) : Finset.powerset s = (range (s.card + 1)).disjiUnion (fun i => powersetCard i s) (s.pairwise_disjoint_powersetCard.set_pairwise _) := by refine ext fun a => ⟨fun ha => ?_, fun ha => ?_⟩ · rw [mem_disjiUnion] exact ⟨a.card, mem_range.mpr (Nat.lt_succ_of_le (card_le_card (mem_powerset.mp ha))), mem_powersetCard.mpr ⟨mem_powerset.mp ha, rfl⟩⟩ · rcases mem_disjiUnion.mp ha with ⟨i, _hi, ha⟩ exact mem_powerset.mpr (mem_powersetCard.mp ha).1 theorem powerset_card_biUnion [DecidableEq (Finset α)] (s : Finset α) : Finset.powerset s = (range (s.card + 1)).biUnion fun i => powersetCard i s := by simpa only [disjiUnion_eq_biUnion] using powerset_card_disjiUnion s theorem powersetCard_sup [DecidableEq α] (u : Finset α) (n : ℕ) (hn : n < u.card) : (powersetCard n.succ u).sup id = u := by apply le_antisymm · simp_rw [Finset.sup_le_iff, mem_powersetCard] rintro x ⟨h, -⟩ exact h · rw [sup_eq_biUnion, le_iff_subset, subset_iff] intro x hx simp only [mem_biUnion, exists_prop, id] obtain ⟨t, ht⟩ : ∃ t, t ∈ powersetCard n (u.erase x) := powersetCard_nonempty.2 (le_trans (Nat.le_sub_one_of_lt hn) pred_card_le_card_erase) refine ⟨insert x t, ?_, mem_insert_self _ _⟩ rw [← insert_erase hx, powersetCard_succ_insert (not_mem_erase _ _)] exact mem_union_right _ (mem_image_of_mem _ ht) theorem powersetCard_map {β : Type*} (f : α ↪ β) (n : ℕ) (s : Finset α) : powersetCard n (s.map f) = (powersetCard n s).map (mapEmbedding f).toEmbedding := ext fun t => by simp only [card_map, mem_powersetCard, le_eq_subset, gt_iff_lt, mem_map, mapEmbedding_apply] constructor · classical intro h have : map f (filter (fun x => (f x ∈ t)) s) = t := by ext x simp only [mem_map, mem_filter, decide_eq_true_eq] exact ⟨fun ⟨_y, ⟨_hy₁, hy₂⟩, hy₃⟩ => hy₃ ▸ hy₂, fun hx => let ⟨y, hy⟩ := mem_map.1 (h.1 hx); ⟨y, ⟨hy.1, hy.2 ▸ hx⟩, hy.2⟩⟩ refine ⟨_, ?_, this⟩ rw [← card_map f, this, h.2]; simp · rintro ⟨a, ⟨has, rfl⟩, rfl⟩ dsimp [RelEmbedding.coe_toEmbedding] -- Porting note: Why is `rw` required here and not `simp`? rw [mapEmbedding_apply] simp [has] end powersetCard end Finset
Data\Finset\Preimage.lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import Mathlib.Data.Set.Finite /-! # Preimage of a `Finset` under an injective map. -/ assert_not_exists Finset.sum open Set Function universe u v w x variable {α : Type u} {β : Type v} {ι : Sort w} {γ : Type x} namespace Finset section Preimage /-- Preimage of `s : Finset β` under a map `f` injective on `f ⁻¹' s` as a `Finset`. -/ noncomputable def preimage (s : Finset β) (f : α → β) (hf : Set.InjOn f (f ⁻¹' ↑s)) : Finset α := (s.finite_toSet.preimage hf).toFinset @[simp] theorem mem_preimage {f : α → β} {s : Finset β} {hf : Set.InjOn f (f ⁻¹' ↑s)} {x : α} : x ∈ preimage s f hf ↔ f x ∈ s := Set.Finite.mem_toFinset _ @[simp, norm_cast] theorem coe_preimage {f : α → β} (s : Finset β) (hf : Set.InjOn f (f ⁻¹' ↑s)) : (↑(preimage s f hf) : Set α) = f ⁻¹' ↑s := Set.Finite.coe_toFinset _ @[simp] theorem preimage_empty {f : α → β} : preimage ∅ f (by simp [InjOn]) = ∅ := Finset.coe_injective (by simp) @[simp] theorem preimage_univ {f : α → β} [Fintype α] [Fintype β] (hf) : preimage univ f hf = univ := Finset.coe_injective (by simp) @[simp] theorem preimage_inter [DecidableEq α] [DecidableEq β] {f : α → β} {s t : Finset β} (hs : Set.InjOn f (f ⁻¹' ↑s)) (ht : Set.InjOn f (f ⁻¹' ↑t)) : (preimage (s ∩ t) f fun x₁ hx₁ x₂ hx₂ => hs (mem_of_mem_inter_left hx₁) (mem_of_mem_inter_left hx₂)) = preimage s f hs ∩ preimage t f ht := Finset.coe_injective (by simp) @[simp] theorem preimage_union [DecidableEq α] [DecidableEq β] {f : α → β} {s t : Finset β} (hst) : preimage (s ∪ t) f hst = (preimage s f fun x₁ hx₁ x₂ hx₂ => hst (mem_union_left _ hx₁) (mem_union_left _ hx₂)) ∪ preimage t f fun x₁ hx₁ x₂ hx₂ => hst (mem_union_right _ hx₁) (mem_union_right _ hx₂) := Finset.coe_injective (by simp) @[simp, nolint simpNF] -- Porting note: linter complains that LHS doesn't simplify theorem preimage_compl [DecidableEq α] [DecidableEq β] [Fintype α] [Fintype β] {f : α → β} (s : Finset β) (hf : Function.Injective f) : preimage sᶜ f hf.injOn = (preimage s f hf.injOn)ᶜ := Finset.coe_injective (by simp) @[simp] lemma preimage_map (f : α ↪ β) (s : Finset α) : (s.map f).preimage f f.injective.injOn = s := coe_injective <| by simp only [coe_preimage, coe_map, Set.preimage_image_eq _ f.injective] theorem monotone_preimage {f : α → β} (h : Injective f) : Monotone fun s => preimage s f h.injOn := fun _ _ H _ hx => mem_preimage.2 (H <| mem_preimage.1 hx) theorem image_subset_iff_subset_preimage [DecidableEq β] {f : α → β} {s : Finset α} {t : Finset β} (hf : Set.InjOn f (f ⁻¹' ↑t)) : s.image f ⊆ t ↔ s ⊆ t.preimage f hf := image_subset_iff.trans <| by simp only [subset_iff, mem_preimage] theorem map_subset_iff_subset_preimage {f : α ↪ β} {s : Finset α} {t : Finset β} : s.map f ⊆ t ↔ s ⊆ t.preimage f f.injective.injOn := by classical rw [map_eq_image, image_subset_iff_subset_preimage] theorem image_preimage [DecidableEq β] (f : α → β) (s : Finset β) [∀ x, Decidable (x ∈ Set.range f)] (hf : Set.InjOn f (f ⁻¹' ↑s)) : image f (preimage s f hf) = s.filter fun x => x ∈ Set.range f := Finset.coe_inj.1 <| by simp only [coe_image, coe_preimage, coe_filter, Set.image_preimage_eq_inter_range, ← Set.sep_mem_eq]; rfl theorem image_preimage_of_bij [DecidableEq β] (f : α → β) (s : Finset β) (hf : Set.BijOn f (f ⁻¹' ↑s) ↑s) : image f (preimage s f hf.injOn) = s := Finset.coe_inj.1 <| by simpa using hf.image_eq theorem preimage_subset {f : α ↪ β} {s : Finset β} {t : Finset α} (hs : s ⊆ t.map f) : s.preimage f f.injective.injOn ⊆ t := fun _ h => (mem_map' f).1 (hs (mem_preimage.1 h)) theorem subset_map_iff {f : α ↪ β} {s : Finset β} {t : Finset α} : s ⊆ t.map f ↔ ∃ u ⊆ t, s = u.map f := by classical simp_rw [← coe_subset, coe_map, subset_image_iff, map_eq_image, eq_comm] theorem sigma_preimage_mk {β : α → Type*} [DecidableEq α] (s : Finset (Σa, β a)) (t : Finset α) : (t.sigma fun a => s.preimage (Sigma.mk a) sigma_mk_injective.injOn) = s.filter fun a => a.1 ∈ t := by ext x simp [and_comm] theorem sigma_preimage_mk_of_subset {β : α → Type*} [DecidableEq α] (s : Finset (Σa, β a)) {t : Finset α} (ht : s.image Sigma.fst ⊆ t) : (t.sigma fun a => s.preimage (Sigma.mk a) sigma_mk_injective.injOn) = s := by rw [sigma_preimage_mk, filter_true_of_mem <| image_subset_iff.1 ht] theorem sigma_image_fst_preimage_mk {β : α → Type*} [DecidableEq α] (s : Finset (Σa, β a)) : ((s.image Sigma.fst).sigma fun a => s.preimage (Sigma.mk a) sigma_mk_injective.injOn) = s := s.sigma_preimage_mk_of_subset (Subset.refl _) end Preimage end Finset
Data\Finset\Prod.lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Oliver Nash -/ import Mathlib.Data.Finset.Card /-! # Finsets in product types This file defines finset constructions on the product type `α × β`. Beware not to confuse with the `Finset.prod` operation which computes the multiplicative product. ## Main declarations * `Finset.product`: Turns `s : Finset α`, `t : Finset β` into their product in `Finset (α × β)`. * `Finset.diag`: For `s : Finset α`, `s.diag` is the `Finset (α × α)` of pairs `(a, a)` with `a ∈ s`. * `Finset.offDiag`: For `s : Finset α`, `s.offDiag` is the `Finset (α × α)` of pairs `(a, b)` with `a, b ∈ s` and `a ≠ b`. -/ assert_not_exists MonoidWithZero open Multiset variable {α β γ : Type*} namespace Finset /-! ### prod -/ section Prod variable {s s' : Finset α} {t t' : Finset β} {a : α} {b : β} /-- `product s t` is the set of pairs `(a, b)` such that `a ∈ s` and `b ∈ t`. -/ protected def product (s : Finset α) (t : Finset β) : Finset (α × β) := ⟨_, s.nodup.product t.nodup⟩ instance instSProd : SProd (Finset α) (Finset β) (Finset (α × β)) where sprod := Finset.product @[simp] theorem product_val : (s ×ˢ t).1 = s.1 ×ˢ t.1 := rfl @[simp] theorem mem_product {p : α × β} : p ∈ s ×ˢ t ↔ p.1 ∈ s ∧ p.2 ∈ t := Multiset.mem_product theorem mk_mem_product (ha : a ∈ s) (hb : b ∈ t) : (a, b) ∈ s ×ˢ t := mem_product.2 ⟨ha, hb⟩ @[simp, norm_cast] theorem coe_product (s : Finset α) (t : Finset β) : (↑(s ×ˢ t) : Set (α × β)) = (s : Set α) ×ˢ t := Set.ext fun _ => Finset.mem_product theorem subset_product_image_fst [DecidableEq α] : (s ×ˢ t).image Prod.fst ⊆ s := fun i => by simp (config := { contextual := true }) [mem_image] theorem subset_product_image_snd [DecidableEq β] : (s ×ˢ t).image Prod.snd ⊆ t := fun i => by simp (config := { contextual := true }) [mem_image] theorem product_image_fst [DecidableEq α] (ht : t.Nonempty) : (s ×ˢ t).image Prod.fst = s := by ext i simp [mem_image, ht.exists_mem] theorem product_image_snd [DecidableEq β] (ht : s.Nonempty) : (s ×ˢ t).image Prod.snd = t := by ext i simp [mem_image, ht.exists_mem] theorem subset_product [DecidableEq α] [DecidableEq β] {s : Finset (α × β)} : s ⊆ s.image Prod.fst ×ˢ s.image Prod.snd := fun _ hp => mem_product.2 ⟨mem_image_of_mem _ hp, mem_image_of_mem _ hp⟩ @[gcongr] theorem product_subset_product (hs : s ⊆ s') (ht : t ⊆ t') : s ×ˢ t ⊆ s' ×ˢ t' := fun ⟨_, _⟩ h => mem_product.2 ⟨hs (mem_product.1 h).1, ht (mem_product.1 h).2⟩ @[gcongr] theorem product_subset_product_left (hs : s ⊆ s') : s ×ˢ t ⊆ s' ×ˢ t := product_subset_product hs (Subset.refl _) @[gcongr] theorem product_subset_product_right (ht : t ⊆ t') : s ×ˢ t ⊆ s ×ˢ t' := product_subset_product (Subset.refl _) ht theorem map_swap_product (s : Finset α) (t : Finset β) : (t ×ˢ s).map ⟨Prod.swap, Prod.swap_injective⟩ = s ×ˢ t := coe_injective <| by push_cast exact Set.image_swap_prod _ _ @[simp] theorem image_swap_product [DecidableEq (α × β)] (s : Finset α) (t : Finset β) : (t ×ˢ s).image Prod.swap = s ×ˢ t := coe_injective <| by push_cast exact Set.image_swap_prod _ _ theorem product_eq_biUnion [DecidableEq (α × β)] (s : Finset α) (t : Finset β) : s ×ˢ t = s.biUnion fun a => t.image fun b => (a, b) := ext fun ⟨x, y⟩ => by simp only [mem_product, mem_biUnion, mem_image, exists_prop, Prod.mk.inj_iff, and_left_comm, exists_and_left, exists_eq_right, exists_eq_left] theorem product_eq_biUnion_right [DecidableEq (α × β)] (s : Finset α) (t : Finset β) : s ×ˢ t = t.biUnion fun b => s.image fun a => (a, b) := ext fun ⟨x, y⟩ => by simp only [mem_product, mem_biUnion, mem_image, exists_prop, Prod.mk.inj_iff, and_left_comm, exists_and_left, exists_eq_right, exists_eq_left] /-- See also `Finset.sup_product_left`. -/ @[simp] theorem product_biUnion [DecidableEq γ] (s : Finset α) (t : Finset β) (f : α × β → Finset γ) : (s ×ˢ t).biUnion f = s.biUnion fun a => t.biUnion fun b => f (a, b) := by classical simp_rw [product_eq_biUnion, biUnion_biUnion, image_biUnion] @[simp] theorem card_product (s : Finset α) (t : Finset β) : card (s ×ˢ t) = card s * card t := Multiset.card_product _ _ /-- The product of two Finsets is nontrivial iff both are nonempty at least one of them is nontrivial. -/ lemma nontrivial_prod_iff : (s ×ˢ t).Nontrivial ↔ s.Nonempty ∧ t.Nonempty ∧ (s.Nontrivial ∨ t.Nontrivial) := by simp_rw [← card_pos, ← one_lt_card_iff_nontrivial, card_product]; apply Nat.one_lt_mul_iff theorem filter_product (p : α → Prop) (q : β → Prop) [DecidablePred p] [DecidablePred q] : ((s ×ˢ t).filter fun x : α × β => p x.1 ∧ q x.2) = s.filter p ×ˢ t.filter q := by ext ⟨a, b⟩ simp [mem_filter, mem_product, decide_eq_true_eq, and_comm, and_left_comm, and_assoc] theorem filter_product_left (p : α → Prop) [DecidablePred p] : ((s ×ˢ t).filter fun x : α × β => p x.1) = s.filter p ×ˢ t := by simpa using filter_product p fun _ => true theorem filter_product_right (q : β → Prop) [DecidablePred q] : ((s ×ˢ t).filter fun x : α × β => q x.2) = s ×ˢ t.filter q := by simpa using filter_product (fun _ : α => true) q theorem filter_product_card (s : Finset α) (t : Finset β) (p : α → Prop) (q : β → Prop) [DecidablePred p] [DecidablePred q] : ((s ×ˢ t).filter fun x : α × β => (p x.1) = (q x.2)).card = (s.filter p).card * (t.filter q).card + (s.filter (¬ p ·)).card * (t.filter (¬ q ·)).card := by classical rw [← card_product, ← card_product, ← filter_product, ← filter_product, ← card_union_of_disjoint] · apply congr_arg ext ⟨a, b⟩ simp only [filter_union_right, mem_filter, mem_product] constructor <;> intro h <;> use h.1 · simp only [h.2, Function.comp_apply, Decidable.em, and_self] · revert h simp only [Function.comp_apply, and_imp] rintro _ _ (_|_) <;> simp [*] · apply Finset.disjoint_filter_filter' exact (disjoint_compl_right.inf_left _).inf_right _ @[simp] theorem empty_product (t : Finset β) : (∅ : Finset α) ×ˢ t = ∅ := rfl @[simp] theorem product_empty (s : Finset α) : s ×ˢ (∅ : Finset β) = ∅ := eq_empty_of_forall_not_mem fun _ h => not_mem_empty _ (Finset.mem_product.1 h).2 theorem Nonempty.product (hs : s.Nonempty) (ht : t.Nonempty) : (s ×ˢ t).Nonempty := let ⟨x, hx⟩ := hs let ⟨y, hy⟩ := ht ⟨(x, y), mem_product.2 ⟨hx, hy⟩⟩ theorem Nonempty.fst (h : (s ×ˢ t).Nonempty) : s.Nonempty := let ⟨xy, hxy⟩ := h ⟨xy.1, (mem_product.1 hxy).1⟩ theorem Nonempty.snd (h : (s ×ˢ t).Nonempty) : t.Nonempty := let ⟨xy, hxy⟩ := h ⟨xy.2, (mem_product.1 hxy).2⟩ @[simp, aesop safe apply (rule_sets := [finsetNonempty])] theorem nonempty_product : (s ×ˢ t).Nonempty ↔ s.Nonempty ∧ t.Nonempty := ⟨fun h => ⟨h.fst, h.snd⟩, fun h => h.1.product h.2⟩ @[simp] theorem product_eq_empty {s : Finset α} {t : Finset β} : s ×ˢ t = ∅ ↔ s = ∅ ∨ t = ∅ := by rw [← not_nonempty_iff_eq_empty, nonempty_product, not_and_or, not_nonempty_iff_eq_empty, not_nonempty_iff_eq_empty] @[simp] theorem singleton_product {a : α} : ({a} : Finset α) ×ˢ t = t.map ⟨Prod.mk a, Prod.mk.inj_left _⟩ := by ext ⟨x, y⟩ simp [and_left_comm, eq_comm] @[simp] theorem product_singleton {b : β} : s ×ˢ {b} = s.map ⟨fun i => (i, b), Prod.mk.inj_right _⟩ := by ext ⟨x, y⟩ simp [and_left_comm, eq_comm] theorem singleton_product_singleton {a : α} {b : β} : ({a} ×ˢ {b} : Finset _) = {(a, b)} := by simp only [product_singleton, Function.Embedding.coeFn_mk, map_singleton] @[simp] theorem union_product [DecidableEq α] [DecidableEq β] : (s ∪ s') ×ˢ t = s ×ˢ t ∪ s' ×ˢ t := by ext ⟨x, y⟩ simp only [or_and_right, mem_union, mem_product] @[simp] theorem product_union [DecidableEq α] [DecidableEq β] : s ×ˢ (t ∪ t') = s ×ˢ t ∪ s ×ˢ t' := by ext ⟨x, y⟩ simp only [and_or_left, mem_union, mem_product] theorem inter_product [DecidableEq α] [DecidableEq β] : (s ∩ s') ×ˢ t = s ×ˢ t ∩ s' ×ˢ t := by ext ⟨x, y⟩ simp only [← and_and_right, mem_inter, mem_product] theorem product_inter [DecidableEq α] [DecidableEq β] : s ×ˢ (t ∩ t') = s ×ˢ t ∩ s ×ˢ t' := by ext ⟨x, y⟩ simp only [← and_and_left, mem_inter, mem_product] theorem product_inter_product [DecidableEq α] [DecidableEq β] : s ×ˢ t ∩ s' ×ˢ t' = (s ∩ s') ×ˢ (t ∩ t') := by ext ⟨x, y⟩ simp only [and_assoc, and_left_comm, mem_inter, mem_product] theorem disjoint_product : Disjoint (s ×ˢ t) (s' ×ˢ t') ↔ Disjoint s s' ∨ Disjoint t t' := by simp_rw [← disjoint_coe, coe_product, Set.disjoint_prod] @[simp] theorem disjUnion_product (hs : Disjoint s s') : s.disjUnion s' hs ×ˢ t = (s ×ˢ t).disjUnion (s' ×ˢ t) (disjoint_product.mpr <| Or.inl hs) := eq_of_veq <| Multiset.add_product _ _ _ @[simp] theorem product_disjUnion (ht : Disjoint t t') : s ×ˢ t.disjUnion t' ht = (s ×ˢ t).disjUnion (s ×ˢ t') (disjoint_product.mpr <| Or.inr ht) := eq_of_veq <| Multiset.product_add _ _ _ end Prod section Diag variable [DecidableEq α] (s t : Finset α) /-- Given a finite set `s`, the diagonal, `s.diag` is the set of pairs of the form `(a, a)` for `a ∈ s`. -/ def diag := (s ×ˢ s).filter fun a : α × α => a.fst = a.snd /-- Given a finite set `s`, the off-diagonal, `s.offDiag` is the set of pairs `(a, b)` with `a ≠ b` for `a, b ∈ s`. -/ def offDiag := (s ×ˢ s).filter fun a : α × α => a.fst ≠ a.snd variable {s} {x : α × α} @[simp] theorem mem_diag : x ∈ s.diag ↔ x.1 ∈ s ∧ x.1 = x.2 := by simp (config := { contextual := true }) [diag] @[simp] theorem mem_offDiag : x ∈ s.offDiag ↔ x.1 ∈ s ∧ x.2 ∈ s ∧ x.1 ≠ x.2 := by simp [offDiag, and_assoc] variable (s) @[simp, norm_cast] theorem coe_offDiag : (s.offDiag : Set (α × α)) = (s : Set α).offDiag := Set.ext fun _ => mem_offDiag @[simp] theorem diag_card : (diag s).card = s.card := by suffices diag s = s.image fun a => (a, a) by rw [this] apply card_image_of_injOn exact fun x1 _ x2 _ h3 => (Prod.mk.inj h3).1 ext ⟨a₁, a₂⟩ rw [mem_diag] constructor <;> intro h <;> rw [Finset.mem_image] at * · use a₁ simpa using h · rcases h with ⟨a, h1, h2⟩ have h := Prod.mk.inj h2 rw [← h.1, ← h.2] use h1 @[simp] theorem offDiag_card : (offDiag s).card = s.card * s.card - s.card := suffices (diag s).card + (offDiag s).card = s.card * s.card by rw [s.diag_card] at this; omega by rw [← card_product, diag, offDiag] conv_rhs => rw [← filter_card_add_filter_neg_card_eq_card (fun a => a.1 = a.2)] @[mono] theorem diag_mono : Monotone (diag : Finset α → Finset (α × α)) := fun _ _ h _ hx => mem_diag.2 <| And.imp_left (@h _) <| mem_diag.1 hx @[mono] theorem offDiag_mono : Monotone (offDiag : Finset α → Finset (α × α)) := fun _ _ h _ hx => mem_offDiag.2 <| And.imp (@h _) (And.imp_left <| @h _) <| mem_offDiag.1 hx @[simp] theorem diag_empty : (∅ : Finset α).diag = ∅ := rfl @[simp] theorem offDiag_empty : (∅ : Finset α).offDiag = ∅ := rfl @[simp] theorem diag_union_offDiag : s.diag ∪ s.offDiag = s ×ˢ s := by conv_rhs => rw [← filter_union_filter_neg_eq (fun a => a.1 = a.2) (s ×ˢ s)] rfl @[simp] theorem disjoint_diag_offDiag : Disjoint s.diag s.offDiag := disjoint_filter_filter_neg (s ×ˢ s) (s ×ˢ s) (fun a => a.1 = a.2) theorem product_sdiff_diag : s ×ˢ s \ s.diag = s.offDiag := by rw [← diag_union_offDiag, union_comm, union_sdiff_self, sdiff_eq_self_of_disjoint (disjoint_diag_offDiag _).symm] theorem product_sdiff_offDiag : s ×ˢ s \ s.offDiag = s.diag := by rw [← diag_union_offDiag, union_sdiff_self, sdiff_eq_self_of_disjoint (disjoint_diag_offDiag _)] theorem diag_inter : (s ∩ t).diag = s.diag ∩ t.diag := ext fun x => by simpa only [mem_diag, mem_inter] using and_and_right theorem offDiag_inter : (s ∩ t).offDiag = s.offDiag ∩ t.offDiag := coe_injective <| by push_cast exact Set.offDiag_inter _ _ theorem diag_union : (s ∪ t).diag = s.diag ∪ t.diag := by ext ⟨i, j⟩ simp only [mem_diag, mem_union, or_and_right] variable {s t} theorem offDiag_union (h : Disjoint s t) : (s ∪ t).offDiag = s.offDiag ∪ t.offDiag ∪ s ×ˢ t ∪ t ×ˢ s := coe_injective <| by push_cast exact Set.offDiag_union (disjoint_coe.2 h) variable (a : α) @[simp] theorem offDiag_singleton : ({a} : Finset α).offDiag = ∅ := by simp [← Finset.card_eq_zero] theorem diag_singleton : ({a} : Finset α).diag = {(a, a)} := by rw [← product_sdiff_offDiag, offDiag_singleton, sdiff_empty, singleton_product_singleton] theorem diag_insert : (insert a s).diag = insert (a, a) s.diag := by rw [insert_eq, insert_eq, diag_union, diag_singleton] theorem offDiag_insert (has : a ∉ s) : (insert a s).offDiag = s.offDiag ∪ {a} ×ˢ s ∪ s ×ˢ {a} := by rw [insert_eq, union_comm, offDiag_union (disjoint_singleton_right.2 has), offDiag_singleton, union_empty, union_right_comm] theorem offDiag_filter_lt_eq_filter_le {ι} [PartialOrder ι] [DecidableEq ι] [DecidableRel (LE.le (α := ι))] [DecidableRel (LT.lt (α := ι))] (s : Finset ι) : s.offDiag.filter (fun i => i.1 < i.2) = s.offDiag.filter (fun i => i.1 ≤ i.2) := by rw [Finset.filter_inj'] rintro ⟨i, j⟩ simp_rw [mem_offDiag, and_imp] rintro _ _ h rw [Ne.le_iff_lt h] end Diag end Finset
Data\Finset\Sigma.lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Yaël Dillies, Bhavik Mehta -/ import Mathlib.Data.Finset.Lattice import Mathlib.Data.Set.Sigma /-! # Finite sets in a sigma type This file defines a few `Finset` constructions on `Σ i, α i`. ## Main declarations * `Finset.sigma`: Given a finset `s` in `ι` and finsets `t i` in each `α i`, `s.sigma t` is the finset of the dependent sum `Σ i, α i` * `Finset.sigmaLift`: Lifts maps `α i → β i → Finset (γ i)` to a map `Σ i, α i → Σ i, β i → Finset (Σ i, γ i)`. ## TODO `Finset.sigmaLift` can be generalized to any alternative functor. But to make the generalization worth it, we must first refactor the functor library so that the `alternative` instance for `Finset` is computable and universe-polymorphic. -/ open Function Multiset variable {ι : Type*} namespace Finset section Sigma variable {α : ι → Type*} {β : Type*} (s s₁ s₂ : Finset ι) (t t₁ t₂ : ∀ i, Finset (α i)) /-- `s.sigma t` is the finset of dependent pairs `⟨i, a⟩` such that `i ∈ s` and `a ∈ t i`. -/ protected def sigma : Finset (Σi, α i) := ⟨_, s.nodup.sigma fun i => (t i).nodup⟩ variable {s s₁ s₂ t t₁ t₂} @[simp] theorem mem_sigma {a : Σi, α i} : a ∈ s.sigma t ↔ a.1 ∈ s ∧ a.2 ∈ t a.1 := Multiset.mem_sigma @[simp, norm_cast] theorem coe_sigma (s : Finset ι) (t : ∀ i, Finset (α i)) : (s.sigma t : Set (Σ i, α i)) = (s : Set ι).sigma fun i ↦ (t i : Set (α i)) := Set.ext fun _ => mem_sigma @[simp, aesop safe apply (rule_sets := [finsetNonempty])] theorem sigma_nonempty : (s.sigma t).Nonempty ↔ ∃ i ∈ s, (t i).Nonempty := by simp [Finset.Nonempty] @[simp] theorem sigma_eq_empty : s.sigma t = ∅ ↔ ∀ i ∈ s, t i = ∅ := by simp only [← not_nonempty_iff_eq_empty, sigma_nonempty, not_exists, not_and] @[mono] theorem sigma_mono (hs : s₁ ⊆ s₂) (ht : ∀ i, t₁ i ⊆ t₂ i) : s₁.sigma t₁ ⊆ s₂.sigma t₂ := fun ⟨i, _⟩ h => let ⟨hi, ha⟩ := mem_sigma.1 h mem_sigma.2 ⟨hs hi, ht i ha⟩ theorem pairwiseDisjoint_map_sigmaMk : (s : Set ι).PairwiseDisjoint fun i => (t i).map (Embedding.sigmaMk i) := by intro i _ j _ hij rw [Function.onFun, disjoint_left] simp_rw [mem_map, Function.Embedding.sigmaMk_apply] rintro _ ⟨y, _, rfl⟩ ⟨z, _, hz'⟩ exact hij (congr_arg Sigma.fst hz'.symm) @[simp] theorem disjiUnion_map_sigma_mk : s.disjiUnion (fun i => (t i).map (Embedding.sigmaMk i)) pairwiseDisjoint_map_sigmaMk = s.sigma t := rfl theorem sigma_eq_biUnion [DecidableEq (Σi, α i)] (s : Finset ι) (t : ∀ i, Finset (α i)) : s.sigma t = s.biUnion fun i => (t i).map <| Embedding.sigmaMk i := by ext ⟨x, y⟩ simp [and_left_comm] variable (s t) (f : (Σi, α i) → β) theorem sup_sigma [SemilatticeSup β] [OrderBot β] : (s.sigma t).sup f = s.sup fun i => (t i).sup fun b => f ⟨i, b⟩ := by simp only [le_antisymm_iff, Finset.sup_le_iff, mem_sigma, and_imp, Sigma.forall] exact ⟨fun i a hi ha => (le_sup hi).trans' <| le_sup (f := fun a => f ⟨i, a⟩) ha, fun i hi a ha => le_sup <| mem_sigma.2 ⟨hi, ha⟩⟩ theorem inf_sigma [SemilatticeInf β] [OrderTop β] : (s.sigma t).inf f = s.inf fun i => (t i).inf fun b => f ⟨i, b⟩ := @sup_sigma _ _ βᵒᵈ _ _ _ _ _ theorem _root_.biSup_finsetSigma [CompleteLattice β] (s : Finset ι) (t : ∀ i, Finset (α i)) (f : Sigma α → β) : ⨆ ij ∈ s.sigma t, f ij = ⨆ (i ∈ s) (j ∈ t i), f ⟨i, j⟩ := by simp_rw [← Finset.iSup_coe, Finset.coe_sigma, biSup_sigma] theorem _root_.biSup_finsetSigma' [CompleteLattice β] (s : Finset ι) (t : ∀ i, Finset (α i)) (f : ∀ i, α i → β) : ⨆ (i ∈ s) (j ∈ t i), f i j = ⨆ ij ∈ s.sigma t, f ij.fst ij.snd := Eq.symm (biSup_finsetSigma _ _ _) theorem _root_.biInf_finsetSigma [CompleteLattice β] (s : Finset ι) (t : ∀ i, Finset (α i)) (f : Sigma α → β) : ⨅ ij ∈ s.sigma t, f ij = ⨅ (i ∈ s) (j ∈ t i), f ⟨i, j⟩ := biSup_finsetSigma (β := βᵒᵈ) _ _ _ theorem _root_.biInf_finsetSigma' [CompleteLattice β] (s : Finset ι) (t : ∀ i, Finset (α i)) (f : ∀ i, α i → β) : ⨅ (i ∈ s) (j ∈ t i), f i j = ⨅ ij ∈ s.sigma t, f ij.fst ij.snd := Eq.symm (biInf_finsetSigma _ _ _) theorem _root_.Set.biUnion_finsetSigma (s : Finset ι) (t : ∀ i, Finset (α i)) (f : Sigma α → Set β) : ⋃ ij ∈ s.sigma t, f ij = ⋃ i ∈ s, ⋃ j ∈ t i, f ⟨i, j⟩ := biSup_finsetSigma _ _ _ theorem _root_.Set.biUnion_finsetSigma' (s : Finset ι) (t : ∀ i, Finset (α i)) (f : ∀ i, α i → Set β) : ⋃ i ∈ s, ⋃ j ∈ t i, f i j = ⋃ ij ∈ s.sigma t, f ij.fst ij.snd := biSup_finsetSigma' _ _ _ theorem _root_.Set.biInter_finsetSigma (s : Finset ι) (t : ∀ i, Finset (α i)) (f : Sigma α → Set β) : ⋂ ij ∈ s.sigma t, f ij = ⋂ i ∈ s, ⋂ j ∈ t i, f ⟨i, j⟩ := biInf_finsetSigma _ _ _ theorem _root_.Set.biInter_finsetSigma' (s : Finset ι) (t : ∀ i, Finset (α i)) (f : ∀ i, α i → Set β) : ⋂ i ∈ s, ⋂ j ∈ t i, f i j = ⋂ ij ∈ s.sigma t, f ij.1 ij.2 := biInf_finsetSigma' _ _ _ end Sigma section SigmaLift variable {α β γ : ι → Type*} [DecidableEq ι] /-- Lifts maps `α i → β i → Finset (γ i)` to a map `Σ i, α i → Σ i, β i → Finset (Σ i, γ i)`. -/ def sigmaLift (f : ∀ ⦃i⦄, α i → β i → Finset (γ i)) (a : Sigma α) (b : Sigma β) : Finset (Sigma γ) := dite (a.1 = b.1) (fun h => (f (h ▸ a.2) b.2).map <| Embedding.sigmaMk _) fun _ => ∅ theorem mem_sigmaLift (f : ∀ ⦃i⦄, α i → β i → Finset (γ i)) (a : Sigma α) (b : Sigma β) (x : Sigma γ) : x ∈ sigmaLift f a b ↔ ∃ (ha : a.1 = x.1) (hb : b.1 = x.1), x.2 ∈ f (ha ▸ a.2) (hb ▸ b.2) := by obtain ⟨⟨i, a⟩, j, b⟩ := a, b obtain rfl | h := Decidable.eq_or_ne i j · constructor · simp_rw [sigmaLift] simp only [dite_eq_ite, ite_true, mem_map, Embedding.sigmaMk_apply, forall_exists_index, and_imp] rintro x hx rfl exact ⟨rfl, rfl, hx⟩ · rintro ⟨⟨⟩, ⟨⟩, hx⟩ rw [sigmaLift, dif_pos rfl, mem_map] exact ⟨_, hx, by simp [Sigma.ext_iff]⟩ · rw [sigmaLift, dif_neg h] refine iff_of_false (not_mem_empty _) ?_ rintro ⟨⟨⟩, ⟨⟩, _⟩ exact h rfl theorem mk_mem_sigmaLift (f : ∀ ⦃i⦄, α i → β i → Finset (γ i)) (i : ι) (a : α i) (b : β i) (x : γ i) : (⟨i, x⟩ : Sigma γ) ∈ sigmaLift f ⟨i, a⟩ ⟨i, b⟩ ↔ x ∈ f a b := by rw [sigmaLift, dif_pos rfl, mem_map] refine ⟨?_, fun hx => ⟨_, hx, rfl⟩⟩ rintro ⟨x, hx, _, rfl⟩ exact hx theorem not_mem_sigmaLift_of_ne_left (f : ∀ ⦃i⦄, α i → β i → Finset (γ i)) (a : Sigma α) (b : Sigma β) (x : Sigma γ) (h : a.1 ≠ x.1) : x ∉ sigmaLift f a b := by rw [mem_sigmaLift] exact fun H => h H.fst theorem not_mem_sigmaLift_of_ne_right (f : ∀ ⦃i⦄, α i → β i → Finset (γ i)) {a : Sigma α} (b : Sigma β) {x : Sigma γ} (h : b.1 ≠ x.1) : x ∉ sigmaLift f a b := by rw [mem_sigmaLift] exact fun H => h H.snd.fst variable {f g : ∀ ⦃i⦄, α i → β i → Finset (γ i)} {a : Σi, α i} {b : Σi, β i} theorem sigmaLift_nonempty : (sigmaLift f a b).Nonempty ↔ ∃ h : a.1 = b.1, (f (h ▸ a.2) b.2).Nonempty := by simp_rw [nonempty_iff_ne_empty, sigmaLift] split_ifs with h <;> simp [h] theorem sigmaLift_eq_empty : sigmaLift f a b = ∅ ↔ ∀ h : a.1 = b.1, f (h ▸ a.2) b.2 = ∅ := by simp_rw [sigmaLift] split_ifs with h · simp [h, forall_prop_of_true h] · simp [h, forall_prop_of_false h] theorem sigmaLift_mono (h : ∀ ⦃i⦄ ⦃a : α i⦄ ⦃b : β i⦄, f a b ⊆ g a b) (a : Σi, α i) (b : Σi, β i) : sigmaLift f a b ⊆ sigmaLift g a b := by rintro x hx rw [mem_sigmaLift] at hx ⊢ obtain ⟨ha, hb, hx⟩ := hx exact ⟨ha, hb, h hx⟩ variable (f a b) theorem card_sigmaLift : (sigmaLift f a b).card = dite (a.1 = b.1) (fun h => (f (h ▸ a.2) b.2).card) fun _ => 0 := by simp_rw [sigmaLift] split_ifs with h <;> simp [h] end SigmaLift end Finset
Data\Finset\Slice.lean
/- Copyright (c) 2021 Bhavik Mehta, Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta, Alena Gusakov, Yaël Dillies -/ import Mathlib.Algebra.BigOperators.Group.Finset import Mathlib.Order.Antichain import Mathlib.Order.Interval.Finset.Nat /-! # `r`-sets and slice This file defines the `r`-th slice of a set family and provides a way to say that a set family is made of `r`-sets. An `r`-set is a finset of cardinality `r` (aka of *size* `r`). The `r`-th slice of a set family is the set family made of its `r`-sets. ## Main declarations * `Set.Sized`: `A.Sized r` means that `A` only contains `r`-sets. * `Finset.slice`: `A.slice r` is the set of `r`-sets in `A`. ## Notation `A # r` is notation for `A.slice r` in locale `finset_family`. -/ open Finset Nat variable {α : Type*} {ι : Sort*} {κ : ι → Sort*} namespace Set variable {A B : Set (Finset α)} {s : Finset α} {r : ℕ} /-! ### Families of `r`-sets -/ /-- `Sized r A` means that every Finset in `A` has size `r`. -/ def Sized (r : ℕ) (A : Set (Finset α)) : Prop := ∀ ⦃x⦄, x ∈ A → card x = r theorem Sized.mono (h : A ⊆ B) (hB : B.Sized r) : A.Sized r := fun _x hx => hB <| h hx @[simp] lemma sized_empty : (∅ : Set (Finset α)).Sized r := by simp [Sized] @[simp] lemma sized_singleton : ({s} : Set (Finset α)).Sized r ↔ s.card = r := by simp [Sized] theorem sized_union : (A ∪ B).Sized r ↔ A.Sized r ∧ B.Sized r := ⟨fun hA => ⟨hA.mono subset_union_left, hA.mono subset_union_right⟩, fun hA _x hx => hx.elim (fun h => hA.1 h) fun h => hA.2 h⟩ alias ⟨_, sized.union⟩ := sized_union --TODO: A `forall_iUnion` lemma would be handy here. @[simp] theorem sized_iUnion {f : ι → Set (Finset α)} : (⋃ i, f i).Sized r ↔ ∀ i, (f i).Sized r := by simp_rw [Set.Sized, Set.mem_iUnion, forall_exists_index] exact forall_swap -- @[simp] -- Porting note: left hand side is not simp-normal form. theorem sized_iUnion₂ {f : ∀ i, κ i → Set (Finset α)} : (⋃ (i) (j), f i j).Sized r ↔ ∀ i j, (f i j).Sized r := by simp only [Set.sized_iUnion] protected theorem Sized.isAntichain (hA : A.Sized r) : IsAntichain (· ⊆ ·) A := fun _s hs _t ht h hst => h <| Finset.eq_of_subset_of_card_le hst ((hA ht).trans (hA hs).symm).le protected theorem Sized.subsingleton (hA : A.Sized 0) : A.Subsingleton := subsingleton_of_forall_eq ∅ fun _s hs => card_eq_zero.1 <| hA hs theorem Sized.subsingleton' [Fintype α] (hA : A.Sized (Fintype.card α)) : A.Subsingleton := subsingleton_of_forall_eq Finset.univ fun s hs => s.card_eq_iff_eq_univ.1 <| hA hs theorem Sized.empty_mem_iff (hA : A.Sized r) : ∅ ∈ A ↔ A = {∅} := hA.isAntichain.bot_mem_iff theorem Sized.univ_mem_iff [Fintype α] (hA : A.Sized r) : Finset.univ ∈ A ↔ A = {Finset.univ} := hA.isAntichain.top_mem_iff theorem sized_powersetCard (s : Finset α) (r : ℕ) : (powersetCard r s : Set (Finset α)).Sized r := fun _t ht => (mem_powersetCard.1 ht).2 end Set namespace Finset section Sized variable [Fintype α] {𝒜 : Finset (Finset α)} {s : Finset α} {r : ℕ} theorem subset_powersetCard_univ_iff : 𝒜 ⊆ powersetCard r univ ↔ (𝒜 : Set (Finset α)).Sized r := forall_congr' fun A => by rw [mem_powersetCard_univ, mem_coe] alias ⟨_, _root_.Set.Sized.subset_powersetCard_univ⟩ := subset_powersetCard_univ_iff theorem _root_.Set.Sized.card_le (h𝒜 : (𝒜 : Set (Finset α)).Sized r) : card 𝒜 ≤ (Fintype.card α).choose r := by rw [Fintype.card, ← card_powersetCard] exact card_le_card (subset_powersetCard_univ_iff.mpr h𝒜) end Sized /-! ### Slices -/ section Slice variable {𝒜 : Finset (Finset α)} {A A₁ A₂ : Finset α} {r r₁ r₂ : ℕ} /-- The `r`-th slice of a set family is the subset of its elements which have cardinality `r`. -/ def slice (𝒜 : Finset (Finset α)) (r : ℕ) : Finset (Finset α) := 𝒜.filter fun i => i.card = r -- Porting note: old code: scoped[FinsetFamily] @[inherit_doc] scoped[Finset] infixl:90 " # " => Finset.slice /-- `A` is in the `r`-th slice of `𝒜` iff it's in `𝒜` and has cardinality `r`. -/ theorem mem_slice : A ∈ 𝒜 # r ↔ A ∈ 𝒜 ∧ A.card = r := mem_filter /-- The `r`-th slice of `𝒜` is a subset of `𝒜`. -/ theorem slice_subset : 𝒜 # r ⊆ 𝒜 := filter_subset _ _ /-- Everything in the `r`-th slice of `𝒜` has size `r`. -/ theorem sized_slice : (𝒜 # r : Set (Finset α)).Sized r := fun _ => And.right ∘ mem_slice.mp theorem eq_of_mem_slice (h₁ : A ∈ 𝒜 # r₁) (h₂ : A ∈ 𝒜 # r₂) : r₁ = r₂ := (sized_slice h₁).symm.trans <| sized_slice h₂ /-- Elements in distinct slices must be distinct. -/ theorem ne_of_mem_slice (h₁ : A₁ ∈ 𝒜 # r₁) (h₂ : A₂ ∈ 𝒜 # r₂) : r₁ ≠ r₂ → A₁ ≠ A₂ := mt fun h => (sized_slice h₁).symm.trans ((congr_arg card h).trans (sized_slice h₂)) theorem pairwiseDisjoint_slice : (Set.univ : Set ℕ).PairwiseDisjoint (slice 𝒜) := fun _ _ _ _ hmn => disjoint_filter.2 fun _s _hs hm hn => hmn <| hm.symm.trans hn variable [Fintype α] (𝒜) @[simp] theorem biUnion_slice [DecidableEq α] : (Iic <| Fintype.card α).biUnion 𝒜.slice = 𝒜 := Subset.antisymm (biUnion_subset.2 fun _r _ => slice_subset) fun s hs => mem_biUnion.2 ⟨s.card, mem_Iic.2 <| s.card_le_univ, mem_slice.2 <| ⟨hs, rfl⟩⟩ @[simp] theorem sum_card_slice : (∑ r ∈ Iic (Fintype.card α), (𝒜 # r).card) = 𝒜.card := by letI := Classical.decEq α rw [← card_biUnion, biUnion_slice] exact Finset.pairwiseDisjoint_slice.subset (Set.subset_univ _) end Slice end Finset
Data\Finset\SMulAntidiagonal.lean
/- Copyright (c) 2024 Scott Carnahan. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Carnahan -/ import Mathlib.Data.Set.Pointwise.SMul import Mathlib.Data.Set.SMulAntidiagonal /-! # Antidiagonal for scalar multiplication as a `Finset`. Given partially ordered sets `G` and `P`, with an action of `G` on `P` that preserves and reflects the order relation, we construct, for any element `a` in `P` and partially well-ordered subsets `s` in `G` and `t` in `P`, the `Finset` of all pairs of an element in `s` and an element in `t` that scalar-multiply to `a`. ## Definitions * Finset.SMulAntidiagonal : Finset antidiagonal for PWO inputs. * Finset.VAddAntidiagonal : Finset antidiagonal for PWO inputs. -/ variable {G P : Type*} open Pointwise namespace Set @[to_additive] theorem IsPWO.smul [PartialOrder G] [PartialOrder P] [SMul G P] [IsOrderedCancelSMul G P] {s : Set G} {t : Set P} (hs : s.IsPWO) (ht : t.IsPWO) : IsPWO (s • t) := by rw [← @image_smul_prod] exact (hs.prod ht).image_of_monotone (monotone_fst.smul monotone_snd) @[to_additive] theorem IsWF.smul [LinearOrder G] [LinearOrder P] [SMul G P] [IsOrderedCancelSMul G P] {s : Set G} {t : Set P} (hs : s.IsWF) (ht : t.IsWF) : IsWF (s • t) := (hs.isPWO.smul ht.isPWO).isWF @[to_additive] theorem IsWF.min_smul [LinearOrder G] [LinearOrder P] [SMul G P] [IsOrderedCancelSMul G P] {s : Set G} {t : Set P} (hs : s.IsWF) (ht : t.IsWF) (hsn : s.Nonempty) (htn : t.Nonempty) : (hs.smul ht).min (hsn.smul htn) = hs.min hsn • ht.min htn := by refine le_antisymm (IsWF.min_le _ _ (mem_smul.2 ⟨_, hs.min_mem _, _, ht.min_mem _, rfl⟩)) ?_ rw [IsWF.le_min_iff] rintro _ ⟨x, hx, y, hy, rfl⟩ exact IsOrderedSMul.smul_le_smul (hs.min_le _ hx) (ht.min_le _ hy) end Set namespace Finset section open Set variable [PartialOrder G] [PartialOrder P] [SMul G P] [IsOrderedCancelSMul G P] {s : Set G} {t : Set P} (hs : s.IsPWO) (ht : t.IsPWO) (a : P) {u : Set G} {hu : u.IsPWO} {v : Set P} {hv : v.IsPWO} {x : G × P} /-- `Finset.SMulAntidiagonal hs ht a` is the set of all pairs of an element in `s` and an element in `t` whose scalar multiplication yields `a`, but its construction requires proofs that `s` and `t` are well-ordered. -/ @[to_additive "`Finset.VAddAntidiagonal hs ht a` is the set of all pairs of an element in `s` and an element in `t` whose vector addition yields `a`, but its construction requires proofs that `s` and `t` are well-ordered."] noncomputable def SMulAntidiagonal [PartialOrder G] [PartialOrder P] [IsOrderedCancelSMul G P] {s : Set G} {t : Set P} (hs : s.IsPWO) (ht : t.IsPWO) (a : P) : Finset (G × P) := (SMulAntidiagonal.finite_of_isPWO hs ht a).toFinset @[to_additive (attr := simp)] theorem mem_smulAntidiagonal : x ∈ SMulAntidiagonal hs ht a ↔ x.1 ∈ s ∧ x.2 ∈ t ∧ x.1 • x.2 = a := by simp only [SMulAntidiagonal, Set.Finite.mem_toFinset] exact Set.mem_sep_iff @[to_additive] theorem smulAntidiagonal_mono_left {a : P} {hs : s.IsPWO} {ht : t.IsPWO} (h : u ⊆ s) : SMulAntidiagonal hu ht a ⊆ SMulAntidiagonal hs ht a := Set.Finite.toFinset_mono <| Set.smulAntidiagonal_mono_left h @[to_additive] theorem smulAntidiagonal_mono_right {a : P} {hs : s.IsPWO} {ht : t.IsPWO} (h : v ⊆ t) : SMulAntidiagonal hs hv a ⊆ SMulAntidiagonal hs ht a := Set.Finite.toFinset_mono <| Set.smulAntidiagonal_mono_right h @[to_additive] theorem support_smulAntidiagonal_subset_smul {hs : s.IsPWO} {ht : t.IsPWO} : { a | (SMulAntidiagonal hs ht a).Nonempty } ⊆ (s • t) := fun a ⟨b, hb⟩ => by rw [mem_smulAntidiagonal] at hb rw [Set.mem_smul] use b.1 refine { left := hb.1, right := ?_ } use b.2 exact { left := hb.2.1, right := hb.2.2 } @[to_additive] theorem isPWO_support_smulAntidiagonal {hs : s.IsPWO} {ht : t.IsPWO} : { a | (SMulAntidiagonal hs ht a).Nonempty }.IsPWO := (hs.smul ht).mono (support_smulAntidiagonal_subset_smul) end @[to_additive] theorem smulAntidiagonal_min_smul_min [LinearOrder G] [LinearOrder P] [SMul G P] [IsOrderedCancelSMul G P] {s : Set G} {t : Set P} (hs : s.IsWF) (ht : t.IsWF) (hns : s.Nonempty) (hnt : t.Nonempty) : SMulAntidiagonal hs.isPWO ht.isPWO (hs.min hns • ht.min hnt) = {(hs.min hns, ht.min hnt)} := by ext ⟨a, b⟩ simp only [mem_smulAntidiagonal, mem_singleton, Prod.ext_iff] constructor · rintro ⟨has, hat, hst⟩ obtain rfl := (hs.min_le hns has).eq_of_not_lt fun hlt => (SMul.smul_lt_smul_of_lt_of_le hlt <| ht.min_le hnt hat).ne' hst exact ⟨rfl, IsCancelSMul.left_cancel _ _ _ hst⟩ · rintro ⟨rfl, rfl⟩ exact ⟨hs.min_mem _, ht.min_mem _, rfl⟩ end Finset
Data\Finset\Sort.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.RelIso.Set import Mathlib.Data.Multiset.Sort import Mathlib.Data.List.NodupEquivFin import Mathlib.Data.Finset.Lattice import Mathlib.Data.Fintype.Card /-! # Construct a sorted list from a finset. -/ namespace Finset open Multiset Nat variable {α β : Type*} /-! ### sort -/ section sort variable (r : α → α → Prop) [DecidableRel r] [IsTrans α r] [IsAntisymm α r] [IsTotal α r] /-- `sort s` constructs a sorted list from the unordered set `s`. (Uses merge sort algorithm.) -/ def sort (s : Finset α) : List α := Multiset.sort r s.1 @[simp] theorem sort_sorted (s : Finset α) : List.Sorted r (sort r s) := Multiset.sort_sorted _ _ @[simp] theorem sort_eq (s : Finset α) : ↑(sort r s) = s.1 := Multiset.sort_eq _ _ @[simp] theorem sort_nodup (s : Finset α) : (sort r s).Nodup := (by rw [sort_eq]; exact s.2 : @Multiset.Nodup α (sort r s)) @[simp] theorem sort_toFinset [DecidableEq α] (s : Finset α) : (sort r s).toFinset = s := List.toFinset_eq (sort_nodup r s) ▸ eq_of_veq (sort_eq r s) @[simp] theorem mem_sort {s : Finset α} {a : α} : a ∈ sort r s ↔ a ∈ s := Multiset.mem_sort _ @[simp] theorem length_sort {s : Finset α} : (sort r s).length = s.card := Multiset.length_sort _ @[simp] theorem sort_empty : sort r ∅ = [] := Multiset.sort_zero r @[simp] theorem sort_singleton (a : α) : sort r {a} = [a] := Multiset.sort_singleton r a open scoped List in theorem sort_perm_toList (s : Finset α) : sort r s ~ s.toList := by rw [← Multiset.coe_eq_coe] simp only [coe_toList, sort_eq] end sort section SortLinearOrder variable [LinearOrder α] theorem sort_sorted_lt (s : Finset α) : List.Sorted (· < ·) (sort (· ≤ ·) s) := (sort_sorted _ _).lt_of_le (sort_nodup _ _) theorem sort_sorted_gt (s : Finset α) : List.Sorted (· > ·) (sort (· ≥ ·) s) := (sort_sorted _ _).gt_of_ge (sort_nodup _ _) theorem sorted_zero_eq_min'_aux (s : Finset α) (h : 0 < (s.sort (· ≤ ·)).length) (H : s.Nonempty) : (s.sort (· ≤ ·)).get ⟨0, h⟩ = s.min' H := by let l := s.sort (· ≤ ·) apply le_antisymm · have : s.min' H ∈ l := (Finset.mem_sort (α := α) (· ≤ ·)).mpr (s.min'_mem H) obtain ⟨i, hi⟩ : ∃ i, l.get i = s.min' H := List.mem_iff_get.1 this rw [← hi] exact (s.sort_sorted (· ≤ ·)).rel_get_of_le (Nat.zero_le i) · have : l.get ⟨0, h⟩ ∈ s := (Finset.mem_sort (α := α) (· ≤ ·)).1 (List.get_mem l 0 h) exact s.min'_le _ this theorem sorted_zero_eq_min' {s : Finset α} {h : 0 < (s.sort (· ≤ ·)).length} : (s.sort (· ≤ ·)).get ⟨0, h⟩ = s.min' (card_pos.1 <| by rwa [length_sort] at h) := sorted_zero_eq_min'_aux _ _ _ theorem min'_eq_sorted_zero {s : Finset α} {h : s.Nonempty} : s.min' h = (s.sort (· ≤ ·)).get ⟨0, (by rw [length_sort]; exact card_pos.2 h)⟩ := (sorted_zero_eq_min'_aux _ _ _).symm theorem sorted_last_eq_max'_aux (s : Finset α) (h : (s.sort (· ≤ ·)).length - 1 < (s.sort (· ≤ ·)).length) (H : s.Nonempty) : (s.sort (· ≤ ·)).get ⟨(s.sort (· ≤ ·)).length - 1, h⟩ = s.max' H := by let l := s.sort (· ≤ ·) apply le_antisymm · have : l.get ⟨(s.sort (· ≤ ·)).length - 1, h⟩ ∈ s := (Finset.mem_sort (α := α) (· ≤ ·)).1 (List.get_mem l _ h) exact s.le_max' _ this · have : s.max' H ∈ l := (Finset.mem_sort (α := α) (· ≤ ·)).mpr (s.max'_mem H) obtain ⟨i, hi⟩ : ∃ i, l.get i = s.max' H := List.mem_iff_get.1 this rw [← hi] exact (s.sort_sorted (· ≤ ·)).rel_get_of_le (Nat.le_sub_one_of_lt i.prop) theorem sorted_last_eq_max' {s : Finset α} {h : (s.sort (· ≤ ·)).length - 1 < (s.sort (· ≤ ·)).length} : (s.sort (· ≤ ·)).get ⟨(s.sort (· ≤ ·)).length - 1, h⟩ = s.max' (by rw [length_sort] at h; exact card_pos.1 (lt_of_le_of_lt bot_le h)) := sorted_last_eq_max'_aux _ _ _ theorem max'_eq_sorted_last {s : Finset α} {h : s.Nonempty} : s.max' h = (s.sort (· ≤ ·)).get ⟨(s.sort (· ≤ ·)).length - 1, by simpa using Nat.sub_lt (card_pos.mpr h) Nat.zero_lt_one⟩ := (sorted_last_eq_max'_aux _ _ _).symm /-- Given a finset `s` of cardinality `k` in a linear order `α`, the map `orderIsoOfFin s h` is the increasing bijection between `Fin k` and `s` as an `OrderIso`. Here, `h` is a proof that the cardinality of `s` is `k`. We use this instead of an iso `Fin s.card ≃o s` to avoid casting issues in further uses of this function. -/ def orderIsoOfFin (s : Finset α) {k : ℕ} (h : s.card = k) : Fin k ≃o s := OrderIso.trans (Fin.castOrderIso ((length_sort (α := α) (· ≤ ·)).trans h).symm) <| (s.sort_sorted_lt.getIso _).trans <| OrderIso.setCongr _ _ <| Set.ext fun _ => mem_sort _ /-- Given a finset `s` of cardinality `k` in a linear order `α`, the map `orderEmbOfFin s h` is the increasing bijection between `Fin k` and `s` as an order embedding into `α`. Here, `h` is a proof that the cardinality of `s` is `k`. We use this instead of an embedding `Fin s.card ↪o α` to avoid casting issues in further uses of this function. -/ def orderEmbOfFin (s : Finset α) {k : ℕ} (h : s.card = k) : Fin k ↪o α := (orderIsoOfFin s h).toOrderEmbedding.trans (OrderEmbedding.subtype _) @[simp] theorem coe_orderIsoOfFin_apply (s : Finset α) {k : ℕ} (h : s.card = k) (i : Fin k) : ↑(orderIsoOfFin s h i) = orderEmbOfFin s h i := rfl theorem orderIsoOfFin_symm_apply (s : Finset α) {k : ℕ} (h : s.card = k) (x : s) : ↑((s.orderIsoOfFin h).symm x) = (s.sort (· ≤ ·)).indexOf ↑x := rfl theorem orderEmbOfFin_apply (s : Finset α) {k : ℕ} (h : s.card = k) (i : Fin k) : s.orderEmbOfFin h i = (s.sort (· ≤ ·)).get ⟨i, by rw [length_sort, h]; exact i.2⟩ := rfl @[simp] theorem orderEmbOfFin_mem (s : Finset α) {k : ℕ} (h : s.card = k) (i : Fin k) : s.orderEmbOfFin h i ∈ s := (s.orderIsoOfFin h i).2 @[simp] theorem range_orderEmbOfFin (s : Finset α) {k : ℕ} (h : s.card = k) : Set.range (s.orderEmbOfFin h) = s := by simp only [orderEmbOfFin, Set.range_comp ((↑) : _ → α) (s.orderIsoOfFin h), RelEmbedding.coe_trans, Set.image_univ, Finset.orderEmbOfFin, RelIso.range_eq, OrderEmbedding.subtype_apply, OrderIso.coe_toOrderEmbedding, eq_self_iff_true, Subtype.range_coe_subtype, Finset.setOf_mem, Finset.coe_inj] /-- The bijection `orderEmbOfFin s h` sends `0` to the minimum of `s`. -/ theorem orderEmbOfFin_zero {s : Finset α} {k : ℕ} (h : s.card = k) (hz : 0 < k) : orderEmbOfFin s h ⟨0, hz⟩ = s.min' (card_pos.mp (h.symm ▸ hz)) := by simp only [orderEmbOfFin_apply, Fin.val_mk, sorted_zero_eq_min'] /-- The bijection `orderEmbOfFin s h` sends `k-1` to the maximum of `s`. -/ theorem orderEmbOfFin_last {s : Finset α} {k : ℕ} (h : s.card = k) (hz : 0 < k) : orderEmbOfFin s h ⟨k - 1, Nat.sub_lt hz (Nat.succ_pos 0)⟩ = s.max' (card_pos.mp (h.symm ▸ hz)) := by simp [orderEmbOfFin_apply, max'_eq_sorted_last, h] /-- `orderEmbOfFin {a} h` sends any argument to `a`. -/ @[simp] theorem orderEmbOfFin_singleton (a : α) (i : Fin 1) : orderEmbOfFin {a} (card_singleton a) i = a := by rw [Subsingleton.elim i ⟨0, Nat.zero_lt_one⟩, orderEmbOfFin_zero _ Nat.zero_lt_one, min'_singleton] /-- Any increasing map `f` from `Fin k` to a finset of cardinality `k` has to coincide with the increasing bijection `orderEmbOfFin s h`. -/ theorem orderEmbOfFin_unique {s : Finset α} {k : ℕ} (h : s.card = k) {f : Fin k → α} (hfs : ∀ x, f x ∈ s) (hmono : StrictMono f) : f = s.orderEmbOfFin h := by apply Fin.strictMono_unique hmono (s.orderEmbOfFin h).strictMono rw [range_orderEmbOfFin, ← Set.image_univ, ← coe_univ, ← coe_image, coe_inj] refine eq_of_subset_of_card_le (fun x hx => ?_) ?_ · rcases mem_image.1 hx with ⟨x, _, rfl⟩ exact hfs x · rw [h, card_image_of_injective _ hmono.injective, card_univ, Fintype.card_fin] /-- An order embedding `f` from `Fin k` to a finset of cardinality `k` has to coincide with the increasing bijection `orderEmbOfFin s h`. -/ theorem orderEmbOfFin_unique' {s : Finset α} {k : ℕ} (h : s.card = k) {f : Fin k ↪o α} (hfs : ∀ x, f x ∈ s) : f = s.orderEmbOfFin h := RelEmbedding.ext <| Function.funext_iff.1 <| orderEmbOfFin_unique h hfs f.strictMono /-- Two parametrizations `orderEmbOfFin` of the same set take the same value on `i` and `j` if and only if `i = j`. Since they can be defined on a priori not defeq types `Fin k` and `Fin l` (although necessarily `k = l`), the conclusion is rather written `(i : ℕ) = (j : ℕ)`. -/ @[simp] theorem orderEmbOfFin_eq_orderEmbOfFin_iff {k l : ℕ} {s : Finset α} {i : Fin k} {j : Fin l} {h : s.card = k} {h' : s.card = l} : s.orderEmbOfFin h i = s.orderEmbOfFin h' j ↔ (i : ℕ) = (j : ℕ) := by substs k l exact (s.orderEmbOfFin rfl).eq_iff_eq.trans Fin.ext_iff /-- Given a finset `s` of size at least `k` in a linear order `α`, the map `orderEmbOfCardLe` is an order embedding from `Fin k` to `α` whose image is contained in `s`. Specifically, it maps `Fin k` to an initial segment of `s`. -/ def orderEmbOfCardLe (s : Finset α) {k : ℕ} (h : k ≤ s.card) : Fin k ↪o α := (Fin.castLEOrderEmb h).trans (s.orderEmbOfFin rfl) theorem orderEmbOfCardLe_mem (s : Finset α) {k : ℕ} (h : k ≤ s.card) (a) : orderEmbOfCardLe s h a ∈ s := by simp only [orderEmbOfCardLe, RelEmbedding.coe_trans, Finset.orderEmbOfFin_mem, Function.comp_apply] end SortLinearOrder unsafe instance [Repr α] : Repr (Finset α) where reprPrec s _ := -- multiset uses `0` not `∅` for empty sets if s.card = 0 then "∅" else repr s.1 end Finset namespace Fin theorem sort_univ (n : ℕ) : Finset.univ.sort (fun x y : Fin n => x ≤ y) = List.finRange n := List.eq_of_perm_of_sorted (List.perm_of_nodup_nodup_toFinset_eq (Finset.univ.sort_nodup _) (List.nodup_finRange n) (by simp)) (Finset.univ.sort_sorted LE.le) (List.pairwise_le_finRange n) end Fin
Data\Finset\Sum.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.Data.Multiset.Sum import Mathlib.Data.Finset.Card /-! # Disjoint sum of finsets This file defines the disjoint sum of two finsets as `Finset (α ⊕ β)`. Beware not to confuse with the `Finset.sum` operation which computes the additive sum. ## Main declarations * `Finset.disjSum`: `s.disjSum t` is the disjoint sum of `s` and `t`. -/ open Function Multiset Sum namespace Finset variable {α β : Type*} (s : Finset α) (t : Finset β) /-- Disjoint sum of finsets. -/ def disjSum : Finset (α ⊕ β) := ⟨s.1.disjSum t.1, s.2.disjSum t.2⟩ @[simp] theorem val_disjSum : (s.disjSum t).1 = s.1.disjSum t.1 := rfl @[simp] theorem empty_disjSum : (∅ : Finset α).disjSum t = t.map Embedding.inr := val_inj.1 <| Multiset.zero_disjSum _ @[simp] theorem disjSum_empty : s.disjSum (∅ : Finset β) = s.map Embedding.inl := val_inj.1 <| Multiset.disjSum_zero _ @[simp] theorem card_disjSum : (s.disjSum t).card = s.card + t.card := Multiset.card_disjSum _ _ theorem disjoint_map_inl_map_inr : Disjoint (s.map Embedding.inl) (t.map Embedding.inr) := by simp_rw [disjoint_left, mem_map] rintro x ⟨a, _, rfl⟩ ⟨b, _, ⟨⟩⟩ @[simp] theorem map_inl_disjUnion_map_inr : (s.map Embedding.inl).disjUnion (t.map Embedding.inr) (disjoint_map_inl_map_inr _ _) = s.disjSum t := rfl variable {s t} {s₁ s₂ : Finset α} {t₁ t₂ : Finset β} {a : α} {b : β} {x : α ⊕ β} theorem mem_disjSum : x ∈ s.disjSum t ↔ (∃ a, a ∈ s ∧ inl a = x) ∨ ∃ b, b ∈ t ∧ inr b = x := Multiset.mem_disjSum @[simp] theorem inl_mem_disjSum : inl a ∈ s.disjSum t ↔ a ∈ s := Multiset.inl_mem_disjSum @[simp] theorem inr_mem_disjSum : inr b ∈ s.disjSum t ↔ b ∈ t := Multiset.inr_mem_disjSum @[simp] theorem disjSum_eq_empty : s.disjSum t = ∅ ↔ s = ∅ ∧ t = ∅ := by simp [ext_iff] theorem disjSum_mono (hs : s₁ ⊆ s₂) (ht : t₁ ⊆ t₂) : s₁.disjSum t₁ ⊆ s₂.disjSum t₂ := val_le_iff.1 <| Multiset.disjSum_mono (val_le_iff.2 hs) (val_le_iff.2 ht) theorem disjSum_mono_left (t : Finset β) : Monotone fun s : Finset α => s.disjSum t := fun _ _ hs => disjSum_mono hs Subset.rfl theorem disjSum_mono_right (s : Finset α) : Monotone (s.disjSum : Finset β → Finset (α ⊕ β)) := fun _ _ => disjSum_mono Subset.rfl theorem disjSum_ssubset_disjSum_of_ssubset_of_subset (hs : s₁ ⊂ s₂) (ht : t₁ ⊆ t₂) : s₁.disjSum t₁ ⊂ s₂.disjSum t₂ := val_lt_iff.1 <| disjSum_lt_disjSum_of_lt_of_le (val_lt_iff.2 hs) (val_le_iff.2 ht) theorem disjSum_ssubset_disjSum_of_subset_of_ssubset (hs : s₁ ⊆ s₂) (ht : t₁ ⊂ t₂) : s₁.disjSum t₁ ⊂ s₂.disjSum t₂ := val_lt_iff.1 <| disjSum_lt_disjSum_of_le_of_lt (val_le_iff.2 hs) (val_lt_iff.2 ht) theorem disjSum_strictMono_left (t : Finset β) : StrictMono fun s : Finset α => s.disjSum t := fun _ _ hs => disjSum_ssubset_disjSum_of_ssubset_of_subset hs Subset.rfl theorem disj_sum_strictMono_right (s : Finset α) : StrictMono (s.disjSum : Finset β → Finset (α ⊕ β)) := fun _ _ => disjSum_ssubset_disjSum_of_subset_of_ssubset Subset.rfl end Finset
Data\Finset\Sups.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.Data.Finset.NAry import Mathlib.Data.Finset.Slice import Mathlib.Data.Set.Sups /-! # Set family operations This file defines a few binary operations on `Finset α` for use in set family combinatorics. ## Main declarations * `Finset.sups s t`: Finset of elements of the form `a ⊔ b` where `a ∈ s`, `b ∈ t`. * `Finset.infs s t`: Finset of elements of the form `a ⊓ b` where `a ∈ s`, `b ∈ t`. * `Finset.disjSups s t`: Finset of elements of the form `a ⊔ b` where `a ∈ s`, `b ∈ t` and `a` and `b` are disjoint. * `Finset.diffs`: Finset of elements of the form `a \ b` where `a ∈ s`, `b ∈ t`. * `Finset.compls`: Finset of elements of the form `aᶜ` where `a ∈ s`. ## Notation We define the following notation in locale `FinsetFamily`: * `s ⊻ t` for `Finset.sups` * `s ⊼ t` for `Finset.infs` * `s ○ t` for `Finset.disjSups s t` * `s \\ t` for `Finset.diffs` * `sᶜˢ` for `Finset.compls` ## References [B. Bollobás, *Combinatorics*][bollobas1986] -/ open Function open SetFamily variable {F α β : Type*} namespace Finset section Sups variable [DecidableEq α] [DecidableEq β] variable [SemilatticeSup α] [SemilatticeSup β] [FunLike F α β] [SupHomClass F α β] variable (s s₁ s₂ t t₁ t₂ u v : Finset α) /-- `s ⊻ t` is the finset of elements of the form `a ⊔ b` where `a ∈ s`, `b ∈ t`. -/ protected def hasSups : HasSups (Finset α) := ⟨image₂ (· ⊔ ·)⟩ scoped[FinsetFamily] attribute [instance] Finset.hasSups open FinsetFamily variable {s t} {a b c : α} @[simp] theorem mem_sups : c ∈ s ⊻ t ↔ ∃ a ∈ s, ∃ b ∈ t, a ⊔ b = c := by simp [(· ⊻ ·)] variable (s t) @[simp, norm_cast] theorem coe_sups : (↑(s ⊻ t) : Set α) = ↑s ⊻ ↑t := coe_image₂ _ _ _ theorem card_sups_le : (s ⊻ t).card ≤ s.card * t.card := card_image₂_le _ _ _ theorem card_sups_iff : (s ⊻ t).card = s.card * t.card ↔ (s ×ˢ t : Set (α × α)).InjOn fun x => x.1 ⊔ x.2 := card_image₂_iff variable {s s₁ s₂ t t₁ t₂ u} theorem sup_mem_sups : a ∈ s → b ∈ t → a ⊔ b ∈ s ⊻ t := mem_image₂_of_mem theorem sups_subset : s₁ ⊆ s₂ → t₁ ⊆ t₂ → s₁ ⊻ t₁ ⊆ s₂ ⊻ t₂ := image₂_subset theorem sups_subset_left : t₁ ⊆ t₂ → s ⊻ t₁ ⊆ s ⊻ t₂ := image₂_subset_left theorem sups_subset_right : s₁ ⊆ s₂ → s₁ ⊻ t ⊆ s₂ ⊻ t := image₂_subset_right lemma image_subset_sups_left : b ∈ t → s.image (· ⊔ b) ⊆ s ⊻ t := image_subset_image₂_left lemma image_subset_sups_right : a ∈ s → t.image (a ⊔ ·) ⊆ s ⊻ t := image_subset_image₂_right theorem forall_sups_iff {p : α → Prop} : (∀ c ∈ s ⊻ t, p c) ↔ ∀ a ∈ s, ∀ b ∈ t, p (a ⊔ b) := forall_image₂_iff @[simp] theorem sups_subset_iff : s ⊻ t ⊆ u ↔ ∀ a ∈ s, ∀ b ∈ t, a ⊔ b ∈ u := image₂_subset_iff @[simp, aesop safe apply (rule_sets := [finsetNonempty])] theorem sups_nonempty : (s ⊻ t).Nonempty ↔ s.Nonempty ∧ t.Nonempty := image₂_nonempty_iff protected theorem Nonempty.sups : s.Nonempty → t.Nonempty → (s ⊻ t).Nonempty := Nonempty.image₂ theorem Nonempty.of_sups_left : (s ⊻ t).Nonempty → s.Nonempty := Nonempty.of_image₂_left theorem Nonempty.of_sups_right : (s ⊻ t).Nonempty → t.Nonempty := Nonempty.of_image₂_right @[simp] theorem empty_sups : ∅ ⊻ t = ∅ := image₂_empty_left @[simp] theorem sups_empty : s ⊻ ∅ = ∅ := image₂_empty_right @[simp] theorem sups_eq_empty : s ⊻ t = ∅ ↔ s = ∅ ∨ t = ∅ := image₂_eq_empty_iff @[simp] lemma singleton_sups : {a} ⊻ t = t.image (a ⊔ ·) := image₂_singleton_left @[simp] lemma sups_singleton : s ⊻ {b} = s.image (· ⊔ b) := image₂_singleton_right theorem singleton_sups_singleton : ({a} ⊻ {b} : Finset α) = {a ⊔ b} := image₂_singleton theorem sups_union_left : (s₁ ∪ s₂) ⊻ t = s₁ ⊻ t ∪ s₂ ⊻ t := image₂_union_left theorem sups_union_right : s ⊻ (t₁ ∪ t₂) = s ⊻ t₁ ∪ s ⊻ t₂ := image₂_union_right theorem sups_inter_subset_left : (s₁ ∩ s₂) ⊻ t ⊆ s₁ ⊻ t ∩ s₂ ⊻ t := image₂_inter_subset_left theorem sups_inter_subset_right : s ⊻ (t₁ ∩ t₂) ⊆ s ⊻ t₁ ∩ s ⊻ t₂ := image₂_inter_subset_right theorem subset_sups {s t : Set α} : ↑u ⊆ s ⊻ t → ∃ s' t' : Finset α, ↑s' ⊆ s ∧ ↑t' ⊆ t ∧ u ⊆ s' ⊻ t' := subset_image₂ lemma image_sups (f : F) (s t : Finset α) : image f (s ⊻ t) = image f s ⊻ image f t := image_image₂_distrib <| map_sup f lemma map_sups (f : F) (hf) (s t : Finset α) : map ⟨f, hf⟩ (s ⊻ t) = map ⟨f, hf⟩ s ⊻ map ⟨f, hf⟩ t := by simpa [map_eq_image] using image_sups f s t lemma subset_sups_self : s ⊆ s ⊻ s := fun _a ha ↦ mem_sups.2 ⟨_, ha, _, ha, sup_idem _⟩ lemma sups_subset_self : s ⊻ s ⊆ s ↔ SupClosed (s : Set α) := sups_subset_iff @[simp] lemma sups_eq_self : s ⊻ s = s ↔ SupClosed (s : Set α) := by simp [← coe_inj] @[simp] lemma univ_sups_univ [Fintype α] : (univ : Finset α) ⊻ univ = univ := by simp lemma filter_sups_le [@DecidableRel α (· ≤ ·)] (s t : Finset α) (a : α) : (s ⊻ t).filter (· ≤ a) = s.filter (· ≤ a) ⊻ t.filter (· ≤ a) := by simp only [← coe_inj, coe_filter, coe_sups, ← mem_coe, Set.sep_sups_le] variable (s t u) lemma biUnion_image_sup_left : s.biUnion (fun a ↦ t.image (a ⊔ ·)) = s ⊻ t := biUnion_image_left lemma biUnion_image_sup_right : t.biUnion (fun b ↦ s.image (· ⊔ b)) = s ⊻ t := biUnion_image_right -- Porting note: simpNF linter doesn't like @[simp] theorem image_sup_product (s t : Finset α) : (s ×ˢ t).image (uncurry (· ⊔ ·)) = s ⊻ t := image_uncurry_product _ _ _ theorem sups_assoc : s ⊻ t ⊻ u = s ⊻ (t ⊻ u) := image₂_assoc sup_assoc theorem sups_comm : s ⊻ t = t ⊻ s := image₂_comm sup_comm theorem sups_left_comm : s ⊻ (t ⊻ u) = t ⊻ (s ⊻ u) := image₂_left_comm sup_left_comm theorem sups_right_comm : s ⊻ t ⊻ u = s ⊻ u ⊻ t := image₂_right_comm sup_right_comm theorem sups_sups_sups_comm : s ⊻ t ⊻ (u ⊻ v) = s ⊻ u ⊻ (t ⊻ v) := image₂_image₂_image₂_comm sup_sup_sup_comm end Sups section Infs variable [DecidableEq α] [DecidableEq β] variable [SemilatticeInf α] [SemilatticeInf β] [FunLike F α β] [InfHomClass F α β] variable (s s₁ s₂ t t₁ t₂ u v : Finset α) /-- `s ⊼ t` is the finset of elements of the form `a ⊓ b` where `a ∈ s`, `b ∈ t`. -/ protected def hasInfs : HasInfs (Finset α) := ⟨image₂ (· ⊓ ·)⟩ scoped[FinsetFamily] attribute [instance] Finset.hasInfs open FinsetFamily variable {s t} {a b c : α} @[simp] theorem mem_infs : c ∈ s ⊼ t ↔ ∃ a ∈ s, ∃ b ∈ t, a ⊓ b = c := by simp [(· ⊼ ·)] variable (s t) @[simp, norm_cast] theorem coe_infs : (↑(s ⊼ t) : Set α) = ↑s ⊼ ↑t := coe_image₂ _ _ _ theorem card_infs_le : (s ⊼ t).card ≤ s.card * t.card := card_image₂_le _ _ _ theorem card_infs_iff : (s ⊼ t).card = s.card * t.card ↔ (s ×ˢ t : Set (α × α)).InjOn fun x => x.1 ⊓ x.2 := card_image₂_iff variable {s s₁ s₂ t t₁ t₂ u} theorem inf_mem_infs : a ∈ s → b ∈ t → a ⊓ b ∈ s ⊼ t := mem_image₂_of_mem theorem infs_subset : s₁ ⊆ s₂ → t₁ ⊆ t₂ → s₁ ⊼ t₁ ⊆ s₂ ⊼ t₂ := image₂_subset theorem infs_subset_left : t₁ ⊆ t₂ → s ⊼ t₁ ⊆ s ⊼ t₂ := image₂_subset_left theorem infs_subset_right : s₁ ⊆ s₂ → s₁ ⊼ t ⊆ s₂ ⊼ t := image₂_subset_right lemma image_subset_infs_left : b ∈ t → s.image (· ⊓ b) ⊆ s ⊼ t := image_subset_image₂_left lemma image_subset_infs_right : a ∈ s → t.image (a ⊓ ·) ⊆ s ⊼ t := image_subset_image₂_right theorem forall_infs_iff {p : α → Prop} : (∀ c ∈ s ⊼ t, p c) ↔ ∀ a ∈ s, ∀ b ∈ t, p (a ⊓ b) := forall_image₂_iff @[simp] theorem infs_subset_iff : s ⊼ t ⊆ u ↔ ∀ a ∈ s, ∀ b ∈ t, a ⊓ b ∈ u := image₂_subset_iff @[simp, aesop safe apply (rule_sets := [finsetNonempty])] theorem infs_nonempty : (s ⊼ t).Nonempty ↔ s.Nonempty ∧ t.Nonempty := image₂_nonempty_iff protected theorem Nonempty.infs : s.Nonempty → t.Nonempty → (s ⊼ t).Nonempty := Nonempty.image₂ theorem Nonempty.of_infs_left : (s ⊼ t).Nonempty → s.Nonempty := Nonempty.of_image₂_left theorem Nonempty.of_infs_right : (s ⊼ t).Nonempty → t.Nonempty := Nonempty.of_image₂_right @[simp] theorem empty_infs : ∅ ⊼ t = ∅ := image₂_empty_left @[simp] theorem infs_empty : s ⊼ ∅ = ∅ := image₂_empty_right @[simp] theorem infs_eq_empty : s ⊼ t = ∅ ↔ s = ∅ ∨ t = ∅ := image₂_eq_empty_iff @[simp] lemma singleton_infs : {a} ⊼ t = t.image (a ⊓ ·) := image₂_singleton_left @[simp] lemma infs_singleton : s ⊼ {b} = s.image (· ⊓ b) := image₂_singleton_right theorem singleton_infs_singleton : ({a} ⊼ {b} : Finset α) = {a ⊓ b} := image₂_singleton theorem infs_union_left : (s₁ ∪ s₂) ⊼ t = s₁ ⊼ t ∪ s₂ ⊼ t := image₂_union_left theorem infs_union_right : s ⊼ (t₁ ∪ t₂) = s ⊼ t₁ ∪ s ⊼ t₂ := image₂_union_right theorem infs_inter_subset_left : (s₁ ∩ s₂) ⊼ t ⊆ s₁ ⊼ t ∩ s₂ ⊼ t := image₂_inter_subset_left theorem infs_inter_subset_right : s ⊼ (t₁ ∩ t₂) ⊆ s ⊼ t₁ ∩ s ⊼ t₂ := image₂_inter_subset_right theorem subset_infs {s t : Set α} : ↑u ⊆ s ⊼ t → ∃ s' t' : Finset α, ↑s' ⊆ s ∧ ↑t' ⊆ t ∧ u ⊆ s' ⊼ t' := subset_image₂ lemma image_infs (f : F) (s t : Finset α) : image f (s ⊼ t) = image f s ⊼ image f t := image_image₂_distrib <| map_inf f lemma map_infs (f : F) (hf) (s t : Finset α) : map ⟨f, hf⟩ (s ⊼ t) = map ⟨f, hf⟩ s ⊼ map ⟨f, hf⟩ t := by simpa [map_eq_image] using image_infs f s t lemma subset_infs_self : s ⊆ s ⊼ s := fun _a ha ↦ mem_infs.2 ⟨_, ha, _, ha, inf_idem _⟩ lemma infs_self_subset : s ⊼ s ⊆ s ↔ InfClosed (s : Set α) := infs_subset_iff @[simp] lemma infs_self : s ⊼ s = s ↔ InfClosed (s : Set α) := by simp [← coe_inj] @[simp] lemma univ_infs_univ [Fintype α] : (univ : Finset α) ⊼ univ = univ := by simp lemma filter_infs_le [@DecidableRel α (· ≤ ·)] (s t : Finset α) (a : α) : (s ⊼ t).filter (a ≤ ·) = s.filter (a ≤ ·) ⊼ t.filter (a ≤ ·) := by simp only [← coe_inj, coe_filter, coe_infs, ← mem_coe, Set.sep_infs_le] variable (s t u) lemma biUnion_image_inf_left : s.biUnion (fun a ↦ t.image (a ⊓ ·)) = s ⊼ t := biUnion_image_left lemma biUnion_image_inf_right : t.biUnion (fun b ↦ s.image (· ⊓ b)) = s ⊼ t := biUnion_image_right -- Porting note: simpNF linter doesn't like @[simp] theorem image_inf_product (s t : Finset α) : (s ×ˢ t).image (uncurry (· ⊓ ·)) = s ⊼ t := image_uncurry_product _ _ _ theorem infs_assoc : s ⊼ t ⊼ u = s ⊼ (t ⊼ u) := image₂_assoc inf_assoc theorem infs_comm : s ⊼ t = t ⊼ s := image₂_comm inf_comm theorem infs_left_comm : s ⊼ (t ⊼ u) = t ⊼ (s ⊼ u) := image₂_left_comm inf_left_comm theorem infs_right_comm : s ⊼ t ⊼ u = s ⊼ u ⊼ t := image₂_right_comm inf_right_comm theorem infs_infs_infs_comm : s ⊼ t ⊼ (u ⊼ v) = s ⊼ u ⊼ (t ⊼ v) := image₂_image₂_image₂_comm inf_inf_inf_comm end Infs open FinsetFamily section DistribLattice variable [DecidableEq α] variable [DistribLattice α] (s t u : Finset α) theorem sups_infs_subset_left : s ⊻ t ⊼ u ⊆ (s ⊻ t) ⊼ (s ⊻ u) := image₂_distrib_subset_left sup_inf_left theorem sups_infs_subset_right : t ⊼ u ⊻ s ⊆ (t ⊻ s) ⊼ (u ⊻ s) := image₂_distrib_subset_right sup_inf_right theorem infs_sups_subset_left : s ⊼ (t ⊻ u) ⊆ s ⊼ t ⊻ s ⊼ u := image₂_distrib_subset_left inf_sup_left theorem infs_sups_subset_right : (t ⊻ u) ⊼ s ⊆ t ⊼ s ⊻ u ⊼ s := image₂_distrib_subset_right inf_sup_right end DistribLattice section Finset variable [DecidableEq α] variable {𝒜 ℬ : Finset (Finset α)} {s t : Finset α} {a : α} @[simp] lemma powerset_union (s t : Finset α) : (s ∪ t).powerset = s.powerset ⊻ t.powerset := by ext u simp only [mem_sups, mem_powerset, le_eq_subset, sup_eq_union] refine ⟨fun h ↦ ⟨_, inter_subset_left (s₂ := u), _, inter_subset_left (s₂ := u), ?_⟩, ?_⟩ · rwa [← union_inter_distrib_right, inter_eq_right] · rintro ⟨v, hv, w, hw, rfl⟩ exact union_subset_union hv hw @[simp] lemma powerset_inter (s t : Finset α) : (s ∩ t).powerset = s.powerset ⊼ t.powerset := by ext u simp only [mem_infs, mem_powerset, le_eq_subset, inf_eq_inter] refine ⟨fun h ↦ ⟨_, inter_subset_left (s₂ := u), _, inter_subset_left (s₂ := u), ?_⟩, ?_⟩ · rwa [← inter_inter_distrib_right, inter_eq_right] · rintro ⟨v, hv, w, hw, rfl⟩ exact inter_subset_inter hv hw @[simp] lemma powerset_sups_powerset_self (s : Finset α) : s.powerset ⊻ s.powerset = s.powerset := by simp [← powerset_union] @[simp] lemma powerset_infs_powerset_self (s : Finset α) : s.powerset ⊼ s.powerset = s.powerset := by simp [← powerset_inter] lemma union_mem_sups : s ∈ 𝒜 → t ∈ ℬ → s ∪ t ∈ 𝒜 ⊻ ℬ := sup_mem_sups lemma inter_mem_infs : s ∈ 𝒜 → t ∈ ℬ → s ∩ t ∈ 𝒜 ⊼ ℬ := inf_mem_infs end Finset section DisjSups variable [DecidableEq α] variable [SemilatticeSup α] [OrderBot α] [@DecidableRel α Disjoint] (s s₁ s₂ t t₁ t₂ u : Finset α) /-- The finset of elements of the form `a ⊔ b` where `a ∈ s`, `b ∈ t` and `a` and `b` are disjoint. -/ def disjSups : Finset α := ((s ×ˢ t).filter fun ab : α × α => Disjoint ab.1 ab.2).image fun ab => ab.1 ⊔ ab.2 @[inherit_doc] scoped[FinsetFamily] infixl:74 " ○ " => Finset.disjSups open FinsetFamily variable {s t u} {a b c : α} @[simp] theorem mem_disjSups : c ∈ s ○ t ↔ ∃ a ∈ s, ∃ b ∈ t, Disjoint a b ∧ a ⊔ b = c := by simp [disjSups, and_assoc] theorem disjSups_subset_sups : s ○ t ⊆ s ⊻ t := by simp_rw [subset_iff, mem_sups, mem_disjSups] exact fun c ⟨a, b, ha, hb, _, hc⟩ => ⟨a, b, ha, hb, hc⟩ variable (s t) theorem card_disjSups_le : (s ○ t).card ≤ s.card * t.card := (card_le_card disjSups_subset_sups).trans <| card_sups_le _ _ variable {s s₁ s₂ t t₁ t₂} theorem disjSups_subset (hs : s₁ ⊆ s₂) (ht : t₁ ⊆ t₂) : s₁ ○ t₁ ⊆ s₂ ○ t₂ := image_subset_image <| filter_subset_filter _ <| product_subset_product hs ht theorem disjSups_subset_left (ht : t₁ ⊆ t₂) : s ○ t₁ ⊆ s ○ t₂ := disjSups_subset Subset.rfl ht theorem disjSups_subset_right (hs : s₁ ⊆ s₂) : s₁ ○ t ⊆ s₂ ○ t := disjSups_subset hs Subset.rfl theorem forall_disjSups_iff {p : α → Prop} : (∀ c ∈ s ○ t, p c) ↔ ∀ a ∈ s, ∀ b ∈ t, Disjoint a b → p (a ⊔ b) := by simp_rw [mem_disjSups] refine ⟨fun h a ha b hb hab => h _ ⟨_, ha, _, hb, hab, rfl⟩, ?_⟩ rintro h _ ⟨a, ha, b, hb, hab, rfl⟩ exact h _ ha _ hb hab @[simp] theorem disjSups_subset_iff : s ○ t ⊆ u ↔ ∀ a ∈ s, ∀ b ∈ t, Disjoint a b → a ⊔ b ∈ u := forall_disjSups_iff theorem Nonempty.of_disjSups_left : (s ○ t).Nonempty → s.Nonempty := by simp_rw [Finset.Nonempty, mem_disjSups] exact fun ⟨_, a, ha, _⟩ => ⟨a, ha⟩ theorem Nonempty.of_disjSups_right : (s ○ t).Nonempty → t.Nonempty := by simp_rw [Finset.Nonempty, mem_disjSups] exact fun ⟨_, _, _, b, hb, _⟩ => ⟨b, hb⟩ @[simp] theorem disjSups_empty_left : ∅ ○ t = ∅ := by simp [disjSups] @[simp] theorem disjSups_empty_right : s ○ ∅ = ∅ := by simp [disjSups] theorem disjSups_singleton : ({a} ○ {b} : Finset α) = if Disjoint a b then {a ⊔ b} else ∅ := by split_ifs with h <;> simp [disjSups, filter_singleton, h] theorem disjSups_union_left : (s₁ ∪ s₂) ○ t = s₁ ○ t ∪ s₂ ○ t := by simp [disjSups, filter_union, image_union] theorem disjSups_union_right : s ○ (t₁ ∪ t₂) = s ○ t₁ ∪ s ○ t₂ := by simp [disjSups, filter_union, image_union] theorem disjSups_inter_subset_left : (s₁ ∩ s₂) ○ t ⊆ s₁ ○ t ∩ s₂ ○ t := by simpa only [disjSups, inter_product, filter_inter_distrib] using image_inter_subset _ _ _ theorem disjSups_inter_subset_right : s ○ (t₁ ∩ t₂) ⊆ s ○ t₁ ∩ s ○ t₂ := by simpa only [disjSups, product_inter, filter_inter_distrib] using image_inter_subset _ _ _ variable (s t) theorem disjSups_comm : s ○ t = t ○ s := by ext rw [mem_disjSups, mem_disjSups] -- Porting note: `exists₂_comm` no longer works with `∃ _ ∈ _, ∃ _ ∈ _, _` constructor <;> · rintro ⟨a, ha, b, hb, hd, hs⟩ rw [disjoint_comm] at hd rw [sup_comm] at hs exact ⟨b, hb, a, ha, hd, hs⟩ end DisjSups open FinsetFamily section DistribLattice variable [DecidableEq α] variable [DistribLattice α] [OrderBot α] [@DecidableRel α Disjoint] (s t u v : Finset α) theorem disjSups_assoc : ∀ s t u : Finset α, s ○ t ○ u = s ○ (t ○ u) := by refine associative_of_commutative_of_le disjSups_comm ?_ simp only [le_eq_subset, disjSups_subset_iff, mem_disjSups] rintro s t u _ ⟨a, ha, b, hb, hab, rfl⟩ c hc habc rw [disjoint_sup_left] at habc exact ⟨a, ha, _, ⟨b, hb, c, hc, habc.2, rfl⟩, hab.sup_right habc.1, (sup_assoc ..).symm⟩ theorem disjSups_left_comm : s ○ (t ○ u) = t ○ (s ○ u) := by simp_rw [← disjSups_assoc, disjSups_comm s] theorem disjSups_right_comm : s ○ t ○ u = s ○ u ○ t := by simp_rw [disjSups_assoc, disjSups_comm] theorem disjSups_disjSups_disjSups_comm : s ○ t ○ (u ○ v) = s ○ u ○ (t ○ v) := by simp_rw [← disjSups_assoc, disjSups_right_comm] end DistribLattice section Diffs variable [DecidableEq α] variable [GeneralizedBooleanAlgebra α] (s s₁ s₂ t t₁ t₂ u v : Finset α) /-- `s \\ t` is the finset of elements of the form `a \ b` where `a ∈ s`, `b ∈ t`. -/ def diffs : Finset α → Finset α → Finset α := image₂ (· \ ·) @[inherit_doc] scoped[FinsetFamily] infixl:74 " \\\\ " => Finset.diffs -- This notation is meant to have higher precedence than `\` and `⊓`, but still within the -- realm of other binary notation open FinsetFamily variable {s t} {a b c : α} @[simp] lemma mem_diffs : c ∈ s \\ t ↔ ∃ a ∈ s, ∃ b ∈ t, a \ b = c := by simp [(· \\ ·)] variable (s t) @[simp, norm_cast] lemma coe_diffs : (↑(s \\ t) : Set α) = Set.image2 (· \ ·) s t := coe_image₂ _ _ _ lemma card_diffs_le : (s \\ t).card ≤ s.card * t.card := card_image₂_le _ _ _ lemma card_diffs_iff : (s \\ t).card = s.card * t.card ↔ (s ×ˢ t : Set (α × α)).InjOn fun x ↦ x.1 \ x.2 := card_image₂_iff variable {s s₁ s₂ t t₁ t₂ u} lemma sdiff_mem_diffs : a ∈ s → b ∈ t → a \ b ∈ s \\ t := mem_image₂_of_mem lemma diffs_subset : s₁ ⊆ s₂ → t₁ ⊆ t₂ → s₁ \\ t₁ ⊆ s₂ \\ t₂ := image₂_subset lemma diffs_subset_left : t₁ ⊆ t₂ → s \\ t₁ ⊆ s \\ t₂ := image₂_subset_left lemma diffs_subset_right : s₁ ⊆ s₂ → s₁ \\ t ⊆ s₂ \\ t := image₂_subset_right lemma image_subset_diffs_left : b ∈ t → s.image (· \ b) ⊆ s \\ t := image_subset_image₂_left lemma image_subset_diffs_right : a ∈ s → t.image (a \ ·) ⊆ s \\ t := image_subset_image₂_right lemma forall_mem_diffs {p : α → Prop} : (∀ c ∈ s \\ t, p c) ↔ ∀ a ∈ s, ∀ b ∈ t, p (a \ b) := forall_image₂_iff @[simp] lemma diffs_subset_iff : s \\ t ⊆ u ↔ ∀ a ∈ s, ∀ b ∈ t, a \ b ∈ u := image₂_subset_iff @[simp, aesop safe apply (rule_sets := [finsetNonempty])] lemma diffs_nonempty : (s \\ t).Nonempty ↔ s.Nonempty ∧ t.Nonempty := image₂_nonempty_iff protected lemma Nonempty.diffs : s.Nonempty → t.Nonempty → (s \\ t).Nonempty := Nonempty.image₂ lemma Nonempty.of_diffs_left : (s \\ t).Nonempty → s.Nonempty := Nonempty.of_image₂_left lemma Nonempty.of_diffs_right : (s \\ t).Nonempty → t.Nonempty := Nonempty.of_image₂_right @[simp] lemma empty_diffs : ∅ \\ t = ∅ := image₂_empty_left @[simp] lemma diffs_empty : s \\ ∅ = ∅ := image₂_empty_right @[simp] lemma diffs_eq_empty : s \\ t = ∅ ↔ s = ∅ ∨ t = ∅ := image₂_eq_empty_iff @[simp] lemma singleton_diffs : {a} \\ t = t.image (a \ ·) := image₂_singleton_left @[simp] lemma diffs_singleton : s \\ {b} = s.image (· \ b) := image₂_singleton_right lemma singleton_diffs_singleton : ({a} \\ {b} : Finset α) = {a \ b} := image₂_singleton lemma diffs_union_left : (s₁ ∪ s₂) \\ t = s₁ \\ t ∪ s₂ \\ t := image₂_union_left lemma diffs_union_right : s \\ (t₁ ∪ t₂) = s \\ t₁ ∪ s \\ t₂ := image₂_union_right lemma diffs_inter_subset_left : (s₁ ∩ s₂) \\ t ⊆ s₁ \\ t ∩ s₂ \\ t := image₂_inter_subset_left lemma diffs_inter_subset_right : s \\ (t₁ ∩ t₂) ⊆ s \\ t₁ ∩ s \\ t₂ := image₂_inter_subset_right lemma subset_diffs {s t : Set α} : ↑u ⊆ Set.image2 (· \ ·) s t → ∃ s' t' : Finset α, ↑s' ⊆ s ∧ ↑t' ⊆ t ∧ u ⊆ s' \\ t' := subset_image₂ variable (s t u) lemma biUnion_image_sdiff_left : s.biUnion (fun a ↦ t.image (a \ ·)) = s \\ t := biUnion_image_left lemma biUnion_image_sdiff_right : t.biUnion (fun b ↦ s.image (· \ b)) = s \\ t := biUnion_image_right lemma image_sdiff_product (s t : Finset α) : (s ×ˢ t).image (uncurry (· \ ·)) = s \\ t := image_uncurry_product _ _ _ lemma diffs_right_comm : s \\ t \\ u = s \\ u \\ t := image₂_right_comm sdiff_right_comm end Diffs section Compls variable [BooleanAlgebra α] (s s₁ s₂ t t₁ t₂ u v : Finset α) /-- `sᶜˢ` is the finset of elements of the form `aᶜ` where `a ∈ s`. -/ def compls : Finset α → Finset α := map ⟨compl, compl_injective⟩ @[inherit_doc] scoped[FinsetFamily] postfix:max "ᶜˢ" => Finset.compls open FinsetFamily variable {s t} {a b c : α} @[simp] lemma mem_compls : a ∈ sᶜˢ ↔ aᶜ ∈ s := by rw [Iff.comm, ← mem_map' ⟨compl, compl_injective⟩, Embedding.coeFn_mk, compl_compl, compls] variable (s t) @[simp] lemma image_compl [DecidableEq α] : s.image compl = sᶜˢ := by simp [compls, map_eq_image] @[simp, norm_cast] lemma coe_compls : (↑sᶜˢ : Set α) = compl '' ↑s := coe_map _ _ @[simp] lemma card_compls : sᶜˢ.card = s.card := card_map _ variable {s s₁ s₂ t t₁ t₂ u} lemma compl_mem_compls : a ∈ s → aᶜ ∈ sᶜˢ := mem_map_of_mem _ @[simp] lemma compls_subset_compls : s₁ᶜˢ ⊆ s₂ᶜˢ ↔ s₁ ⊆ s₂ := map_subset_map lemma forall_mem_compls {p : α → Prop} : (∀ a ∈ sᶜˢ, p a) ↔ ∀ a ∈ s, p aᶜ := forall_mem_map lemma exists_compls_iff {p : α → Prop} : (∃ a ∈ sᶜˢ, p a) ↔ ∃ a ∈ s, p aᶜ := by aesop @[simp] lemma compls_compls (s : Finset α) : sᶜˢᶜˢ = s := by ext; simp lemma compls_subset_iff : sᶜˢ ⊆ t ↔ s ⊆ tᶜˢ := by rw [← compls_subset_compls, compls_compls] @[simp, aesop safe apply (rule_sets := [finsetNonempty])] lemma compls_nonempty : sᶜˢ.Nonempty ↔ s.Nonempty := map_nonempty protected alias ⟨Nonempty.of_compls, Nonempty.compls⟩ := compls_nonempty @[simp] lemma compls_empty : (∅ : Finset α)ᶜˢ = ∅ := map_empty _ @[simp] lemma compls_eq_empty : sᶜˢ = ∅ ↔ s = ∅ := map_eq_empty @[simp] lemma compls_singleton (a : α) : {a}ᶜˢ = {aᶜ} := map_singleton _ _ @[simp] lemma compls_univ [Fintype α] : (univ : Finset α)ᶜˢ = univ := by ext; simp variable [DecidableEq α] @[simp] lemma compls_union (s t : Finset α) : (s ∪ t)ᶜˢ = sᶜˢ ∪ tᶜˢ := map_union _ _ @[simp] lemma compls_inter (s t : Finset α) : (s ∩ t)ᶜˢ = sᶜˢ ∩ tᶜˢ := map_inter _ _ @[simp] lemma compls_infs (s t : Finset α) : (s ⊼ t)ᶜˢ = sᶜˢ ⊻ tᶜˢ := by simp_rw [← image_compl]; exact image_image₂_distrib fun _ _ ↦ compl_inf @[simp] lemma compls_sups (s t : Finset α) : (s ⊻ t)ᶜˢ = sᶜˢ ⊼ tᶜˢ := by simp_rw [← image_compl]; exact image_image₂_distrib fun _ _ ↦ compl_sup @[simp] lemma infs_compls_eq_diffs (s t : Finset α) : s ⊼ tᶜˢ = s \\ t := by ext; simp [sdiff_eq]; aesop @[simp] lemma compls_infs_eq_diffs (s t : Finset α) : sᶜˢ ⊼ t = t \\ s := by rw [infs_comm, infs_compls_eq_diffs] @[simp] lemma diffs_compls_eq_infs (s t : Finset α) : s \\ tᶜˢ = s ⊼ t := by rw [← infs_compls_eq_diffs, compls_compls] variable {α : Type*} [DecidableEq α] [Fintype α] {𝒜 : Finset (Finset α)} {n : ℕ} protected lemma _root_.Set.Sized.compls (h𝒜 : (𝒜 : Set (Finset α)).Sized n) : (𝒜ᶜˢ : Set (Finset α)).Sized (Fintype.card α - n) := Finset.forall_mem_compls.2 <| fun s hs ↦ by rw [Finset.card_compl, h𝒜 hs] lemma sized_compls (hn : n ≤ Fintype.card α) : (𝒜ᶜˢ : Set (Finset α)).Sized n ↔ (𝒜 : Set (Finset α)).Sized (Fintype.card α - n) where mp h𝒜 := by simpa using h𝒜.compls mpr h𝒜 := by simpa only [Nat.sub_sub_self hn] using h𝒜.compls end Compls end Finset
Data\Finset\Sym.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 [`data.finset.sym`@`98e83c3d541c77cdb7da20d79611a780ff8e7d90`..`02ba8949f486ebecf93fe7460f1ed0564b5e442c`](https://leanprover-community.github.io/mathlib-port-status/file/data/finset/sym?range=98e83c3d541c77cdb7da20d79611a780ff8e7d90..02ba8949f486ebecf93fe7460f1ed0564b5e442c) -/ import Mathlib.Data.Finset.Lattice import Mathlib.Data.Fintype.Vector import Mathlib.Data.Multiset.Sym /-! # Symmetric powers of a finset This file defines the symmetric powers of a finset as `Finset (Sym α n)` and `Finset (Sym2 α)`. ## Main declarations * `Finset.sym`: The symmetric power of a finset. `s.sym n` is all the multisets of cardinality `n` whose elements are in `s`. * `Finset.sym2`: The symmetric square of a finset. `s.sym2` is all the pairs whose elements are in `s`. * A `Fintype (Sym2 α)` instance that does not require `DecidableEq α`. ## TODO `Finset.sym` forms a Galois connection between `Finset α` and `Finset (Sym α n)`. Similar for `Finset.sym2`. -/ namespace Finset variable {α β : Type*} /-- `s.sym2` is the finset of all unordered pairs of elements from `s`. It is the image of `s ×ˢ s` under the quotient `α × α → Sym2 α`. -/ @[simps] protected def sym2 (s : Finset α) : Finset (Sym2 α) := ⟨s.1.sym2, s.2.sym2⟩ section variable {s t : Finset α} {a b : α} theorem mk_mem_sym2_iff : s(a, b) ∈ s.sym2 ↔ a ∈ s ∧ b ∈ s := by rw [mem_mk, sym2_val, Multiset.mk_mem_sym2_iff, mem_mk, mem_mk] @[simp] theorem mem_sym2_iff {m : Sym2 α} : m ∈ s.sym2 ↔ ∀ a ∈ m, a ∈ s := by rw [mem_mk, sym2_val, Multiset.mem_sym2_iff] simp only [mem_val] theorem sym2_cons (a : α) (s : Finset α) (ha : a ∉ s) : (s.cons a ha).sym2 = ((s.cons a ha).map <| Sym2.mkEmbedding a).disjUnion s.sym2 (by simp [Finset.disjoint_left, ha]) := val_injective <| Multiset.sym2_cons _ _ theorem sym2_insert [DecidableEq α] (a : α) (s : Finset α) : (insert a s).sym2 = ((insert a s).image fun b => s(a, b)) ∪ s.sym2 := by obtain ha | ha := Decidable.em (a ∈ s) · simp only [insert_eq_of_mem ha, right_eq_union, image_subset_iff] aesop · simpa [map_eq_image] using sym2_cons a s ha theorem sym2_map (f : α ↪ β) (s : Finset α) : (s.map f).sym2 = s.sym2.map (.sym2Map f) := val_injective <| s.val.sym2_map _ theorem sym2_image [DecidableEq β] (f : α → β) (s : Finset α) : (s.image f).sym2 = s.sym2.image (Sym2.map f) := by apply val_injective dsimp [Finset.sym2] rw [← Multiset.dedup_sym2, Multiset.sym2_map] instance _root_.Sym2.instFintype [Fintype α] : Fintype (Sym2 α) where elems := Finset.univ.sym2 complete := fun x ↦ by rw [mem_sym2_iff]; exact (fun a _ ↦ mem_univ a) -- Note(kmill): Using a default argument to make this simp lemma more general. @[simp] theorem sym2_univ [Fintype α] (inst : Fintype (Sym2 α) := Sym2.instFintype) : (univ : Finset α).sym2 = univ := by ext simp only [mem_sym2_iff, mem_univ, implies_true] @[simp, mono] theorem sym2_mono (h : s ⊆ t) : s.sym2 ⊆ t.sym2 := by rw [← val_le_iff, sym2_val, sym2_val] apply Multiset.sym2_mono rwa [val_le_iff] theorem monotone_sym2 : Monotone (Finset.sym2 : Finset α → _) := fun _ _ => sym2_mono theorem injective_sym2 : Function.Injective (Finset.sym2 : Finset α → _) := by intro s t h ext x simpa using congr(s(x, x) ∈ $h) theorem strictMono_sym2 : StrictMono (Finset.sym2 : Finset α → _) := monotone_sym2.strictMono_of_injective injective_sym2 theorem sym2_toFinset [DecidableEq α] (m : Multiset α) : m.toFinset.sym2 = m.sym2.toFinset := by ext z refine z.ind fun x y ↦ ?_ simp only [mk_mem_sym2_iff, Multiset.mem_toFinset, Multiset.mk_mem_sym2_iff] @[simp] theorem sym2_empty : (∅ : Finset α).sym2 = ∅ := rfl @[simp] theorem sym2_eq_empty : s.sym2 = ∅ ↔ s = ∅ := by rw [← val_eq_zero, sym2_val, Multiset.sym2_eq_zero_iff, val_eq_zero] @[simp, aesop safe apply (rule_sets := [finsetNonempty])] theorem sym2_nonempty : s.sym2.Nonempty ↔ s.Nonempty := by rw [← not_iff_not] simp_rw [not_nonempty_iff_eq_empty, sym2_eq_empty] protected alias ⟨_, Nonempty.sym2⟩ := sym2_nonempty @[simp] theorem sym2_singleton (a : α) : ({a} : Finset α).sym2 = {Sym2.diag a} := rfl /-- Finset **stars and bars** for the case `n = 2`. -/ theorem card_sym2 (s : Finset α) : s.sym2.card = Nat.choose (s.card + 1) 2 := by rw [card_def, sym2_val, Multiset.card_sym2, ← card_def] end variable {s t : Finset α} {a b : α} section variable [DecidableEq α] theorem sym2_eq_image : s.sym2 = (s ×ˢ s).image Sym2.mk := by ext z refine z.ind fun x y ↦ ?_ rw [mk_mem_sym2_iff, mem_image] constructor · intro h use (x, y) simp only [mem_product, h, and_self, true_and] · rintro ⟨⟨a, b⟩, h⟩ simp only [mem_product, Sym2.eq_iff] at h obtain ⟨h, (⟨rfl, rfl⟩ | ⟨rfl, rfl⟩)⟩ := h <;> simp [h] theorem isDiag_mk_of_mem_diag {a : α × α} (h : a ∈ s.diag) : (Sym2.mk a).IsDiag := (Sym2.isDiag_iff_proj_eq _).2 (mem_diag.1 h).2 theorem not_isDiag_mk_of_mem_offDiag {a : α × α} (h : a ∈ s.offDiag) : ¬ (Sym2.mk a).IsDiag := by rw [Sym2.isDiag_iff_proj_eq] exact (mem_offDiag.1 h).2.2 end section Sym2 variable {m : Sym2 α} -- Porting note: add this lemma and remove simp in the next lemma since simpNF lint -- warns that its LHS is not in normal form @[simp] theorem diag_mem_sym2_mem_iff : (∀ b, b ∈ Sym2.diag a → b ∈ s) ↔ a ∈ s := by rw [← mem_sym2_iff] exact mk_mem_sym2_iff.trans <| and_self_iff theorem diag_mem_sym2_iff : Sym2.diag a ∈ s.sym2 ↔ a ∈ s := by simp [diag_mem_sym2_mem_iff] theorem image_diag_union_image_offDiag [DecidableEq α] : s.diag.image Sym2.mk ∪ s.offDiag.image Sym2.mk = s.sym2 := by rw [← image_union, diag_union_offDiag, sym2_eq_image] end Sym2 section Sym variable [DecidableEq α] {n : ℕ} -- Porting note: instance needed instance : DecidableEq (Sym α n) := inferInstanceAs <| DecidableEq <| Subtype _ /-- Lifts a finset to `Sym α n`. `s.sym n` is the finset of all unordered tuples of cardinality `n` with elements in `s`. -/ protected def sym (s : Finset α) : ∀ n, Finset (Sym α n) | 0 => {∅} | n + 1 => s.sup fun a ↦ Finset.image (Sym.cons a) (s.sym n) @[simp] theorem sym_zero : s.sym 0 = {∅} := rfl @[simp] theorem sym_succ : s.sym (n + 1) = s.sup fun a ↦ (s.sym n).image <| Sym.cons a := rfl @[simp] theorem mem_sym_iff {m : Sym α n} : m ∈ s.sym n ↔ ∀ a ∈ m, a ∈ s := by induction' n with n ih · refine mem_singleton.trans ⟨?_, fun _ ↦ Sym.eq_nil_of_card_zero _⟩ rintro rfl exact fun a ha ↦ (Finset.not_mem_empty _ ha).elim refine mem_sup.trans ⟨?_, fun h ↦ ?_⟩ · rintro ⟨a, ha, he⟩ b hb rw [mem_image] at he obtain ⟨m, he, rfl⟩ := he rw [Sym.mem_cons] at hb obtain rfl | hb := hb · exact ha · exact ih.1 he _ hb · obtain ⟨a, m, rfl⟩ := m.exists_eq_cons_of_succ exact ⟨a, h _ <| Sym.mem_cons_self _ _, mem_image_of_mem _ <| ih.2 fun b hb ↦ h _ <| Sym.mem_cons_of_mem hb⟩ @[simp] theorem sym_empty (n : ℕ) : (∅ : Finset α).sym (n + 1) = ∅ := rfl theorem replicate_mem_sym (ha : a ∈ s) (n : ℕ) : Sym.replicate n a ∈ s.sym n := mem_sym_iff.2 fun b hb ↦ by rwa [(Sym.mem_replicate.1 hb).2] protected theorem Nonempty.sym (h : s.Nonempty) (n : ℕ) : (s.sym n).Nonempty := let ⟨_a, ha⟩ := h ⟨_, replicate_mem_sym ha n⟩ @[simp] theorem sym_singleton (a : α) (n : ℕ) : ({a} : Finset α).sym n = {Sym.replicate n a} := eq_singleton_iff_unique_mem.2 ⟨replicate_mem_sym (mem_singleton.2 rfl) _, fun _s hs ↦ Sym.eq_replicate_iff.2 fun _b hb ↦ eq_of_mem_singleton <| mem_sym_iff.1 hs _ hb⟩ theorem eq_empty_of_sym_eq_empty (h : s.sym n = ∅) : s = ∅ := by rw [← not_nonempty_iff_eq_empty] at h ⊢ exact fun hs ↦ h (hs.sym _) @[simp] theorem sym_eq_empty : s.sym n = ∅ ↔ n ≠ 0 ∧ s = ∅ := by cases n · exact iff_of_false (singleton_ne_empty _) fun h ↦ (h.1 rfl).elim · refine ⟨fun h ↦ ⟨Nat.succ_ne_zero _, eq_empty_of_sym_eq_empty h⟩, ?_⟩ rintro ⟨_, rfl⟩ exact sym_empty _ @[simp] theorem sym_nonempty : (s.sym n).Nonempty ↔ n = 0 ∨ s.Nonempty := by simp only [nonempty_iff_ne_empty, ne_eq, sym_eq_empty, not_and_or, not_ne_iff] @[simp] theorem sym_univ [Fintype α] (n : ℕ) : (univ : Finset α).sym n = univ := eq_univ_iff_forall.2 fun _s ↦ mem_sym_iff.2 fun _a _ ↦ mem_univ _ @[simp] theorem sym_mono (h : s ⊆ t) (n : ℕ) : s.sym n ⊆ t.sym n := fun _m hm ↦ mem_sym_iff.2 fun _a ha ↦ h <| mem_sym_iff.1 hm _ ha @[simp] theorem sym_inter (s t : Finset α) (n : ℕ) : (s ∩ t).sym n = s.sym n ∩ t.sym n := by ext m simp only [mem_inter, mem_sym_iff, imp_and, forall_and] @[simp] theorem sym_union (s t : Finset α) (n : ℕ) : s.sym n ∪ t.sym n ⊆ (s ∪ t).sym n := union_subset (sym_mono subset_union_left n) (sym_mono subset_union_right n) theorem sym_fill_mem (a : α) {i : Fin (n + 1)} {m : Sym α (n - i)} (h : m ∈ s.sym (n - i)) : m.fill a i ∈ (insert a s).sym n := mem_sym_iff.2 fun b hb ↦ mem_insert.2 <| (Sym.mem_fill_iff.1 hb).imp And.right <| mem_sym_iff.1 h b theorem sym_filterNe_mem {m : Sym α n} (a : α) (h : m ∈ s.sym n) : (m.filterNe a).2 ∈ (Finset.erase s a).sym (n - (m.filterNe a).1) := mem_sym_iff.2 fun b H ↦ mem_erase.2 <| (Multiset.mem_filter.1 H).symm.imp Ne.symm <| mem_sym_iff.1 h b /-- If `a` does not belong to the finset `s`, then the `n`th symmetric power of `{a} ∪ s` is in 1-1 correspondence with the disjoint union of the `n - i`th symmetric powers of `s`, for `0 ≤ i ≤ n`. -/ @[simps] def symInsertEquiv (h : a ∉ s) : (insert a s).sym n ≃ Σi : Fin (n + 1), s.sym (n - i) where toFun m := ⟨_, (m.1.filterNe a).2, by convert sym_filterNe_mem a m.2; rw [erase_insert h]⟩ invFun m := ⟨m.2.1.fill a m.1, sym_fill_mem a m.2.2⟩ left_inv m := Subtype.ext <| m.1.fill_filterNe a right_inv := fun ⟨i, m, hm⟩ ↦ by refine Function.Injective.sigma_map (β₂ := ?_) (f₂ := ?_) (Function.injective_id) (fun i ↦ ?_) ?_ · exact fun i ↦ Sym α (n - i) swap · exact Subtype.coe_injective refine Eq.trans ?_ (Sym.filter_ne_fill a _ ?_) exacts [rfl, h ∘ mem_sym_iff.1 hm a] end Sym end Finset
Data\Finset\Union.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.Finset.Basic import Mathlib.Data.Multiset.Bind import Mathlib.Order.SetNotation /-! # Unions of finite sets This file defines the union of a family `t : α → Finset β` of finsets bounded by a finset `s : Finset α`. ## Main declarations * `Finset.disjUnion`: Given a hypothesis `h` which states that finsets `s` and `t` are disjoint, `s.disjUnion t h` is the set such that `a ∈ disjUnion s t h` iff `a ∈ s` or `a ∈ t`; this does not require decidable equality on the type `α`. * `Finset.biUnion`: Finite unions of finsets; given an indexing function `f : α → Finset β` and an `s : Finset α`, `s.biUnion f` is the union of all finsets of the form `f a` for `a ∈ s`. ## TODO Remove `Finset.biUnion` in favour of `Finset.sup`. -/ assert_not_exists MonoidWithZero assert_not_exists MulAction variable {α β γ : Type*} {s s₁ s₂ : Finset α} {t t₁ t₂ : α → Finset β} namespace Finset section DisjiUnion /-- `disjiUnion s f h` is the set such that `a ∈ disjiUnion s f` iff `a ∈ f i` for some `i ∈ s`. It is the same as `s.biUnion f`, but it does not require decidable equality on the type. The hypothesis ensures that the sets are disjoint. -/ def disjiUnion (s : Finset α) (t : α → Finset β) (hf : (s : Set α).PairwiseDisjoint t) : Finset β := ⟨s.val.bind (Finset.val ∘ t), Multiset.nodup_bind.2 ⟨fun a _ ↦ (t a).nodup, s.nodup.pairwise fun _ ha _ hb hab ↦ disjoint_val.2 <| hf ha hb hab⟩⟩ @[simp] lemma disjiUnion_val (s : Finset α) (t : α → Finset β) (h) : (s.disjiUnion t h).1 = s.1.bind fun a ↦ (t a).1 := rfl @[simp] lemma disjiUnion_empty (t : α → Finset β) : disjiUnion ∅ t (by simp) = ∅ := rfl @[simp] lemma mem_disjiUnion {b : β} {h} : b ∈ s.disjiUnion t h ↔ ∃ a ∈ s, b ∈ t a := by simp only [mem_def, disjiUnion_val, Multiset.mem_bind, exists_prop] @[simp, norm_cast] lemma coe_disjiUnion {h} : (s.disjiUnion t h : Set β) = ⋃ x ∈ (s : Set α), t x := by simp [Set.ext_iff, mem_disjiUnion, Set.mem_iUnion, iff_self_iff, mem_coe, imp_true_iff] @[simp] lemma disjiUnion_cons (a : α) (s : Finset α) (ha : a ∉ s) (f : α → Finset β) (H) : disjiUnion (cons a s ha) f H = (f a).disjUnion ((s.disjiUnion f) fun _ hb _ hc ↦ H (mem_cons_of_mem hb) (mem_cons_of_mem hc)) (disjoint_left.2 fun _ hb h ↦ let ⟨_, hc, h⟩ := mem_disjiUnion.mp h disjoint_left.mp (H (mem_cons_self a s) (mem_cons_of_mem hc) (ne_of_mem_of_not_mem hc ha).symm) hb h) := eq_of_veq <| Multiset.cons_bind _ _ _ @[simp] lemma singleton_disjiUnion (a : α) {h} : Finset.disjiUnion {a} t h = t a := eq_of_veq <| Multiset.singleton_bind _ _ lemma disjiUnion_disjiUnion (s : Finset α) (f : α → Finset β) (g : β → Finset γ) (h1 h2) : (s.disjiUnion f h1).disjiUnion g h2 = s.attach.disjiUnion (fun a ↦ ((f a).disjiUnion g) fun b hb c hc ↦ h2 (mem_disjiUnion.mpr ⟨_, a.prop, hb⟩) (mem_disjiUnion.mpr ⟨_, a.prop, hc⟩)) fun a _ b _ hab ↦ disjoint_left.mpr fun x hxa hxb ↦ by obtain ⟨xa, hfa, hga⟩ := mem_disjiUnion.mp hxa obtain ⟨xb, hfb, hgb⟩ := mem_disjiUnion.mp hxb refine disjoint_left.mp (h2 (mem_disjiUnion.mpr ⟨_, a.prop, hfa⟩) (mem_disjiUnion.mpr ⟨_, b.prop, hfb⟩) ?_) hga hgb rintro rfl exact disjoint_left.mp (h1 a.prop b.prop <| Subtype.coe_injective.ne hab) hfa hfb := eq_of_veq <| Multiset.bind_assoc.trans (Multiset.attach_bind_coe _ _).symm variable [DecidableEq β] {s : Finset α} {t : Finset β} {f : α → β} private lemma pairwiseDisjoint_fibers : Set.PairwiseDisjoint ↑t fun a ↦ s.filter (f · = a) := fun x' hx y' hy hne ↦ by simp_rw [disjoint_left, mem_filter]; rintro i ⟨_, rfl⟩ ⟨_, rfl⟩; exact hne rfl -- `simpNF` claims that the statement can't simplify itself, but it can (as of 2024-02-14) @[simp, nolint simpNF] lemma disjiUnion_filter_eq (s : Finset α) (t : Finset β) (f : α → β) : t.disjiUnion (fun a ↦ s.filter (f · = a)) pairwiseDisjoint_fibers = s.filter fun c ↦ f c ∈ t := ext fun b => by simpa using and_comm lemma disjiUnion_filter_eq_of_maps_to (h : ∀ x ∈ s, f x ∈ t) : t.disjiUnion (fun a ↦ s.filter (f · = a)) pairwiseDisjoint_fibers = s := by simpa [filter_eq_self] end DisjiUnion section BUnion variable [DecidableEq β] /-- `Finset.biUnion s t` is the union of `t a` over `a ∈ s`. (This was formerly `bind` due to the monad structure on types with `DecidableEq`.) -/ protected def biUnion (s : Finset α) (t : α → Finset β) : Finset β := (s.1.bind fun a ↦ (t a).1).toFinset @[simp] lemma biUnion_val (s : Finset α) (t : α → Finset β) : (s.biUnion t).1 = (s.1.bind fun a ↦ (t a).1).dedup := rfl @[simp] lemma biUnion_empty : Finset.biUnion ∅ t = ∅ := rfl @[simp] lemma mem_biUnion {b : β} : b ∈ s.biUnion t ↔ ∃ a ∈ s, b ∈ t a := by simp only [mem_def, biUnion_val, Multiset.mem_dedup, Multiset.mem_bind, exists_prop] @[simp, norm_cast] lemma coe_biUnion : (s.biUnion t : Set β) = ⋃ x ∈ (s : Set α), t x := by simp [Set.ext_iff, mem_biUnion, Set.mem_iUnion, iff_self_iff, mem_coe, imp_true_iff] @[simp] lemma biUnion_insert [DecidableEq α] {a : α} : (insert a s).biUnion t = t a ∪ s.biUnion t := ext fun x ↦ by simp only [mem_biUnion, exists_prop, mem_union, mem_insert, or_and_right, exists_or, exists_eq_left] lemma biUnion_congr (hs : s₁ = s₂) (ht : ∀ a ∈ s₁, t₁ a = t₂ a) : s₁.biUnion t₁ = s₂.biUnion t₂ := ext fun x ↦ by -- Porting note: this entire proof was `simp [or_and_right, exists_or]` simp_rw [mem_biUnion] apply exists_congr simp (config := { contextual := true }) only [hs, and_congr_right_iff, ht, implies_true] @[simp] lemma disjiUnion_eq_biUnion (s : Finset α) (f : α → Finset β) (hf) : s.disjiUnion f hf = s.biUnion f := eq_of_veq (s.disjiUnion f hf).nodup.dedup.symm lemma biUnion_subset {s' : Finset β} : s.biUnion t ⊆ s' ↔ ∀ x ∈ s, t x ⊆ s' := by simp only [subset_iff, mem_biUnion] exact ⟨fun H a ha b hb ↦ H ⟨a, ha, hb⟩, fun H b ⟨a, ha, hb⟩ ↦ H a ha hb⟩ @[simp] lemma singleton_biUnion {a : α} : Finset.biUnion {a} t = t a := by classical rw [← insert_emptyc_eq, biUnion_insert, biUnion_empty, union_empty] lemma biUnion_inter (s : Finset α) (f : α → Finset β) (t : Finset β) : s.biUnion f ∩ t = s.biUnion fun x ↦ f x ∩ t := by ext x simp only [mem_biUnion, mem_inter] tauto lemma inter_biUnion (t : Finset β) (s : Finset α) (f : α → Finset β) : t ∩ s.biUnion f = s.biUnion fun x ↦ t ∩ f x := by rw [inter_comm, biUnion_inter] simp [inter_comm] lemma biUnion_biUnion [DecidableEq γ] (s : Finset α) (f : α → Finset β) (g : β → Finset γ) : (s.biUnion f).biUnion g = s.biUnion fun a ↦ (f a).biUnion g := by ext simp only [Finset.mem_biUnion, exists_prop] simp_rw [← exists_and_right, ← exists_and_left, and_assoc] rw [exists_comm] lemma bind_toFinset [DecidableEq α] (s : Multiset α) (t : α → Multiset β) : (s.bind t).toFinset = s.toFinset.biUnion fun a ↦ (t a).toFinset := ext fun x ↦ by simp only [Multiset.mem_toFinset, mem_biUnion, Multiset.mem_bind, exists_prop] lemma biUnion_mono (h : ∀ a ∈ s, t₁ a ⊆ t₂ a) : s.biUnion t₁ ⊆ s.biUnion t₂ := by have : ∀ b a, a ∈ s → b ∈ t₁ a → ∃ a : α, a ∈ s ∧ b ∈ t₂ a := fun b a ha hb ↦ ⟨a, ha, Finset.mem_of_subset (h a ha) hb⟩ simpa only [subset_iff, mem_biUnion, exists_imp, and_imp, exists_prop] lemma biUnion_subset_biUnion_of_subset_left (t : α → Finset β) (h : s₁ ⊆ s₂) : s₁.biUnion t ⊆ s₂.biUnion t := fun x ↦ by simp only [and_imp, mem_biUnion, exists_prop]; exact Exists.imp fun a ha ↦ ⟨h ha.1, ha.2⟩ lemma subset_biUnion_of_mem (u : α → Finset β) {x : α} (xs : x ∈ s) : u x ⊆ s.biUnion u := singleton_biUnion.superset.trans <| biUnion_subset_biUnion_of_subset_left u <| singleton_subset_iff.2 xs @[simp] lemma biUnion_subset_iff_forall_subset {α β : Type*} [DecidableEq β] {s : Finset α} {t : Finset β} {f : α → Finset β} : s.biUnion f ⊆ t ↔ ∀ x ∈ s, f x ⊆ t := ⟨fun h _ hx ↦ (subset_biUnion_of_mem f hx).trans h, fun h _ hx ↦ let ⟨_, ha₁, ha₂⟩ := mem_biUnion.mp hx h _ ha₁ ha₂⟩ @[simp] lemma biUnion_singleton_eq_self [DecidableEq α] : s.biUnion (singleton : α → Finset α) = s := ext fun x ↦ by simp only [mem_biUnion, mem_singleton, exists_prop, exists_eq_right'] lemma filter_biUnion (s : Finset α) (f : α → Finset β) (p : β → Prop) [DecidablePred p] : (s.biUnion f).filter p = s.biUnion fun a ↦ (f a).filter p := by ext b simp only [mem_biUnion, exists_prop, mem_filter] constructor · rintro ⟨⟨a, ha, hba⟩, hb⟩ exact ⟨a, ha, hba, hb⟩ · rintro ⟨a, ha, hba, hb⟩ exact ⟨⟨a, ha, hba⟩, hb⟩ lemma biUnion_filter_eq_of_maps_to [DecidableEq α] {s : Finset α} {t : Finset β} {f : α → β} (h : ∀ x ∈ s, f x ∈ t) : (t.biUnion fun a ↦ s.filter fun c ↦ f c = a) = s := by simpa only [disjiUnion_eq_biUnion] using disjiUnion_filter_eq_of_maps_to h lemma erase_biUnion (f : α → Finset β) (s : Finset α) (b : β) : (s.biUnion f).erase b = s.biUnion fun x ↦ (f x).erase b := by ext a simp only [mem_biUnion, not_exists, not_and, mem_erase, ne_eq] tauto @[simp] lemma biUnion_nonempty : (s.biUnion t).Nonempty ↔ ∃ x ∈ s, (t x).Nonempty := by simp only [Finset.Nonempty, mem_biUnion] rw [exists_swap] simp [exists_and_left] lemma Nonempty.biUnion (hs : s.Nonempty) (ht : ∀ x ∈ s, (t x).Nonempty) : (s.biUnion t).Nonempty := biUnion_nonempty.2 <| hs.imp fun x hx ↦ ⟨hx, ht x hx⟩ lemma disjoint_biUnion_left (s : Finset α) (f : α → Finset β) (t : Finset β) : Disjoint (s.biUnion f) t ↔ ∀ i ∈ s, Disjoint (f i) t := by classical refine s.induction ?_ ?_ · simp only [forall_mem_empty_iff, biUnion_empty, disjoint_empty_left] · intro i s his ih simp only [disjoint_union_left, biUnion_insert, his, forall_mem_insert, ih] lemma disjoint_biUnion_right (s : Finset β) (t : Finset α) (f : α → Finset β) : Disjoint s (t.biUnion f) ↔ ∀ i ∈ t, Disjoint s (f i) := by simpa only [_root_.disjoint_comm] using disjoint_biUnion_left t f s end BUnion end Finset
Data\Finset\Update.lean
/- Copyright (c) 2023 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import Mathlib.Data.Finset.Basic /-! # Update a function on a set of values This file defines `Function.updateFinset`, the operation that updates a function on a (finite) set of values. This is a very specific function used for `MeasureTheory.marginal`, and possibly not that useful for other purposes. -/ variable {ι : Sort _} {π : ι → Sort _} {x : ∀ i, π i} [DecidableEq ι] namespace Function /-- `updateFinset x s y` is the vector `x` with the coordinates in `s` changed to the values of `y`. -/ def updateFinset (x : ∀ i, π i) (s : Finset ι) (y : ∀ i : ↥s, π i) (i : ι) : π i := if hi : i ∈ s then y ⟨i, hi⟩ else x i open Finset Equiv theorem updateFinset_def {s : Finset ι} {y} : updateFinset x s y = fun i ↦ if hi : i ∈ s then y ⟨i, hi⟩ else x i := rfl @[simp] theorem updateFinset_empty {y} : updateFinset x ∅ y = x := rfl theorem updateFinset_singleton {i y} : updateFinset x {i} y = Function.update x i (y ⟨i, mem_singleton_self i⟩) := by congr with j by_cases hj : j = i · cases hj simp only [dif_pos, Finset.mem_singleton, update_same, updateFinset] · simp [hj, updateFinset] theorem update_eq_updateFinset {i y} : Function.update x i y = updateFinset x {i} (uniqueElim y) := by congr with j by_cases hj : j = i · cases hj simp only [dif_pos, Finset.mem_singleton, update_same, updateFinset] exact uniqueElim_default (α := fun j : ({i} : Finset ι) => π j) y · simp [hj, updateFinset] theorem updateFinset_updateFinset {s t : Finset ι} (hst : Disjoint s t) {y : ∀ i : ↥s, π i} {z : ∀ i : ↥t, π i} : updateFinset (updateFinset x s y) t z = updateFinset x (s ∪ t) (Equiv.piFinsetUnion π hst ⟨y, z⟩) := by set e := Equiv.Finset.union s t hst congr with i by_cases his : i ∈ s <;> by_cases hit : i ∈ t <;> simp only [updateFinset, his, hit, dif_pos, dif_neg, Finset.mem_union, true_or_iff, false_or_iff, not_false_iff] · exfalso; exact Finset.disjoint_left.mp hst his hit · exact piCongrLeft_sum_inl (fun b : ↥(s ∪ t) => π b) e y z ⟨i, his⟩ |>.symm · exact piCongrLeft_sum_inr (fun b : ↥(s ∪ t) => π b) e y z ⟨i, hit⟩ |>.symm end Function
Data\Finset\Pointwise\Interval.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.Finset.Pointwise import Mathlib.Data.Set.Pointwise.Interval /-! # Pointwise operations on intervals This should be kept in sync with `Mathlib/Data/Set/Pointwise/Interval.lean`. -/ variable {α : Type*} namespace Finset open scoped Pointwise /-! ### Binary pointwise operations Note that the subset operations below only cover the cases with the largest possible intervals on the LHS: to conclude that `Ioo a b * Ioo c d ⊆ Ioo (a * c) (c * d)`, you can use monotonicity of `*` and `Finset.Ico_mul_Ioc_subset`. TODO: repeat these lemmas for the generality of `mul_le_mul` (which assumes nonnegativity), which the unprimed names have been reserved for -/ section ContravariantLE variable [Mul α] [Preorder α] [DecidableEq α] variable [CovariantClass α α (· * ·) (· ≤ ·)] [CovariantClass α α (Function.swap HMul.hMul) LE.le] @[to_additive Icc_add_Icc_subset] theorem Icc_mul_Icc_subset' [LocallyFiniteOrder α] (a b c d : α) : Icc a b * Icc c d ⊆ Icc (a * c) (b * d) := Finset.coe_subset.mp <| by simpa using Set.Icc_mul_Icc_subset' _ _ _ _ @[to_additive Iic_add_Iic_subset] theorem Iic_mul_Iic_subset' [LocallyFiniteOrderBot α] (a b : α) : Iic a * Iic b ⊆ Iic (a * b) := Finset.coe_subset.mp <| by simpa using Set.Iic_mul_Iic_subset' _ _ @[to_additive Ici_add_Ici_subset] theorem Ici_mul_Ici_subset' [LocallyFiniteOrderTop α] (a b : α) : Ici a * Ici b ⊆ Ici (a * b) := Finset.coe_subset.mp <| by simpa using Set.Ici_mul_Ici_subset' _ _ end ContravariantLE section ContravariantLT variable [Mul α] [PartialOrder α] [DecidableEq α] variable [CovariantClass α α (· * ·) (· < ·)] [CovariantClass α α (Function.swap HMul.hMul) LT.lt] @[to_additive Icc_add_Ico_subset] theorem Icc_mul_Ico_subset' [LocallyFiniteOrder α] (a b c d : α) : Icc a b * Ico c d ⊆ Ico (a * c) (b * d) := Finset.coe_subset.mp <| by simpa using Set.Icc_mul_Ico_subset' _ _ _ _ @[to_additive Ico_add_Icc_subset] theorem Ico_mul_Icc_subset' [LocallyFiniteOrder α] (a b c d : α) : Ico a b * Icc c d ⊆ Ico (a * c) (b * d) := Finset.coe_subset.mp <| by simpa using Set.Ico_mul_Icc_subset' _ _ _ _ @[to_additive Ioc_add_Ico_subset] theorem Ioc_mul_Ico_subset' [LocallyFiniteOrder α] (a b c d : α) : Ioc a b * Ico c d ⊆ Ioo (a * c) (b * d) := Finset.coe_subset.mp <| by simpa using Set.Ioc_mul_Ico_subset' _ _ _ _ @[to_additive Ico_add_Ioc_subset] theorem Ico_mul_Ioc_subset' [LocallyFiniteOrder α] (a b c d : α) : Ico a b * Ioc c d ⊆ Ioo (a * c) (b * d) := Finset.coe_subset.mp <| by simpa using Set.Ico_mul_Ioc_subset' _ _ _ _ @[to_additive Iic_add_Iio_subset] theorem Iic_mul_Iio_subset' [LocallyFiniteOrderBot α] (a b : α) : Iic a * Iio b ⊆ Iio (a * b) := Finset.coe_subset.mp <| by simpa using Set.Iic_mul_Iio_subset' _ _ @[to_additive Iio_add_Iic_subset] theorem Iio_mul_Iic_subset' [LocallyFiniteOrderBot α] (a b : α) : Iio a * Iic b ⊆ Iio (a * b) := Finset.coe_subset.mp <| by simpa using Set.Iio_mul_Iic_subset' _ _ @[to_additive Ioi_add_Ici_subset] theorem Ioi_mul_Ici_subset' [LocallyFiniteOrderTop α] (a b : α) : Ioi a * Ici b ⊆ Ioi (a * b) := Finset.coe_subset.mp <| by simpa using Set.Ioi_mul_Ici_subset' _ _ @[to_additive Ici_add_Ioi_subset] theorem Ici_mul_Ioi_subset' [LocallyFiniteOrderTop α] (a b : α) : Ici a * Ioi b ⊆ Ioi (a * b) := Finset.coe_subset.mp <| by simpa using Set.Ici_mul_Ioi_subset' _ _ end ContravariantLT end Finset
Data\Finsupp\AList.lean
/- Copyright (c) 2022 Violeta Hernández. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Violeta Hernández -/ import Mathlib.Data.Finsupp.Basic import Mathlib.Data.List.AList /-! # Connections between `Finsupp` and `AList` ## Main definitions * `Finsupp.toAList` * `AList.lookupFinsupp`: converts an association list into a finitely supported function via `AList.lookup`, sending absent keys to zero. -/ namespace Finsupp variable {α M : Type*} [Zero M] /-- Produce an association list for the finsupp over its support using choice. -/ @[simps] noncomputable def toAList (f : α →₀ M) : AList fun _x : α => M := ⟨f.graph.toList.map Prod.toSigma, by rw [List.NodupKeys, List.keys, List.map_map, Prod.fst_comp_toSigma, List.nodup_map_iff_inj_on] · rintro ⟨b, m⟩ hb ⟨c, n⟩ hc (rfl : b = c) rw [Finset.mem_toList, Finsupp.mem_graph_iff] at hb hc dsimp at hb hc rw [← hc.1, hb.1] · apply Finset.nodup_toList⟩ @[simp] theorem toAList_keys_toFinset [DecidableEq α] (f : α →₀ M) : f.toAList.keys.toFinset = f.support := by ext simp [toAList, AList.mem_keys, AList.keys, List.keys] @[simp] theorem mem_toAlist {f : α →₀ M} {x : α} : x ∈ f.toAList ↔ f x ≠ 0 := by classical rw [AList.mem_keys, ← List.mem_toFinset, toAList_keys_toFinset, mem_support_iff] end Finsupp namespace AList variable {α M : Type*} [Zero M] open List /-- Converts an association list into a finitely supported function via `AList.lookup`, sending absent keys to zero. -/ noncomputable def lookupFinsupp (l : AList fun _x : α => M) : α →₀ M where support := by haveI := Classical.decEq α; haveI := Classical.decEq M exact (l.1.filter fun x => Sigma.snd x ≠ 0).keys.toFinset toFun a := haveI := Classical.decEq α (l.lookup a).getD 0 mem_support_toFun a := by classical simp_rw [@mem_toFinset _ _, List.mem_keys, List.mem_filter, ← mem_lookup_iff] cases lookup a l <;> simp @[simp] theorem lookupFinsupp_apply [DecidableEq α] (l : AList fun _x : α => M) (a : α) : l.lookupFinsupp a = (l.lookup a).getD 0 := by convert rfl; congr @[simp] theorem lookupFinsupp_support [DecidableEq α] [DecidableEq M] (l : AList fun _x : α => M) : l.lookupFinsupp.support = (l.1.filter fun x => Sigma.snd x ≠ 0).keys.toFinset := by dsimp only [lookupFinsupp] congr! theorem lookupFinsupp_eq_iff_of_ne_zero [DecidableEq α] {l : AList fun _x : α => M} {a : α} {x : M} (hx : x ≠ 0) : l.lookupFinsupp a = x ↔ x ∈ l.lookup a := by rw [lookupFinsupp_apply] cases' lookup a l with m <;> simp [hx.symm] theorem lookupFinsupp_eq_zero_iff [DecidableEq α] {l : AList fun _x : α => M} {a : α} : l.lookupFinsupp a = 0 ↔ a ∉ l ∨ (0 : M) ∈ l.lookup a := by rw [lookupFinsupp_apply, ← lookup_eq_none] cases' lookup a l with m <;> simp @[simp] theorem empty_lookupFinsupp : lookupFinsupp (∅ : AList fun _x : α => M) = 0 := by classical ext simp @[simp] theorem insert_lookupFinsupp [DecidableEq α] (l : AList fun _x : α => M) (a : α) (m : M) : (l.insert a m).lookupFinsupp = l.lookupFinsupp.update a m := by ext b by_cases h : b = a <;> simp [h] @[simp] theorem singleton_lookupFinsupp (a : α) (m : M) : (singleton a m).lookupFinsupp = Finsupp.single a m := by classical -- porting note (#10745): was `simp [← AList.insert_empty]` but timeout issues simp only [← AList.insert_empty, insert_lookupFinsupp, empty_lookupFinsupp, Finsupp.zero_update] @[simp] theorem _root_.Finsupp.toAList_lookupFinsupp (f : α →₀ M) : f.toAList.lookupFinsupp = f := by ext a classical by_cases h : f a = 0 · suffices f.toAList.lookup a = none by simp [h, this] simp [lookup_eq_none, h] · suffices f.toAList.lookup a = some (f a) by simp [h, this] apply mem_lookup_iff.2 simpa using h theorem lookupFinsupp_surjective : Function.Surjective (@lookupFinsupp α M _) := fun f => ⟨_, Finsupp.toAList_lookupFinsupp f⟩ end AList
Data\Finsupp\Antidiagonal.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.Finset.NatAntidiagonal import Mathlib.Data.Finsupp.Multiset import Mathlib.Data.Multiset.Antidiagonal /-! # The `Finsupp` counterpart of `Multiset.antidiagonal`. The antidiagonal of `s : α →₀ ℕ` consists of all pairs `(t₁, t₂) : (α →₀ ℕ) × (α →₀ ℕ)` such that `t₁ + t₂ = s`. -/ namespace Finsupp open Finset universe u variable {α : Type u} [DecidableEq α] /-- The `Finsupp` counterpart of `Multiset.antidiagonal`: the antidiagonal of `s : α →₀ ℕ` consists of all pairs `(t₁, t₂) : (α →₀ ℕ) × (α →₀ ℕ)` such that `t₁ + t₂ = s`. The finitely supported function `antidiagonal s` is equal to the multiplicities of these pairs. -/ def antidiagonal' (f : α →₀ ℕ) : (α →₀ ℕ) × (α →₀ ℕ) →₀ ℕ := Multiset.toFinsupp ((Finsupp.toMultiset f).antidiagonal.map (Prod.map Multiset.toFinsupp Multiset.toFinsupp)) /-- The antidiagonal of `s : α →₀ ℕ` is the finset of all pairs `(t₁, t₂) : (α →₀ ℕ) × (α →₀ ℕ)` such that `t₁ + t₂ = s`. -/ instance instHasAntidiagonal : HasAntidiagonal (α →₀ ℕ) where antidiagonal f := f.antidiagonal'.support mem_antidiagonal {f} {p} := by rcases p with ⟨p₁, p₂⟩ simp [antidiagonal', ← and_assoc, Multiset.toFinsupp_eq_iff, ← Multiset.toFinsupp_eq_iff (f := f)] @[simp] theorem antidiagonal_zero : antidiagonal (0 : α →₀ ℕ) = singleton (0, 0) := rfl @[to_additive] theorem prod_antidiagonal_swap {M : Type*} [CommMonoid M] (n : α →₀ ℕ) (f : (α →₀ ℕ) → (α →₀ ℕ) → M) : ∏ p ∈ antidiagonal n, f p.1 p.2 = ∏ p ∈ antidiagonal n, f p.2 p.1 := prod_equiv (Equiv.prodComm _ _) (by simp [add_comm]) (by simp) @[simp] theorem antidiagonal_single (a : α) (n : ℕ) : antidiagonal (single a n) = (antidiagonal n).map (Function.Embedding.prodMap ⟨_, single_injective a⟩ ⟨_, single_injective a⟩) := by ext ⟨x, y⟩ simp only [mem_antidiagonal, mem_map, mem_antidiagonal, Function.Embedding.coe_prodMap, Function.Embedding.coeFn_mk, Prod.map_apply, Prod.mk.injEq, Prod.exists] constructor · intro h refine ⟨x a, y a, DFunLike.congr_fun h a |>.trans single_eq_same, ?_⟩ simp_rw [DFunLike.ext_iff, ← forall_and] intro i replace h := DFunLike.congr_fun h i simp_rw [single_apply, Finsupp.add_apply] at h ⊢ obtain rfl | hai := Decidable.eq_or_ne a i · exact ⟨if_pos rfl, if_pos rfl⟩ · simp_rw [if_neg hai, _root_.add_eq_zero_iff] at h ⊢ exact h.imp Eq.symm Eq.symm · rintro ⟨a, b, rfl, rfl, rfl⟩ exact (single_add _ _ _).symm end Finsupp
Data\Finsupp\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, Scott Morrison -/ import Mathlib.Algebra.BigOperators.Finsupp import Mathlib.Algebra.Module.Basic import Mathlib.Algebra.Regular.SMul import Mathlib.Data.Rat.BigOperators /-! # Miscellaneous definitions, lemmas, and constructions using finsupp ## Main declarations * `Finsupp.graph`: the finset of input and output pairs with non-zero outputs. * `Finsupp.mapRange.equiv`: `Finsupp.mapRange` as an equiv. * `Finsupp.mapDomain`: maps the domain of a `Finsupp` by a function and by summing. * `Finsupp.comapDomain`: postcomposition of a `Finsupp` with a function injective on the preimage of its support. * `Finsupp.some`: restrict a finitely supported function on `Option α` to a finitely supported function on `α`. * `Finsupp.filter`: `filter p f` is the finitely supported function that is `f a` if `p a` is true and 0 otherwise. * `Finsupp.frange`: the image of a finitely supported function on its support. * `Finsupp.subtype_domain`: the restriction of a finitely supported function `f` to a subtype. ## Implementation notes This file is a `noncomputable theory` and uses classical logic throughout. ## TODO * This file is currently ~1600 lines long and is quite a miscellany of definitions and lemmas, so it should be divided into smaller pieces. * Expand the list of definitions and important lemmas to the module docstring. -/ noncomputable section open Finset Function variable {α β γ ι M M' N P G H R S : Type*} namespace Finsupp /-! ### Declarations about `graph` -/ section Graph variable [Zero M] /-- The graph of a finitely supported function over its support, i.e. the finset of input and output pairs with non-zero outputs. -/ def graph (f : α →₀ M) : Finset (α × M) := f.support.map ⟨fun a => Prod.mk a (f a), fun _ _ h => (Prod.mk.inj h).1⟩ theorem mk_mem_graph_iff {a : α} {m : M} {f : α →₀ M} : (a, m) ∈ f.graph ↔ f a = m ∧ m ≠ 0 := by simp_rw [graph, mem_map, mem_support_iff] constructor · rintro ⟨b, ha, rfl, -⟩ exact ⟨rfl, ha⟩ · rintro ⟨rfl, ha⟩ exact ⟨a, ha, rfl⟩ @[simp] theorem mem_graph_iff {c : α × M} {f : α →₀ M} : c ∈ f.graph ↔ f c.1 = c.2 ∧ c.2 ≠ 0 := by cases c exact mk_mem_graph_iff theorem mk_mem_graph (f : α →₀ M) {a : α} (ha : a ∈ f.support) : (a, f a) ∈ f.graph := mk_mem_graph_iff.2 ⟨rfl, mem_support_iff.1 ha⟩ theorem apply_eq_of_mem_graph {a : α} {m : M} {f : α →₀ M} (h : (a, m) ∈ f.graph) : f a = m := (mem_graph_iff.1 h).1 @[simp 1100] -- Porting note: change priority to appease `simpNF` theorem not_mem_graph_snd_zero (a : α) (f : α →₀ M) : (a, (0 : M)) ∉ f.graph := fun h => (mem_graph_iff.1 h).2.irrefl @[simp] theorem image_fst_graph [DecidableEq α] (f : α →₀ M) : f.graph.image Prod.fst = f.support := by classical simp only [graph, map_eq_image, image_image, Embedding.coeFn_mk, (· ∘ ·), image_id'] theorem graph_injective (α M) [Zero M] : Injective (@graph α M _) := by intro f g h classical have hsup : f.support = g.support := by rw [← image_fst_graph, h, image_fst_graph] refine ext_iff'.2 ⟨hsup, fun x hx => apply_eq_of_mem_graph <| h.symm ▸ ?_⟩ exact mk_mem_graph _ (hsup ▸ hx) @[simp] theorem graph_inj {f g : α →₀ M} : f.graph = g.graph ↔ f = g := (graph_injective α M).eq_iff @[simp] theorem graph_zero : graph (0 : α →₀ M) = ∅ := by simp [graph] @[simp] theorem graph_eq_empty {f : α →₀ M} : f.graph = ∅ ↔ f = 0 := (graph_injective α M).eq_iff' graph_zero end Graph end Finsupp /-! ### Declarations about `mapRange` -/ section MapRange namespace Finsupp section Equiv variable [Zero M] [Zero N] [Zero P] /-- `Finsupp.mapRange` as an equiv. -/ @[simps apply] def mapRange.equiv (f : M ≃ N) (hf : f 0 = 0) (hf' : f.symm 0 = 0) : (α →₀ M) ≃ (α →₀ N) where toFun := (mapRange f hf : (α →₀ M) → α →₀ N) invFun := (mapRange f.symm hf' : (α →₀ N) → α →₀ M) left_inv x := by rw [← mapRange_comp _ _ _ _] <;> simp_rw [Equiv.symm_comp_self] · exact mapRange_id _ · rfl right_inv x := by rw [← mapRange_comp _ _ _ _] <;> simp_rw [Equiv.self_comp_symm] · exact mapRange_id _ · rfl @[simp] theorem mapRange.equiv_refl : mapRange.equiv (Equiv.refl M) rfl rfl = Equiv.refl (α →₀ M) := Equiv.ext mapRange_id theorem mapRange.equiv_trans (f : M ≃ N) (hf : f 0 = 0) (hf') (f₂ : N ≃ P) (hf₂ : f₂ 0 = 0) (hf₂') : (mapRange.equiv (f.trans f₂) (by rw [Equiv.trans_apply, hf, hf₂]) (by rw [Equiv.symm_trans_apply, hf₂', hf']) : (α →₀ _) ≃ _) = (mapRange.equiv f hf hf').trans (mapRange.equiv f₂ hf₂ hf₂') := Equiv.ext <| mapRange_comp f₂ hf₂ f hf ((congrArg f₂ hf).trans hf₂) @[simp] theorem mapRange.equiv_symm (f : M ≃ N) (hf hf') : ((mapRange.equiv f hf hf').symm : (α →₀ _) ≃ _) = mapRange.equiv f.symm hf' hf := Equiv.ext fun _ => rfl end Equiv section ZeroHom variable [Zero M] [Zero N] [Zero P] /-- Composition with a fixed zero-preserving homomorphism is itself a zero-preserving homomorphism on functions. -/ @[simps] def mapRange.zeroHom (f : ZeroHom M N) : ZeroHom (α →₀ M) (α →₀ N) where toFun := (mapRange f f.map_zero : (α →₀ M) → α →₀ N) map_zero' := mapRange_zero @[simp] theorem mapRange.zeroHom_id : mapRange.zeroHom (ZeroHom.id M) = ZeroHom.id (α →₀ M) := ZeroHom.ext mapRange_id theorem mapRange.zeroHom_comp (f : ZeroHom N P) (f₂ : ZeroHom M N) : (mapRange.zeroHom (f.comp f₂) : ZeroHom (α →₀ _) _) = (mapRange.zeroHom f).comp (mapRange.zeroHom f₂) := ZeroHom.ext <| mapRange_comp f (map_zero f) f₂ (map_zero f₂) (by simp only [comp_apply, map_zero]) end ZeroHom section AddMonoidHom variable [AddCommMonoid M] [AddCommMonoid N] [AddCommMonoid P] variable {F : Type*} [FunLike F M N] [AddMonoidHomClass F M N] /-- Composition with a fixed additive homomorphism is itself an additive homomorphism on functions. -/ @[simps] def mapRange.addMonoidHom (f : M →+ N) : (α →₀ M) →+ α →₀ N where toFun := (mapRange f f.map_zero : (α →₀ M) → α →₀ N) map_zero' := mapRange_zero map_add' a b := by dsimp only; exact mapRange_add f.map_add _ _; -- Porting note: `dsimp` needed @[simp] theorem mapRange.addMonoidHom_id : mapRange.addMonoidHom (AddMonoidHom.id M) = AddMonoidHom.id (α →₀ M) := AddMonoidHom.ext mapRange_id theorem mapRange.addMonoidHom_comp (f : N →+ P) (f₂ : M →+ N) : (mapRange.addMonoidHom (f.comp f₂) : (α →₀ _) →+ _) = (mapRange.addMonoidHom f).comp (mapRange.addMonoidHom f₂) := AddMonoidHom.ext <| mapRange_comp f (map_zero f) f₂ (map_zero f₂) (by simp only [comp_apply, map_zero]) @[simp] theorem mapRange.addMonoidHom_toZeroHom (f : M →+ N) : (mapRange.addMonoidHom f).toZeroHom = (mapRange.zeroHom f.toZeroHom : ZeroHom (α →₀ _) _) := ZeroHom.ext fun _ => rfl theorem mapRange_multiset_sum (f : F) (m : Multiset (α →₀ M)) : mapRange f (map_zero f) m.sum = (m.map fun x => mapRange f (map_zero f) x).sum := (mapRange.addMonoidHom (f : M →+ N) : (α →₀ _) →+ _).map_multiset_sum _ theorem mapRange_finset_sum (f : F) (s : Finset ι) (g : ι → α →₀ M) : mapRange f (map_zero f) (∑ x ∈ s, g x) = ∑ x ∈ s, mapRange f (map_zero f) (g x) := map_sum (mapRange.addMonoidHom (f : M →+ N)) _ _ /-- `Finsupp.mapRange.AddMonoidHom` as an equiv. -/ @[simps apply] def mapRange.addEquiv (f : M ≃+ N) : (α →₀ M) ≃+ (α →₀ N) := { mapRange.addMonoidHom f.toAddMonoidHom with toFun := (mapRange f f.map_zero : (α →₀ M) → α →₀ N) invFun := (mapRange f.symm f.symm.map_zero : (α →₀ N) → α →₀ M) left_inv := fun x => by rw [← mapRange_comp _ _ _ _] <;> simp_rw [AddEquiv.symm_comp_self] · exact mapRange_id _ · rfl right_inv := fun x => by rw [← mapRange_comp _ _ _ _] <;> simp_rw [AddEquiv.self_comp_symm] · exact mapRange_id _ · rfl } @[simp] theorem mapRange.addEquiv_refl : mapRange.addEquiv (AddEquiv.refl M) = AddEquiv.refl (α →₀ M) := AddEquiv.ext mapRange_id theorem mapRange.addEquiv_trans (f : M ≃+ N) (f₂ : N ≃+ P) : (mapRange.addEquiv (f.trans f₂) : (α →₀ M) ≃+ (α →₀ P)) = (mapRange.addEquiv f).trans (mapRange.addEquiv f₂) := AddEquiv.ext (mapRange_comp _ f₂.map_zero _ f.map_zero (by simp)) @[simp] theorem mapRange.addEquiv_symm (f : M ≃+ N) : ((mapRange.addEquiv f).symm : (α →₀ _) ≃+ _) = mapRange.addEquiv f.symm := AddEquiv.ext fun _ => rfl @[simp] theorem mapRange.addEquiv_toAddMonoidHom (f : M ≃+ N) : ((mapRange.addEquiv f : (α →₀ _) ≃+ _) : _ →+ _) = (mapRange.addMonoidHom f.toAddMonoidHom : (α →₀ _) →+ _) := AddMonoidHom.ext fun _ => rfl @[simp] theorem mapRange.addEquiv_toEquiv (f : M ≃+ N) : ↑(mapRange.addEquiv f : (α →₀ _) ≃+ _) = (mapRange.equiv (f : M ≃ N) f.map_zero f.symm.map_zero : (α →₀ _) ≃ _) := Equiv.ext fun _ => rfl end AddMonoidHom end Finsupp end MapRange /-! ### Declarations about `equivCongrLeft` -/ section EquivCongrLeft variable [Zero M] namespace Finsupp /-- Given `f : α ≃ β`, we can map `l : α →₀ M` to `equivMapDomain f l : β →₀ M` (computably) by mapping the support forwards and the function backwards. -/ def equivMapDomain (f : α ≃ β) (l : α →₀ M) : β →₀ M where support := l.support.map f.toEmbedding toFun a := l (f.symm a) mem_support_toFun a := by simp only [Finset.mem_map_equiv, mem_support_toFun]; rfl @[simp] theorem equivMapDomain_apply (f : α ≃ β) (l : α →₀ M) (b : β) : equivMapDomain f l b = l (f.symm b) := rfl theorem equivMapDomain_symm_apply (f : α ≃ β) (l : β →₀ M) (a : α) : equivMapDomain f.symm l a = l (f a) := rfl @[simp] theorem equivMapDomain_refl (l : α →₀ M) : equivMapDomain (Equiv.refl _) l = l := by ext x; rfl theorem equivMapDomain_refl' : equivMapDomain (Equiv.refl _) = @id (α →₀ M) := by ext x; rfl theorem equivMapDomain_trans (f : α ≃ β) (g : β ≃ γ) (l : α →₀ M) : equivMapDomain (f.trans g) l = equivMapDomain g (equivMapDomain f l) := by ext x; rfl theorem equivMapDomain_trans' (f : α ≃ β) (g : β ≃ γ) : @equivMapDomain _ _ M _ (f.trans g) = equivMapDomain g ∘ equivMapDomain f := by ext x; rfl @[simp] theorem equivMapDomain_single (f : α ≃ β) (a : α) (b : M) : equivMapDomain f (single a b) = single (f a) b := by classical ext x simp only [single_apply, Equiv.apply_eq_iff_eq_symm_apply, equivMapDomain_apply] @[simp] theorem equivMapDomain_zero {f : α ≃ β} : equivMapDomain f (0 : α →₀ M) = (0 : β →₀ M) := by ext; simp only [equivMapDomain_apply, coe_zero, Pi.zero_apply] @[to_additive (attr := simp)] theorem prod_equivMapDomain [CommMonoid N] (f : α ≃ β) (l : α →₀ M) (g : β → M → N) : prod (equivMapDomain f l) g = prod l (fun a m => g (f a) m) := by simp [prod, equivMapDomain] /-- Given `f : α ≃ β`, the finitely supported function spaces are also in bijection: `(α →₀ M) ≃ (β →₀ M)`. This is the finitely-supported version of `Equiv.piCongrLeft`. -/ def equivCongrLeft (f : α ≃ β) : (α →₀ M) ≃ (β →₀ M) := by refine ⟨equivMapDomain f, equivMapDomain f.symm, fun f => ?_, fun f => ?_⟩ <;> ext x <;> simp only [equivMapDomain_apply, Equiv.symm_symm, Equiv.symm_apply_apply, Equiv.apply_symm_apply] @[simp] theorem equivCongrLeft_apply (f : α ≃ β) (l : α →₀ M) : equivCongrLeft f l = equivMapDomain f l := rfl @[simp] theorem equivCongrLeft_symm (f : α ≃ β) : (@equivCongrLeft _ _ M _ f).symm = equivCongrLeft f.symm := rfl end Finsupp end EquivCongrLeft section CastFinsupp variable [Zero M] (f : α →₀ M) namespace Nat @[simp, norm_cast] theorem cast_finsupp_prod [CommSemiring R] (g : α → M → ℕ) : (↑(f.prod g) : R) = f.prod fun a b => ↑(g a b) := Nat.cast_prod _ _ @[simp, norm_cast] theorem cast_finsupp_sum [CommSemiring R] (g : α → M → ℕ) : (↑(f.sum g) : R) = f.sum fun a b => ↑(g a b) := Nat.cast_sum _ _ end Nat namespace Int @[simp, norm_cast] theorem cast_finsupp_prod [CommRing R] (g : α → M → ℤ) : (↑(f.prod g) : R) = f.prod fun a b => ↑(g a b) := Int.cast_prod _ _ @[simp, norm_cast] theorem cast_finsupp_sum [CommRing R] (g : α → M → ℤ) : (↑(f.sum g) : R) = f.sum fun a b => ↑(g a b) := Int.cast_sum _ _ end Int namespace Rat @[simp, norm_cast] theorem cast_finsupp_sum [DivisionRing R] [CharZero R] (g : α → M → ℚ) : (↑(f.sum g) : R) = f.sum fun a b => ↑(g a b) := cast_sum _ _ @[simp, norm_cast] theorem cast_finsupp_prod [Field R] [CharZero R] (g : α → M → ℚ) : (↑(f.prod g) : R) = f.prod fun a b => ↑(g a b) := cast_prod _ _ end Rat end CastFinsupp /-! ### Declarations about `mapDomain` -/ namespace Finsupp section MapDomain variable [AddCommMonoid M] {v v₁ v₂ : α →₀ M} /-- Given `f : α → β` and `v : α →₀ M`, `mapDomain f v : β →₀ M` is the finitely supported function whose value at `a : β` is the sum of `v x` over all `x` such that `f x = a`. -/ def mapDomain (f : α → β) (v : α →₀ M) : β →₀ M := v.sum fun a => single (f a) theorem mapDomain_apply {f : α → β} (hf : Function.Injective f) (x : α →₀ M) (a : α) : mapDomain f x (f a) = x a := by rw [mapDomain, sum_apply, sum_eq_single a, single_eq_same] · intro b _ hba exact single_eq_of_ne (hf.ne hba) · intro _ rw [single_zero, coe_zero, Pi.zero_apply] theorem mapDomain_notin_range {f : α → β} (x : α →₀ M) (a : β) (h : a ∉ Set.range f) : mapDomain f x a = 0 := by rw [mapDomain, sum_apply, sum] exact Finset.sum_eq_zero fun a' _ => single_eq_of_ne fun eq => h <| eq ▸ Set.mem_range_self _ @[simp] theorem mapDomain_id : mapDomain id v = v := sum_single _ theorem mapDomain_comp {f : α → β} {g : β → γ} : mapDomain (g ∘ f) v = mapDomain g (mapDomain f v) := by refine ((sum_sum_index ?_ ?_).trans ?_).symm · intro exact single_zero _ · intro exact single_add _ refine sum_congr fun _ _ => sum_single_index ?_ exact single_zero _ @[simp] theorem mapDomain_single {f : α → β} {a : α} {b : M} : mapDomain f (single a b) = single (f a) b := sum_single_index <| single_zero _ @[simp] theorem mapDomain_zero {f : α → β} : mapDomain f (0 : α →₀ M) = (0 : β →₀ M) := sum_zero_index theorem mapDomain_congr {f g : α → β} (h : ∀ x ∈ v.support, f x = g x) : v.mapDomain f = v.mapDomain g := Finset.sum_congr rfl fun _ H => by simp only [h _ H] theorem mapDomain_add {f : α → β} : mapDomain f (v₁ + v₂) = mapDomain f v₁ + mapDomain f v₂ := sum_add_index' (fun _ => single_zero _) fun _ => single_add _ @[simp] theorem mapDomain_equiv_apply {f : α ≃ β} (x : α →₀ M) (a : β) : mapDomain f x a = x (f.symm a) := by conv_lhs => rw [← f.apply_symm_apply a] exact mapDomain_apply f.injective _ _ /-- `Finsupp.mapDomain` is an `AddMonoidHom`. -/ @[simps] def mapDomain.addMonoidHom (f : α → β) : (α →₀ M) →+ β →₀ M where toFun := mapDomain f map_zero' := mapDomain_zero map_add' _ _ := mapDomain_add @[simp] theorem mapDomain.addMonoidHom_id : mapDomain.addMonoidHom id = AddMonoidHom.id (α →₀ M) := AddMonoidHom.ext fun _ => mapDomain_id theorem mapDomain.addMonoidHom_comp (f : β → γ) (g : α → β) : (mapDomain.addMonoidHom (f ∘ g) : (α →₀ M) →+ γ →₀ M) = (mapDomain.addMonoidHom f).comp (mapDomain.addMonoidHom g) := AddMonoidHom.ext fun _ => mapDomain_comp theorem mapDomain_finset_sum {f : α → β} {s : Finset ι} {v : ι → α →₀ M} : mapDomain f (∑ i ∈ s, v i) = ∑ i ∈ s, mapDomain f (v i) := map_sum (mapDomain.addMonoidHom f) _ _ theorem mapDomain_sum [Zero N] {f : α → β} {s : α →₀ N} {v : α → N → α →₀ M} : mapDomain f (s.sum v) = s.sum fun a b => mapDomain f (v a b) := map_finsupp_sum (mapDomain.addMonoidHom f : (α →₀ M) →+ β →₀ M) _ _ theorem mapDomain_support [DecidableEq β] {f : α → β} {s : α →₀ M} : (s.mapDomain f).support ⊆ s.support.image f := Finset.Subset.trans support_sum <| Finset.Subset.trans (Finset.biUnion_mono fun a _ => support_single_subset) <| by rw [Finset.biUnion_singleton] theorem mapDomain_apply' (S : Set α) {f : α → β} (x : α →₀ M) (hS : (x.support : Set α) ⊆ S) (hf : Set.InjOn f S) {a : α} (ha : a ∈ S) : mapDomain f x (f a) = x a := by classical rw [mapDomain, sum_apply, sum] simp_rw [single_apply] by_cases hax : a ∈ x.support · rw [← Finset.add_sum_erase _ _ hax, if_pos rfl] convert add_zero (x a) refine Finset.sum_eq_zero fun i hi => if_neg ?_ exact (hf.mono hS).ne (Finset.mem_of_mem_erase hi) hax (Finset.ne_of_mem_erase hi) · rw [not_mem_support_iff.1 hax] refine Finset.sum_eq_zero fun i hi => if_neg ?_ exact hf.ne (hS hi) ha (ne_of_mem_of_not_mem hi hax) theorem mapDomain_support_of_injOn [DecidableEq β] {f : α → β} (s : α →₀ M) (hf : Set.InjOn f s.support) : (mapDomain f s).support = Finset.image f s.support := Finset.Subset.antisymm mapDomain_support <| by intro x hx simp only [mem_image, exists_prop, mem_support_iff, Ne] at hx rcases hx with ⟨hx_w, hx_h_left, rfl⟩ simp only [mem_support_iff, Ne] rw [mapDomain_apply' (↑s.support : Set _) _ _ hf] · exact hx_h_left · simp only [mem_coe, mem_support_iff, Ne] exact hx_h_left · exact Subset.refl _ theorem mapDomain_support_of_injective [DecidableEq β] {f : α → β} (hf : Function.Injective f) (s : α →₀ M) : (mapDomain f s).support = Finset.image f s.support := mapDomain_support_of_injOn s hf.injOn @[to_additive] theorem prod_mapDomain_index [CommMonoid N] {f : α → β} {s : α →₀ M} {h : β → M → N} (h_zero : ∀ b, h b 0 = 1) (h_add : ∀ b m₁ m₂, h b (m₁ + m₂) = h b m₁ * h b m₂) : (mapDomain f s).prod h = s.prod fun a m => h (f a) m := (prod_sum_index h_zero h_add).trans <| prod_congr fun _ _ => prod_single_index (h_zero _) -- Note that in `prod_mapDomain_index`, `M` is still an additive monoid, -- so there is no analogous version in terms of `MonoidHom`. /-- A version of `sum_mapDomain_index` that takes a bundled `AddMonoidHom`, rather than separate linearity hypotheses. -/ @[simp] theorem sum_mapDomain_index_addMonoidHom [AddCommMonoid N] {f : α → β} {s : α →₀ M} (h : β → M →+ N) : ((mapDomain f s).sum fun b m => h b m) = s.sum fun a m => h (f a) m := sum_mapDomain_index (fun b => (h b).map_zero) (fun b _ _ => (h b).map_add _ _) theorem embDomain_eq_mapDomain (f : α ↪ β) (v : α →₀ M) : embDomain f v = mapDomain f v := by ext a by_cases h : a ∈ Set.range f · rcases h with ⟨a, rfl⟩ rw [mapDomain_apply f.injective, embDomain_apply] · rw [mapDomain_notin_range, embDomain_notin_range] <;> assumption @[to_additive] theorem prod_mapDomain_index_inj [CommMonoid N] {f : α → β} {s : α →₀ M} {h : β → M → N} (hf : Function.Injective f) : (s.mapDomain f).prod h = s.prod fun a b => h (f a) b := by rw [← Function.Embedding.coeFn_mk f hf, ← embDomain_eq_mapDomain, prod_embDomain] theorem mapDomain_injective {f : α → β} (hf : Function.Injective f) : Function.Injective (mapDomain f : (α →₀ M) → β →₀ M) := by intro v₁ v₂ eq ext a have : mapDomain f v₁ (f a) = mapDomain f v₂ (f a) := by rw [eq] rwa [mapDomain_apply hf, mapDomain_apply hf] at this /-- When `f` is an embedding we have an embedding `(α →₀ ℕ) ↪ (β →₀ ℕ)` given by `mapDomain`. -/ @[simps] def mapDomainEmbedding {α β : Type*} (f : α ↪ β) : (α →₀ ℕ) ↪ β →₀ ℕ := ⟨Finsupp.mapDomain f, Finsupp.mapDomain_injective f.injective⟩ theorem mapDomain.addMonoidHom_comp_mapRange [AddCommMonoid N] (f : α → β) (g : M →+ N) : (mapDomain.addMonoidHom f).comp (mapRange.addMonoidHom g) = (mapRange.addMonoidHom g).comp (mapDomain.addMonoidHom f) := by ext simp only [AddMonoidHom.coe_comp, Finsupp.mapRange_single, Finsupp.mapDomain.addMonoidHom_apply, Finsupp.singleAddHom_apply, eq_self_iff_true, Function.comp_apply, Finsupp.mapDomain_single, Finsupp.mapRange.addMonoidHom_apply] /-- When `g` preserves addition, `mapRange` and `mapDomain` commute. -/ theorem mapDomain_mapRange [AddCommMonoid N] (f : α → β) (v : α →₀ M) (g : M → N) (h0 : g 0 = 0) (hadd : ∀ x y, g (x + y) = g x + g y) : mapDomain f (mapRange g h0 v) = mapRange g h0 (mapDomain f v) := let g' : M →+ N := { toFun := g map_zero' := h0 map_add' := hadd } DFunLike.congr_fun (mapDomain.addMonoidHom_comp_mapRange f g') v theorem sum_update_add [AddCommMonoid α] [AddCommMonoid β] (f : ι →₀ α) (i : ι) (a : α) (g : ι → α → β) (hg : ∀ i, g i 0 = 0) (hgg : ∀ (j : ι) (a₁ a₂ : α), g j (a₁ + a₂) = g j a₁ + g j a₂) : (f.update i a).sum g + g i (f i) = f.sum g + g i a := by rw [update_eq_erase_add_single, sum_add_index' hg hgg] conv_rhs => rw [← Finsupp.update_self f i] rw [update_eq_erase_add_single, sum_add_index' hg hgg, add_assoc, add_assoc] congr 1 rw [add_comm, sum_single_index (hg _), sum_single_index (hg _)] theorem mapDomain_injOn (S : Set α) {f : α → β} (hf : Set.InjOn f S) : Set.InjOn (mapDomain f : (α →₀ M) → β →₀ M) { w | (w.support : Set α) ⊆ S } := by intro v₁ hv₁ v₂ hv₂ eq ext a classical by_cases h : a ∈ v₁.support ∪ v₂.support · rw [← mapDomain_apply' S _ hv₁ hf _, ← mapDomain_apply' S _ hv₂ hf _, eq] <;> · apply Set.union_subset hv₁ hv₂ exact mod_cast h · simp only [not_or, mem_union, not_not, mem_support_iff] at h simp [h] theorem equivMapDomain_eq_mapDomain {M} [AddCommMonoid M] (f : α ≃ β) (l : α →₀ M) : equivMapDomain f l = mapDomain f l := by ext x; simp [mapDomain_equiv_apply] end MapDomain /-! ### Declarations about `comapDomain` -/ section ComapDomain /-- Given `f : α → β`, `l : β →₀ M` and a proof `hf` that `f` is injective on the preimage of `l.support`, `comapDomain f l hf` is the finitely supported function from `α` to `M` given by composing `l` with `f`. -/ @[simps support] def comapDomain [Zero M] (f : α → β) (l : β →₀ M) (hf : Set.InjOn f (f ⁻¹' ↑l.support)) : α →₀ M where support := l.support.preimage f hf toFun a := l (f a) mem_support_toFun := by intro a simp only [Finset.mem_def.symm, Finset.mem_preimage] exact l.mem_support_toFun (f a) @[simp] theorem comapDomain_apply [Zero M] (f : α → β) (l : β →₀ M) (hf : Set.InjOn f (f ⁻¹' ↑l.support)) (a : α) : comapDomain f l hf a = l (f a) := rfl theorem sum_comapDomain [Zero M] [AddCommMonoid N] (f : α → β) (l : β →₀ M) (g : β → M → N) (hf : Set.BijOn f (f ⁻¹' ↑l.support) ↑l.support) : (comapDomain f l hf.injOn).sum (g ∘ f) = l.sum g := by simp only [sum, comapDomain_apply, (· ∘ ·), comapDomain] exact Finset.sum_preimage_of_bij f _ hf fun x => g x (l x) theorem eq_zero_of_comapDomain_eq_zero [AddCommMonoid M] (f : α → β) (l : β →₀ M) (hf : Set.BijOn f (f ⁻¹' ↑l.support) ↑l.support) : comapDomain f l hf.injOn = 0 → l = 0 := by rw [← support_eq_empty, ← support_eq_empty, comapDomain] simp only [Finset.ext_iff, Finset.not_mem_empty, iff_false_iff, mem_preimage] intro h a ha cases' hf.2.2 ha with b hb exact h b (hb.2.symm ▸ ha) section FInjective section Zero variable [Zero M] lemma embDomain_comapDomain {f : α ↪ β} {g : β →₀ M} (hg : ↑g.support ⊆ Set.range f) : embDomain f (comapDomain f g f.injective.injOn) = g := by ext b by_cases hb : b ∈ Set.range f · obtain ⟨a, rfl⟩ := hb rw [embDomain_apply, comapDomain_apply] · replace hg : g b = 0 := not_mem_support_iff.mp <| mt (hg ·) hb rw [embDomain_notin_range _ _ _ hb, hg] /-- Note the `hif` argument is needed for this to work in `rw`. -/ @[simp] theorem comapDomain_zero (f : α → β) (hif : Set.InjOn f (f ⁻¹' ↑(0 : β →₀ M).support) := Finset.coe_empty ▸ (Set.injOn_empty f)) : comapDomain f (0 : β →₀ M) hif = (0 : α →₀ M) := by ext rfl @[simp] theorem comapDomain_single (f : α → β) (a : α) (m : M) (hif : Set.InjOn f (f ⁻¹' (single (f a) m).support)) : comapDomain f (Finsupp.single (f a) m) hif = Finsupp.single a m := by rcases eq_or_ne m 0 with (rfl | hm) · simp only [single_zero, comapDomain_zero] · rw [eq_single_iff, comapDomain_apply, comapDomain_support, ← Finset.coe_subset, coe_preimage, support_single_ne_zero _ hm, coe_singleton, coe_singleton, single_eq_same] rw [support_single_ne_zero _ hm, coe_singleton] at hif exact ⟨fun x hx => hif hx rfl hx, rfl⟩ end Zero section AddZeroClass variable [AddZeroClass M] {f : α → β} theorem comapDomain_add (v₁ v₂ : β →₀ M) (hv₁ : Set.InjOn f (f ⁻¹' ↑v₁.support)) (hv₂ : Set.InjOn f (f ⁻¹' ↑v₂.support)) (hv₁₂ : Set.InjOn f (f ⁻¹' ↑(v₁ + v₂).support)) : comapDomain f (v₁ + v₂) hv₁₂ = comapDomain f v₁ hv₁ + comapDomain f v₂ hv₂ := by ext simp only [comapDomain_apply, coe_add, Pi.add_apply] /-- A version of `Finsupp.comapDomain_add` that's easier to use. -/ theorem comapDomain_add_of_injective (hf : Function.Injective f) (v₁ v₂ : β →₀ M) : comapDomain f (v₁ + v₂) hf.injOn = comapDomain f v₁ hf.injOn + comapDomain f v₂ hf.injOn := comapDomain_add _ _ _ _ _ /-- `Finsupp.comapDomain` is an `AddMonoidHom`. -/ @[simps] def comapDomain.addMonoidHom (hf : Function.Injective f) : (β →₀ M) →+ α →₀ M where toFun x := comapDomain f x hf.injOn map_zero' := comapDomain_zero f map_add' := comapDomain_add_of_injective hf end AddZeroClass variable [AddCommMonoid M] (f : α → β) theorem mapDomain_comapDomain (hf : Function.Injective f) (l : β →₀ M) (hl : ↑l.support ⊆ Set.range f) : mapDomain f (comapDomain f l hf.injOn) = l := by conv_rhs => rw [← embDomain_comapDomain (f := ⟨f, hf⟩) hl (M := M), embDomain_eq_mapDomain] rfl end FInjective end ComapDomain /-! ### Declarations about finitely supported functions whose support is an `Option` type -/ section Option /-- Restrict a finitely supported function on `Option α` to a finitely supported function on `α`. -/ def some [Zero M] (f : Option α →₀ M) : α →₀ M := f.comapDomain Option.some fun _ => by simp @[simp] theorem some_apply [Zero M] (f : Option α →₀ M) (a : α) : f.some a = f (Option.some a) := rfl @[simp] theorem some_zero [Zero M] : (0 : Option α →₀ M).some = 0 := by ext simp @[simp] theorem some_add [AddCommMonoid M] (f g : Option α →₀ M) : (f + g).some = f.some + g.some := by ext simp @[simp] theorem some_single_none [Zero M] (m : M) : (single none m : Option α →₀ M).some = 0 := by ext simp @[simp] theorem some_single_some [Zero M] (a : α) (m : M) : (single (Option.some a) m : Option α →₀ M).some = single a m := by classical ext b simp [single_apply] @[to_additive] theorem prod_option_index [AddCommMonoid M] [CommMonoid N] (f : Option α →₀ M) (b : Option α → M → N) (h_zero : ∀ o, b o 0 = 1) (h_add : ∀ o m₁ m₂, b o (m₁ + m₂) = b o m₁ * b o m₂) : f.prod b = b none (f none) * f.some.prod fun a => b (Option.some a) := by classical apply induction_linear f · simp [some_zero, h_zero] · intro f₁ f₂ h₁ h₂ rw [Finsupp.prod_add_index, h₁, h₂, some_add, Finsupp.prod_add_index] · simp only [h_add, Pi.add_apply, Finsupp.coe_add] rw [mul_mul_mul_comm] all_goals simp [h_zero, h_add] · rintro (_ | a) m <;> simp [h_zero, h_add] theorem sum_option_index_smul [Semiring R] [AddCommMonoid M] [Module R M] (f : Option α →₀ R) (b : Option α → M) : (f.sum fun o r => r • b o) = f none • b none + f.some.sum fun a r => r • b (Option.some a) := f.sum_option_index _ (fun _ => zero_smul _ _) fun _ _ _ => add_smul _ _ _ end Option /-! ### Declarations about `Finsupp.filter` -/ section Filter section Zero variable [Zero M] (p : α → Prop) [DecidablePred p] (f : α →₀ M) /-- `Finsupp.filter p f` is the finitely supported function that is `f a` if `p a` is true and `0` otherwise. -/ def filter (p : α → Prop) [DecidablePred p] (f : α →₀ M) : α →₀ M where toFun a := if p a then f a else 0 support := f.support.filter p mem_support_toFun a := by beta_reduce -- Porting note(#12129): additional beta reduction needed to activate `split_ifs` split_ifs with h <;> · simp only [h, mem_filter, mem_support_iff] tauto theorem filter_apply (a : α) : f.filter p a = if p a then f a else 0 := rfl theorem filter_eq_indicator : ⇑(f.filter p) = Set.indicator { x | p x } f := by ext simp [filter_apply, Set.indicator_apply] theorem filter_eq_zero_iff : f.filter p = 0 ↔ ∀ x, p x → f x = 0 := by simp only [DFunLike.ext_iff, filter_eq_indicator, zero_apply, Set.indicator_apply_eq_zero, Set.mem_setOf_eq] theorem filter_eq_self_iff : f.filter p = f ↔ ∀ x, f x ≠ 0 → p x := by simp only [DFunLike.ext_iff, filter_eq_indicator, Set.indicator_apply_eq_self, Set.mem_setOf_eq, not_imp_comm] @[simp] theorem filter_apply_pos {a : α} (h : p a) : f.filter p a = f a := if_pos h @[simp] theorem filter_apply_neg {a : α} (h : ¬p a) : f.filter p a = 0 := if_neg h @[simp] theorem support_filter : (f.filter p).support = f.support.filter p := rfl theorem filter_zero : (0 : α →₀ M).filter p = 0 := by classical rw [← support_eq_empty, support_filter, support_zero, Finset.filter_empty] @[simp] theorem filter_single_of_pos {a : α} {b : M} (h : p a) : (single a b).filter p = single a b := (filter_eq_self_iff _ _).2 fun _ hx => (single_apply_ne_zero.1 hx).1.symm ▸ h @[simp] theorem filter_single_of_neg {a : α} {b : M} (h : ¬p a) : (single a b).filter p = 0 := (filter_eq_zero_iff _ _).2 fun _ hpx => single_apply_eq_zero.2 fun hxa => absurd hpx (hxa.symm ▸ h) @[to_additive] theorem prod_filter_index [CommMonoid N] (g : α → M → N) : (f.filter p).prod g = ∏ x ∈ (f.filter p).support, g x (f x) := by classical refine Finset.prod_congr rfl fun x hx => ?_ rw [support_filter, Finset.mem_filter] at hx rw [filter_apply_pos _ _ hx.2] @[to_additive (attr := simp)] theorem prod_filter_mul_prod_filter_not [CommMonoid N] (g : α → M → N) : (f.filter p).prod g * (f.filter fun a => ¬p a).prod g = f.prod g := by classical simp_rw [prod_filter_index, support_filter, Finset.prod_filter_mul_prod_filter_not, Finsupp.prod] @[to_additive (attr := simp)] theorem prod_div_prod_filter [CommGroup G] (g : α → M → G) : f.prod g / (f.filter p).prod g = (f.filter fun a => ¬p a).prod g := div_eq_of_eq_mul' (prod_filter_mul_prod_filter_not _ _ _).symm end Zero theorem filter_pos_add_filter_neg [AddZeroClass M] (f : α →₀ M) (p : α → Prop) [DecidablePred p] : (f.filter p + f.filter fun a => ¬p a) = f := DFunLike.coe_injective <| by simp only [coe_add, filter_eq_indicator] exact Set.indicator_self_add_compl { x | p x } f end Filter /-! ### Declarations about `frange` -/ section Frange variable [Zero M] /-- `frange f` is the image of `f` on the support of `f`. -/ def frange (f : α →₀ M) : Finset M := haveI := Classical.decEq M Finset.image f f.support theorem mem_frange {f : α →₀ M} {y : M} : y ∈ f.frange ↔ y ≠ 0 ∧ ∃ x, f x = y := by rw [frange, @Finset.mem_image _ _ (Classical.decEq _) _ f.support] exact ⟨fun ⟨x, hx1, hx2⟩ => ⟨hx2 ▸ mem_support_iff.1 hx1, x, hx2⟩, fun ⟨hy, x, hx⟩ => ⟨x, mem_support_iff.2 (hx.symm ▸ hy), hx⟩⟩ -- Porting note: maybe there is a better way to fix this, but (1) it wasn't seeing past `frange` -- the definition, and (2) it needed the `Classical.decEq` instance again. theorem zero_not_mem_frange {f : α →₀ M} : (0 : M) ∉ f.frange := fun H => (mem_frange.1 H).1 rfl theorem frange_single {x : α} {y : M} : frange (single x y) ⊆ {y} := fun r hr => let ⟨t, ht1, ht2⟩ := mem_frange.1 hr ht2 ▸ by classical rw [single_apply] at ht2 ⊢ split_ifs at ht2 ⊢ · exact Finset.mem_singleton_self _ · exact (t ht2.symm).elim end Frange /-! ### Declarations about `Finsupp.subtypeDomain` -/ section SubtypeDomain section Zero variable [Zero M] {p : α → Prop} /-- `subtypeDomain p f` is the restriction of the finitely supported function `f` to subtype `p`. -/ def subtypeDomain (p : α → Prop) (f : α →₀ M) : Subtype p →₀ M where support := haveI := Classical.decPred p f.support.subtype p toFun := f ∘ Subtype.val mem_support_toFun a := by simp only [@mem_subtype _ _ (Classical.decPred p), mem_support_iff]; rfl @[simp] theorem support_subtypeDomain [D : DecidablePred p] {f : α →₀ M} : (subtypeDomain p f).support = f.support.subtype p := by rw [Subsingleton.elim D] <;> rfl @[simp] theorem subtypeDomain_apply {a : Subtype p} {v : α →₀ M} : (subtypeDomain p v) a = v a.val := rfl @[simp] theorem subtypeDomain_zero : subtypeDomain p (0 : α →₀ M) = 0 := rfl theorem subtypeDomain_eq_zero_iff' {f : α →₀ M} : f.subtypeDomain p = 0 ↔ ∀ x, p x → f x = 0 := by classical simp_rw [← support_eq_empty, support_subtypeDomain, subtype_eq_empty, not_mem_support_iff] theorem subtypeDomain_eq_zero_iff {f : α →₀ M} (hf : ∀ x ∈ f.support, p x) : f.subtypeDomain p = 0 ↔ f = 0 := subtypeDomain_eq_zero_iff'.trans ⟨fun H => ext fun x => by classical exact if hx : p x then H x hx else not_mem_support_iff.1 <| mt (hf x) hx, fun H x _ => by simp [H]⟩ @[to_additive] theorem prod_subtypeDomain_index [CommMonoid N] {v : α →₀ M} {h : α → M → N} (hp : ∀ x ∈ v.support, p x) : (v.subtypeDomain p).prod (fun a b ↦ h a b) = v.prod h := by refine Finset.prod_bij (fun p _ ↦ p) ?_ ?_ ?_ ?_ <;> aesop end Zero section AddZeroClass variable [AddZeroClass M] {p : α → Prop} {v v' : α →₀ M} @[simp] theorem subtypeDomain_add {v v' : α →₀ M} : (v + v').subtypeDomain p = v.subtypeDomain p + v'.subtypeDomain p := ext fun _ => rfl /-- `subtypeDomain` but as an `AddMonoidHom`. -/ def subtypeDomainAddMonoidHom : (α →₀ M) →+ Subtype p →₀ M where toFun := subtypeDomain p map_zero' := subtypeDomain_zero map_add' _ _ := subtypeDomain_add /-- `Finsupp.filter` as an `AddMonoidHom`. -/ def filterAddHom (p : α → Prop) [DecidablePred p] : (α →₀ M) →+ α →₀ M where toFun := filter p map_zero' := filter_zero p map_add' f g := DFunLike.coe_injective <| by simp only [filter_eq_indicator, coe_add] exact Set.indicator_add { x | p x } f g @[simp] theorem filter_add [DecidablePred p] {v v' : α →₀ M} : (v + v').filter p = v.filter p + v'.filter p := (filterAddHom p).map_add v v' end AddZeroClass section CommMonoid variable [AddCommMonoid M] {p : α → Prop} theorem subtypeDomain_sum {s : Finset ι} {h : ι → α →₀ M} : (∑ c ∈ s, h c).subtypeDomain p = ∑ c ∈ s, (h c).subtypeDomain p := map_sum subtypeDomainAddMonoidHom _ s theorem subtypeDomain_finsupp_sum [Zero N] {s : β →₀ N} {h : β → N → α →₀ M} : (s.sum h).subtypeDomain p = s.sum fun c d => (h c d).subtypeDomain p := subtypeDomain_sum theorem filter_sum [DecidablePred p] (s : Finset ι) (f : ι → α →₀ M) : (∑ a ∈ s, f a).filter p = ∑ a ∈ s, filter p (f a) := map_sum (filterAddHom p) f s theorem filter_eq_sum (p : α → Prop) [DecidablePred p] (f : α →₀ M) : f.filter p = ∑ i ∈ f.support.filter p, single i (f i) := (f.filter p).sum_single.symm.trans <| Finset.sum_congr rfl fun x hx => by rw [filter_apply_pos _ _ (mem_filter.1 hx).2] end CommMonoid section Group variable [AddGroup G] {p : α → Prop} {v v' : α →₀ G} @[simp] theorem subtypeDomain_neg : (-v).subtypeDomain p = -v.subtypeDomain p := ext fun _ => rfl @[simp] theorem subtypeDomain_sub : (v - v').subtypeDomain p = v.subtypeDomain p - v'.subtypeDomain p := ext fun _ => rfl @[simp] theorem single_neg (a : α) (b : G) : single a (-b) = -single a b := (singleAddHom a : G →+ _).map_neg b @[simp] theorem single_sub (a : α) (b₁ b₂ : G) : single a (b₁ - b₂) = single a b₁ - single a b₂ := (singleAddHom a : G →+ _).map_sub b₁ b₂ @[simp] theorem erase_neg (a : α) (f : α →₀ G) : erase a (-f) = -erase a f := (eraseAddHom a : (_ →₀ G) →+ _).map_neg f @[simp] theorem erase_sub (a : α) (f₁ f₂ : α →₀ G) : erase a (f₁ - f₂) = erase a f₁ - erase a f₂ := (eraseAddHom a : (_ →₀ G) →+ _).map_sub f₁ f₂ @[simp] theorem filter_neg (p : α → Prop) [DecidablePred p] (f : α →₀ G) : filter p (-f) = -filter p f := (filterAddHom p : (_ →₀ G) →+ _).map_neg f @[simp] theorem filter_sub (p : α → Prop) [DecidablePred p] (f₁ f₂ : α →₀ G) : filter p (f₁ - f₂) = filter p f₁ - filter p f₂ := (filterAddHom p : (_ →₀ G) →+ _).map_sub f₁ f₂ end Group end SubtypeDomain theorem mem_support_multiset_sum [AddCommMonoid M] {s : Multiset (α →₀ M)} (a : α) : a ∈ s.sum.support → ∃ f ∈ s, a ∈ (f : α →₀ M).support := Multiset.induction_on s (fun h => False.elim (by simp at h)) (by intro f s ih ha by_cases h : a ∈ f.support · exact ⟨f, Multiset.mem_cons_self _ _, h⟩ · simp only [Multiset.sum_cons, mem_support_iff, add_apply, not_mem_support_iff.1 h, zero_add] at ha rcases ih (mem_support_iff.2 ha) with ⟨f', h₀, h₁⟩ exact ⟨f', Multiset.mem_cons_of_mem h₀, h₁⟩) theorem mem_support_finset_sum [AddCommMonoid M] {s : Finset ι} {h : ι → α →₀ M} (a : α) (ha : a ∈ (∑ c ∈ s, h c).support) : ∃ c ∈ s, a ∈ (h c).support := let ⟨_, hf, hfa⟩ := mem_support_multiset_sum a ha let ⟨c, hc, Eq⟩ := Multiset.mem_map.1 hf ⟨c, hc, Eq.symm ▸ hfa⟩ /-! ### Declarations about `curry` and `uncurry` -/ section CurryUncurry variable [AddCommMonoid M] [AddCommMonoid N] /-- Given a finitely supported function `f` from a product type `α × β` to `γ`, `curry f` is the "curried" finitely supported function from `α` to the type of finitely supported functions from `β` to `γ`. -/ protected def curry (f : α × β →₀ M) : α →₀ β →₀ M := f.sum fun p c => single p.1 (single p.2 c) @[simp] theorem curry_apply (f : α × β →₀ M) (x : α) (y : β) : f.curry x y = f (x, y) := by classical have : ∀ b : α × β, single b.fst (single b.snd (f b)) x y = if b = (x, y) then f b else 0 := by rintro ⟨b₁, b₂⟩ simp only [ne_eq, single_apply, Prod.ext_iff, ite_and] split_ifs <;> simp [single_apply, *] rw [Finsupp.curry, sum_apply, sum_apply, sum_eq_single, this, if_pos rfl] · intro b _ b_ne rw [this b, if_neg b_ne] · intro _ rw [single_zero, single_zero, coe_zero, Pi.zero_apply, coe_zero, Pi.zero_apply] theorem sum_curry_index (f : α × β →₀ M) (g : α → β → M → N) (hg₀ : ∀ a b, g a b 0 = 0) (hg₁ : ∀ a b c₀ c₁, g a b (c₀ + c₁) = g a b c₀ + g a b c₁) : (f.curry.sum fun a f => f.sum (g a)) = f.sum fun p c => g p.1 p.2 c := by rw [Finsupp.curry] trans · exact sum_sum_index (fun a => sum_zero_index) fun a b₀ b₁ => sum_add_index' (fun a => hg₀ _ _) fun c d₀ d₁ => hg₁ _ _ _ _ congr; funext p c trans · exact sum_single_index sum_zero_index exact sum_single_index (hg₀ _ _) /-- Given a finitely supported function `f` from `α` to the type of finitely supported functions from `β` to `M`, `uncurry f` is the "uncurried" finitely supported function from `α × β` to `M`. -/ protected def uncurry (f : α →₀ β →₀ M) : α × β →₀ M := f.sum fun a g => g.sum fun b c => single (a, b) c /-- `finsuppProdEquiv` defines the `Equiv` between `((α × β) →₀ M)` and `(α →₀ (β →₀ M))` given by currying and uncurrying. -/ def finsuppProdEquiv : (α × β →₀ M) ≃ (α →₀ β →₀ M) where toFun := Finsupp.curry invFun := Finsupp.uncurry left_inv f := by rw [Finsupp.uncurry, sum_curry_index] · simp_rw [Prod.mk.eta, sum_single] · intros apply single_zero · intros apply single_add right_inv f := by simp only [Finsupp.curry, Finsupp.uncurry, sum_sum_index, sum_zero_index, sum_add_index, sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall₃_true_iff, (single_sum _ _ _).symm, sum_single] theorem filter_curry (f : α × β →₀ M) (p : α → Prop) [DecidablePred p] : (f.filter fun a : α × β => p a.1).curry = f.curry.filter p := by classical rw [Finsupp.curry, Finsupp.curry, Finsupp.sum, Finsupp.sum, filter_sum, support_filter, sum_filter] refine Finset.sum_congr rfl ?_ rintro ⟨a₁, a₂⟩ _ split_ifs with h · rw [filter_apply_pos, filter_single_of_pos] <;> exact h · rwa [filter_single_of_neg] theorem support_curry [DecidableEq α] (f : α × β →₀ M) : f.curry.support ⊆ f.support.image Prod.fst := by rw [← Finset.biUnion_singleton] refine Finset.Subset.trans support_sum ?_ exact Finset.biUnion_mono fun a _ => support_single_subset end CurryUncurry /-! ### Declarations about finitely supported functions whose support is a `Sum` type -/ section Sum /-- `Finsupp.sumElim f g` maps `inl x` to `f x` and `inr y` to `g y`. -/ def sumElim {α β γ : Type*} [Zero γ] (f : α →₀ γ) (g : β →₀ γ) : α ⊕ β →₀ γ := onFinset (by haveI := Classical.decEq α haveI := Classical.decEq β exact f.support.map ⟨_, Sum.inl_injective⟩ ∪ g.support.map ⟨_, Sum.inr_injective⟩) (Sum.elim f g) fun ab h => by cases' ab with a b <;> letI := Classical.decEq α <;> letI := Classical.decEq β <;> -- porting note (#10754): had to add these `DecidableEq` instances simp only [Sum.elim_inl, Sum.elim_inr] at h <;> simpa @[simp, norm_cast] theorem coe_sumElim {α β γ : Type*} [Zero γ] (f : α →₀ γ) (g : β →₀ γ) : ⇑(sumElim f g) = Sum.elim f g := rfl theorem sumElim_apply {α β γ : Type*} [Zero γ] (f : α →₀ γ) (g : β →₀ γ) (x : α ⊕ β) : sumElim f g x = Sum.elim f g x := rfl theorem sumElim_inl {α β γ : Type*} [Zero γ] (f : α →₀ γ) (g : β →₀ γ) (x : α) : sumElim f g (Sum.inl x) = f x := rfl theorem sumElim_inr {α β γ : Type*} [Zero γ] (f : α →₀ γ) (g : β →₀ γ) (x : β) : sumElim f g (Sum.inr x) = g x := rfl /-- The equivalence between `(α ⊕ β) →₀ γ` and `(α →₀ γ) × (β →₀ γ)`. This is the `Finsupp` version of `Equiv.sum_arrow_equiv_prod_arrow`. -/ @[simps apply symm_apply] def sumFinsuppEquivProdFinsupp {α β γ : Type*} [Zero γ] : (α ⊕ β →₀ γ) ≃ (α →₀ γ) × (β →₀ γ) where toFun f := ⟨f.comapDomain Sum.inl Sum.inl_injective.injOn, f.comapDomain Sum.inr Sum.inr_injective.injOn⟩ invFun fg := sumElim fg.1 fg.2 left_inv f := by ext ab cases' ab with a b <;> simp right_inv fg := by ext <;> simp theorem fst_sumFinsuppEquivProdFinsupp {α β γ : Type*} [Zero γ] (f : α ⊕ β →₀ γ) (x : α) : (sumFinsuppEquivProdFinsupp f).1 x = f (Sum.inl x) := rfl theorem snd_sumFinsuppEquivProdFinsupp {α β γ : Type*} [Zero γ] (f : α ⊕ β →₀ γ) (y : β) : (sumFinsuppEquivProdFinsupp f).2 y = f (Sum.inr y) := rfl theorem sumFinsuppEquivProdFinsupp_symm_inl {α β γ : Type*} [Zero γ] (fg : (α →₀ γ) × (β →₀ γ)) (x : α) : (sumFinsuppEquivProdFinsupp.symm fg) (Sum.inl x) = fg.1 x := rfl theorem sumFinsuppEquivProdFinsupp_symm_inr {α β γ : Type*} [Zero γ] (fg : (α →₀ γ) × (β →₀ γ)) (y : β) : (sumFinsuppEquivProdFinsupp.symm fg) (Sum.inr y) = fg.2 y := rfl variable [AddMonoid M] /-- The additive equivalence between `(α ⊕ β) →₀ M` and `(α →₀ M) × (β →₀ M)`. This is the `Finsupp` version of `Equiv.sum_arrow_equiv_prod_arrow`. -/ @[simps! apply symm_apply] def sumFinsuppAddEquivProdFinsupp {α β : Type*} : (α ⊕ β →₀ M) ≃+ (α →₀ M) × (β →₀ M) := { sumFinsuppEquivProdFinsupp with map_add' := by intros ext <;> simp only [Equiv.toFun_as_coe, Prod.fst_add, Prod.snd_add, add_apply, snd_sumFinsuppEquivProdFinsupp, fst_sumFinsuppEquivProdFinsupp] } theorem fst_sumFinsuppAddEquivProdFinsupp {α β : Type*} (f : α ⊕ β →₀ M) (x : α) : (sumFinsuppAddEquivProdFinsupp f).1 x = f (Sum.inl x) := rfl theorem snd_sumFinsuppAddEquivProdFinsupp {α β : Type*} (f : α ⊕ β →₀ M) (y : β) : (sumFinsuppAddEquivProdFinsupp f).2 y = f (Sum.inr y) := rfl theorem sumFinsuppAddEquivProdFinsupp_symm_inl {α β : Type*} (fg : (α →₀ M) × (β →₀ M)) (x : α) : (sumFinsuppAddEquivProdFinsupp.symm fg) (Sum.inl x) = fg.1 x := rfl theorem sumFinsuppAddEquivProdFinsupp_symm_inr {α β : Type*} (fg : (α →₀ M) × (β →₀ M)) (y : β) : (sumFinsuppAddEquivProdFinsupp.symm fg) (Sum.inr y) = fg.2 y := rfl end Sum /-! ### Declarations about scalar multiplication -/ section variable [Zero M] [MonoidWithZero R] [MulActionWithZero R M] @[simp, nolint simpNF] -- `simpNF` incorrectly complains the LHS doesn't simplify. theorem single_smul (a b : α) (f : α → M) (r : R) : single a r b • f a = single a (r • f b) b := by by_cases h : a = b <;> simp [h] end section variable [Monoid G] [MulAction G α] [AddCommMonoid M] /-- Scalar multiplication acting on the domain. This is not an instance as it would conflict with the action on the range. See the `instance_diamonds` test for examples of such conflicts. -/ def comapSMul : SMul G (α →₀ M) where smul g := mapDomain (g • ·) attribute [local instance] comapSMul theorem comapSMul_def (g : G) (f : α →₀ M) : g • f = mapDomain (g • ·) f := rfl @[simp] theorem comapSMul_single (g : G) (a : α) (b : M) : g • single a b = single (g • a) b := mapDomain_single /-- `Finsupp.comapSMul` is multiplicative -/ def comapMulAction : MulAction G (α →₀ M) where one_smul f := by rw [comapSMul_def, one_smul_eq_id, mapDomain_id] mul_smul g g' f := by rw [comapSMul_def, comapSMul_def, comapSMul_def, ← comp_smul_left, mapDomain_comp] attribute [local instance] comapMulAction /-- `Finsupp.comapSMul` is distributive -/ def comapDistribMulAction : DistribMulAction G (α →₀ M) where smul_zero g := by ext a simp only [comapSMul_def] simp smul_add g f f' := by ext simp only [comapSMul_def] simp [mapDomain_add] end section variable [Group G] [MulAction G α] [AddCommMonoid M] attribute [local instance] comapSMul comapMulAction comapDistribMulAction /-- When `G` is a group, `Finsupp.comapSMul` acts by precomposition with the action of `g⁻¹`. -/ @[simp] theorem comapSMul_apply (g : G) (f : α →₀ M) (a : α) : (g • f) a = f (g⁻¹ • a) := by conv_lhs => rw [← smul_inv_smul g a] exact mapDomain_apply (MulAction.injective g) _ (g⁻¹ • a) end section instance smulZeroClass [Zero M] [SMulZeroClass R M] : SMulZeroClass R (α →₀ M) where smul a v := v.mapRange (a • ·) (smul_zero _) smul_zero a := by ext apply smul_zero /-! Throughout this section, some `Monoid` and `Semiring` arguments are specified with `{}` instead of `[]`. See note [implicit instance arguments]. -/ @[simp, norm_cast] theorem coe_smul [Zero M] [SMulZeroClass R M] (b : R) (v : α →₀ M) : ⇑(b • v) = b • ⇑v := rfl theorem smul_apply [Zero M] [SMulZeroClass R M] (b : R) (v : α →₀ M) (a : α) : (b • v) a = b • v a := rfl theorem _root_.IsSMulRegular.finsupp [Zero M] [SMulZeroClass R M] {k : R} (hk : IsSMulRegular M k) : IsSMulRegular (α →₀ M) k := fun _ _ h => ext fun i => hk (DFunLike.congr_fun h i) instance faithfulSMul [Nonempty α] [Zero M] [SMulZeroClass R M] [FaithfulSMul R M] : FaithfulSMul R (α →₀ M) where eq_of_smul_eq_smul h := let ⟨a⟩ := ‹Nonempty α› eq_of_smul_eq_smul fun m : M => by simpa using DFunLike.congr_fun (h (single a m)) a instance instSMulWithZero [Zero R] [Zero M] [SMulWithZero R M] : SMulWithZero R (α →₀ M) where zero_smul f := by ext i; exact zero_smul _ _ variable (α M) instance distribSMul [AddZeroClass M] [DistribSMul R M] : DistribSMul R (α →₀ M) where smul := (· • ·) smul_add _ _ _ := ext fun _ => smul_add _ _ _ smul_zero _ := ext fun _ => smul_zero _ instance distribMulAction [Monoid R] [AddMonoid M] [DistribMulAction R M] : DistribMulAction R (α →₀ M) := { Finsupp.distribSMul _ _ with one_smul := fun x => ext fun y => one_smul R (x y) mul_smul := fun r s x => ext fun y => mul_smul r s (x y) } instance isScalarTower [Zero M] [SMulZeroClass R M] [SMulZeroClass S M] [SMul R S] [IsScalarTower R S M] : IsScalarTower R S (α →₀ M) where smul_assoc _ _ _ := ext fun _ => smul_assoc _ _ _ instance smulCommClass [Zero M] [SMulZeroClass R M] [SMulZeroClass S M] [SMulCommClass R S M] : SMulCommClass R S (α →₀ M) where smul_comm _ _ _ := ext fun _ => smul_comm _ _ _ instance isCentralScalar [Zero M] [SMulZeroClass R M] [SMulZeroClass Rᵐᵒᵖ M] [IsCentralScalar R M] : IsCentralScalar R (α →₀ M) where op_smul_eq_smul _ _ := ext fun _ => op_smul_eq_smul _ _ instance module [Semiring R] [AddCommMonoid M] [Module R M] : Module R (α →₀ M) := { toDistribMulAction := Finsupp.distribMulAction α M zero_smul := fun _ => ext fun _ => zero_smul _ _ add_smul := fun _ _ _ => ext fun _ => add_smul _ _ _ } variable {α M} theorem support_smul [AddMonoid M] [SMulZeroClass R M] {b : R} {g : α →₀ M} : (b • g).support ⊆ g.support := fun a => by simp only [smul_apply, mem_support_iff, Ne] exact mt fun h => h.symm ▸ smul_zero _ @[simp] theorem support_smul_eq [Semiring R] [AddCommMonoid M] [Module R M] [NoZeroSMulDivisors R M] {b : R} (hb : b ≠ 0) {g : α →₀ M} : (b • g).support = g.support := Finset.ext fun a => by simp [Finsupp.smul_apply, hb] section variable {p : α → Prop} [DecidablePred p] @[simp] theorem filter_smul {_ : Monoid R} [AddMonoid M] [DistribMulAction R M] {b : R} {v : α →₀ M} : (b • v).filter p = b • v.filter p := DFunLike.coe_injective <| by simp only [filter_eq_indicator, coe_smul] exact Set.indicator_const_smul { x | p x } b v end theorem mapDomain_smul {_ : Monoid R} [AddCommMonoid M] [DistribMulAction R M] {f : α → β} (b : R) (v : α →₀ M) : mapDomain f (b • v) = b • mapDomain f v := mapDomain_mapRange _ _ _ _ (smul_add b) @[simp] theorem smul_single [Zero M] [SMulZeroClass R M] (c : R) (a : α) (b : M) : c • Finsupp.single a b = Finsupp.single a (c • b) := mapRange_single -- Porting note: removed `simp` because `simpNF` can prove it. theorem smul_single' {_ : Semiring R} (c : R) (a : α) (b : R) : c • Finsupp.single a b = Finsupp.single a (c * b) := smul_single _ _ _ theorem mapRange_smul {_ : Monoid R} [AddMonoid M] [DistribMulAction R M] [AddMonoid N] [DistribMulAction R N] {f : M → N} {hf : f 0 = 0} (c : R) (v : α →₀ M) (hsmul : ∀ x, f (c • x) = c • f x) : mapRange f hf (c • v) = c • mapRange f hf v := by erw [← mapRange_comp] · have : f ∘ (c • ·) = (c • ·) ∘ f := funext hsmul simp_rw [this] apply mapRange_comp simp only [Function.comp_apply, smul_zero, hf] theorem smul_single_one [Semiring R] (a : α) (b : R) : b • single a (1 : R) = single a b := by rw [smul_single, smul_eq_mul, mul_one] theorem comapDomain_smul [AddMonoid M] [Monoid R] [DistribMulAction R M] {f : α → β} (r : R) (v : β →₀ M) (hfv : Set.InjOn f (f ⁻¹' ↑v.support)) (hfrv : Set.InjOn f (f ⁻¹' ↑(r • v).support) := hfv.mono <| Set.preimage_mono <| Finset.coe_subset.mpr support_smul) : comapDomain f (r • v) hfrv = r • comapDomain f v hfv := by ext rfl /-- A version of `Finsupp.comapDomain_smul` that's easier to use. -/ theorem comapDomain_smul_of_injective [AddMonoid M] [Monoid R] [DistribMulAction R M] {f : α → β} (hf : Function.Injective f) (r : R) (v : β →₀ M) : comapDomain f (r • v) hf.injOn = r • comapDomain f v hf.injOn := comapDomain_smul _ _ _ _ end theorem sum_smul_index [Semiring R] [AddCommMonoid M] {g : α →₀ R} {b : R} {h : α → R → M} (h0 : ∀ i, h i 0 = 0) : (b • g).sum h = g.sum fun i a => h i (b * a) := Finsupp.sum_mapRange_index h0 theorem sum_smul_index' [AddMonoid M] [DistribSMul R M] [AddCommMonoid N] {g : α →₀ M} {b : R} {h : α → M → N} (h0 : ∀ i, h i 0 = 0) : (b • g).sum h = g.sum fun i c => h i (b • c) := Finsupp.sum_mapRange_index h0 /-- A version of `Finsupp.sum_smul_index'` for bundled additive maps. -/ theorem sum_smul_index_addMonoidHom [AddMonoid M] [AddCommMonoid N] [DistribSMul R M] {g : α →₀ M} {b : R} {h : α → M →+ N} : ((b • g).sum fun a => h a) = g.sum fun i c => h i (b • c) := sum_mapRange_index fun i => (h i).map_zero instance noZeroSMulDivisors [Semiring R] [AddCommMonoid M] [Module R M] {ι : Type*} [NoZeroSMulDivisors R M] : NoZeroSMulDivisors R (ι →₀ M) := ⟨fun h => or_iff_not_imp_left.mpr fun hc => Finsupp.ext fun i => (smul_eq_zero.mp (DFunLike.ext_iff.mp h i)).resolve_left hc⟩ section DistribMulActionSemiHom variable [Semiring R] variable [AddCommMonoid M] [AddCommMonoid N] [DistribMulAction R M] [DistribMulAction R N] /-- `Finsupp.single` as a `DistribMulActionSemiHom`. See also `Finsupp.lsingle` for the version as a linear map. -/ def DistribMulActionHom.single (a : α) : M →+[R] α →₀ M := { singleAddHom a with map_smul' := fun k m => by simp only show singleAddHom a (k • m) = k • singleAddHom a m change Finsupp.single a (k • m) = k • (Finsupp.single a m) -- Porting note: because `singleAddHom_apply` is missing simp only [smul_single] } theorem distribMulActionHom_ext {f g : (α →₀ M) →+[R] N} (h : ∀ (a : α) (m : M), f (single a m) = g (single a m)) : f = g := DistribMulActionHom.toAddMonoidHom_injective <| addHom_ext h /-- See note [partially-applied ext lemmas]. -/ @[ext] theorem distribMulActionHom_ext' {f g : (α →₀ M) →+[R] N} (h : ∀ a : α, f.comp (DistribMulActionHom.single a) = g.comp (DistribMulActionHom.single a)) : f = g := distribMulActionHom_ext fun a => DistribMulActionHom.congr_fun (h a) end DistribMulActionSemiHom section variable [Zero R] /-- The `Finsupp` version of `Pi.unique`. -/ instance uniqueOfRight [Subsingleton R] : Unique (α →₀ R) := DFunLike.coe_injective.unique /-- The `Finsupp` version of `Pi.uniqueOfIsEmpty`. -/ instance uniqueOfLeft [IsEmpty α] : Unique (α →₀ R) := DFunLike.coe_injective.unique end section variable {M : Type*} [Zero M] {P : α → Prop} [DecidablePred P] /-- Combine finitely supported functions over `{a // P a}` and `{a // ¬P a}`, by case-splitting on `P a`. -/ @[simps] def piecewise (f : Subtype P →₀ M) (g : {a // ¬ P a} →₀ M) : α →₀ M where toFun a := if h : P a then f ⟨a, h⟩ else g ⟨a, h⟩ support := (f.support.map (.subtype _)).disjUnion (g.support.map (.subtype _)) <| by simp_rw [Finset.disjoint_left, mem_map, forall_exists_index, Embedding.coe_subtype, Subtype.forall, Subtype.exists] rintro _ a ha ⟨-, rfl⟩ ⟨b, hb, -, rfl⟩ exact hb ha mem_support_toFun a := by by_cases ha : P a <;> simp [ha] @[simp] theorem subtypeDomain_piecewise (f : Subtype P →₀ M) (g : {a // ¬ P a} →₀ M) : subtypeDomain P (f.piecewise g) = f := Finsupp.ext fun a => dif_pos a.prop @[simp] theorem subtypeDomain_not_piecewise (f : Subtype P →₀ M) (g : {a // ¬ P a} →₀ M) : subtypeDomain (¬P ·) (f.piecewise g) = g := Finsupp.ext fun a => dif_neg a.prop /-- Extend the domain of a `Finsupp` by using `0` where `P x` does not hold. -/ @[simps! support toFun] def extendDomain (f : Subtype P →₀ M) : α →₀ M := piecewise f 0 theorem extendDomain_eq_embDomain_subtype (f : Subtype P →₀ M) : extendDomain f = embDomain (.subtype _) f := by ext a by_cases h : P a · refine Eq.trans ?_ (embDomain_apply (.subtype P) f (Subtype.mk a h)).symm simp [h] · rw [embDomain_notin_range, extendDomain_toFun, dif_neg h] simp [h] theorem support_extendDomain_subset (f : Subtype P →₀ M) : ↑(f.extendDomain).support ⊆ {x | P x} := by intro x rw [extendDomain_support, mem_coe, mem_map, Embedding.coe_subtype] rintro ⟨x, -, rfl⟩ exact x.prop @[simp] theorem subtypeDomain_extendDomain (f : Subtype P →₀ M) : subtypeDomain P f.extendDomain = f := subtypeDomain_piecewise _ _ theorem extendDomain_subtypeDomain (f : α →₀ M) (hf : ∀ a ∈ f.support, P a) : (subtypeDomain P f).extendDomain = f := by ext a by_cases h : P a · exact dif_pos h · #adaptation_note /-- Prior to nightly-2024-06-18, this `rw` was done by `dsimp`. -/ rw [extendDomain_toFun] dsimp rw [if_neg h, eq_comm, ← not_mem_support_iff] refine mt ?_ h exact @hf _ @[simp] theorem extendDomain_single (a : Subtype P) (m : M) : (single a m).extendDomain = single a.val m := by ext a' #adaptation_note /-- Prior to nightly-2024-06-18, this `rw` was instead `dsimp only`. -/ rw [extendDomain_toFun] obtain rfl | ha := eq_or_ne a.val a' · simp_rw [single_eq_same, dif_pos a.prop] · simp_rw [single_eq_of_ne ha, dite_eq_right_iff] intro h rw [single_eq_of_ne] simp [Subtype.ext_iff, ha] end /-- Given an `AddCommMonoid M` and `s : Set α`, `restrictSupportEquiv s M` is the `Equiv` between the subtype of finitely supported functions with support contained in `s` and the type of finitely supported functions from `s`. -/ def restrictSupportEquiv (s : Set α) (M : Type*) [AddCommMonoid M] : { f : α →₀ M // ↑f.support ⊆ s } ≃ (s →₀ M) where toFun f := subtypeDomain (· ∈ s) f.1 invFun f := letI := Classical.decPred (· ∈ s); ⟨f.extendDomain, support_extendDomain_subset _⟩ left_inv f := letI := Classical.decPred (· ∈ s); Subtype.ext <| extendDomain_subtypeDomain f.1 f.prop right_inv _ := letI := Classical.decPred (· ∈ s); subtypeDomain_extendDomain _ /-- Given `AddCommMonoid M` and `e : α ≃ β`, `domCongr e` is the corresponding `Equiv` between `α →₀ M` and `β →₀ M`. This is `Finsupp.equivCongrLeft` as an `AddEquiv`. -/ @[simps apply] protected def domCongr [AddCommMonoid M] (e : α ≃ β) : (α →₀ M) ≃+ (β →₀ M) where toFun := equivMapDomain e invFun := equivMapDomain e.symm left_inv v := by simp only [← equivMapDomain_trans, Equiv.self_trans_symm] exact equivMapDomain_refl _ right_inv := by intro v simp only [← equivMapDomain_trans, Equiv.symm_trans_self] exact equivMapDomain_refl _ map_add' a b := by simp only [equivMapDomain_eq_mapDomain]; exact mapDomain_add @[simp] theorem domCongr_refl [AddCommMonoid M] : Finsupp.domCongr (Equiv.refl α) = AddEquiv.refl (α →₀ M) := AddEquiv.ext fun _ => equivMapDomain_refl _ @[simp] theorem domCongr_symm [AddCommMonoid M] (e : α ≃ β) : (Finsupp.domCongr e).symm = (Finsupp.domCongr e.symm : (β →₀ M) ≃+ (α →₀ M)) := AddEquiv.ext fun _ => rfl @[simp] theorem domCongr_trans [AddCommMonoid M] (e : α ≃ β) (f : β ≃ γ) : (Finsupp.domCongr e).trans (Finsupp.domCongr f) = (Finsupp.domCongr (e.trans f) : (α →₀ M) ≃+ _) := AddEquiv.ext fun _ => (equivMapDomain_trans _ _ _).symm end Finsupp namespace Finsupp /-! ### Declarations about sigma types -/ section Sigma variable {αs : ι → Type*} [Zero M] (l : (Σi, αs i) →₀ M) /-- Given `l`, a finitely supported function from the sigma type `Σ (i : ι), αs i` to `M` and an index element `i : ι`, `split l i` is the `i`th component of `l`, a finitely supported function from `as i` to `M`. This is the `Finsupp` version of `Sigma.curry`. -/ def split (i : ι) : αs i →₀ M := l.comapDomain (Sigma.mk i) fun _ _ _ _ hx => heq_iff_eq.1 (Sigma.mk.inj_iff.mp hx).2 -- Porting note: it seems like Lean 4 never generated the `Sigma.mk.inj` lemma? theorem split_apply (i : ι) (x : αs i) : split l i x = l ⟨i, x⟩ := by dsimp only [split] rw [comapDomain_apply] /-- Given `l`, a finitely supported function from the sigma type `Σ (i : ι), αs i` to `β`, `split_support l` is the finset of indices in `ι` that appear in the support of `l`. -/ def splitSupport (l : (Σi, αs i) →₀ M) : Finset ι := haveI := Classical.decEq ι l.support.image Sigma.fst theorem mem_splitSupport_iff_nonzero (i : ι) : i ∈ splitSupport l ↔ split l i ≠ 0 := by rw [splitSupport, @mem_image _ _ (Classical.decEq _), Ne, ← support_eq_empty, ← Ne, ← Finset.nonempty_iff_ne_empty, split, comapDomain, Finset.Nonempty] -- porting note (#10754): had to add the `Classical.decEq` instance manually simp only [exists_prop, Finset.mem_preimage, exists_and_right, exists_eq_right, mem_support_iff, Sigma.exists, Ne] /-- Given `l`, a finitely supported function from the sigma type `Σ i, αs i` to `β` and an `ι`-indexed family `g` of functions from `(αs i →₀ β)` to `γ`, `split_comp` defines a finitely supported function from the index type `ι` to `γ` given by composing `g i` with `split l i`. -/ def splitComp [Zero N] (g : ∀ i, (αs i →₀ M) → N) (hg : ∀ i x, x = 0 ↔ g i x = 0) : ι →₀ N where support := splitSupport l toFun i := g i (split l i) mem_support_toFun := by intro i rw [mem_splitSupport_iff_nonzero, not_iff_not, hg] theorem sigma_support : l.support = l.splitSupport.sigma fun i => (l.split i).support := by simp only [Finset.ext_iff, splitSupport, split, comapDomain, @mem_image _ _ (Classical.decEq _), mem_preimage, Sigma.forall, mem_sigma] -- porting note (#10754): had to add the `Classical.decEq` instance manually tauto theorem sigma_sum [AddCommMonoid N] (f : (Σi : ι, αs i) → M → N) : l.sum f = ∑ i ∈ splitSupport l, (split l i).sum fun (a : αs i) b => f ⟨i, a⟩ b := by simp only [sum, sigma_support, sum_sigma, split_apply] variable {η : Type*} [Fintype η] {ιs : η → Type*} [Zero α] /-- On a `Fintype η`, `Finsupp.split` is an equivalence between `(Σ (j : η), ιs j) →₀ α` and `Π j, (ιs j →₀ α)`. This is the `Finsupp` version of `Equiv.Pi_curry`. -/ noncomputable def sigmaFinsuppEquivPiFinsupp : ((Σj, ιs j) →₀ α) ≃ ∀ j, ιs j →₀ α where toFun := split invFun f := onFinset (Finset.univ.sigma fun j => (f j).support) (fun ji => f ji.1 ji.2) fun g hg => Finset.mem_sigma.mpr ⟨Finset.mem_univ _, mem_support_iff.mpr hg⟩ left_inv f := by ext simp [split] right_inv f := by ext simp [split] @[simp] theorem sigmaFinsuppEquivPiFinsupp_apply (f : (Σj, ιs j) →₀ α) (j i) : sigmaFinsuppEquivPiFinsupp f j i = f ⟨j, i⟩ := rfl /-- On a `Fintype η`, `Finsupp.split` is an additive equivalence between `(Σ (j : η), ιs j) →₀ α` and `Π j, (ιs j →₀ α)`. This is the `AddEquiv` version of `Finsupp.sigmaFinsuppEquivPiFinsupp`. -/ noncomputable def sigmaFinsuppAddEquivPiFinsupp {α : Type*} {ιs : η → Type*} [AddMonoid α] : ((Σj, ιs j) →₀ α) ≃+ ∀ j, ιs j →₀ α := { sigmaFinsuppEquivPiFinsupp with map_add' := fun f g => by ext simp } @[simp] theorem sigmaFinsuppAddEquivPiFinsupp_apply {α : Type*} {ιs : η → Type*} [AddMonoid α] (f : (Σj, ιs j) →₀ α) (j i) : sigmaFinsuppAddEquivPiFinsupp f j i = f ⟨j, i⟩ := rfl end Sigma end Finsupp
Data\Finsupp\BigOperators.lean
/- Copyright (c) 2022 Yakov Pechersky. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yakov Pechersky -/ import Mathlib.Algebra.BigOperators.Group.Finset import Mathlib.Data.Finsupp.Defs import Mathlib.Data.Finset.Pairwise /-! # Sums of collections of Finsupp, and their support This file provides results about the `Finsupp.support` of sums of collections of `Finsupp`, including sums of `List`, `Multiset`, and `Finset`. The support of the sum is a subset of the union of the supports: * `List.support_sum_subset` * `Multiset.support_sum_subset` * `Finset.support_sum_subset` The support of the sum of pairwise disjoint finsupps is equal to the union of the supports * `List.support_sum_eq` * `Multiset.support_sum_eq` * `Finset.support_sum_eq` Member in the support of the indexed union over a collection iff it is a member of the support of a member of the collection: * `List.mem_foldr_sup_support_iff` * `Multiset.mem_sup_map_support_iff` * `Finset.mem_sup_support_iff` -/ variable {ι M : Type*} [DecidableEq ι] theorem List.support_sum_subset [AddMonoid M] (l : List (ι →₀ M)) : l.sum.support ⊆ l.foldr (Finsupp.support · ⊔ ·) ∅ := by induction' l with hd tl IH · simp · simp only [List.sum_cons, Finset.union_comm] refine Finsupp.support_add.trans (Finset.union_subset_union ?_ IH) rfl theorem Multiset.support_sum_subset [AddCommMonoid M] (s : Multiset (ι →₀ M)) : s.sum.support ⊆ (s.map Finsupp.support).sup := by induction s using Quot.inductionOn simpa only [Multiset.quot_mk_to_coe'', Multiset.sum_coe, Multiset.map_coe, Multiset.sup_coe, List.foldr_map] using List.support_sum_subset _ theorem Finset.support_sum_subset [AddCommMonoid M] (s : Finset (ι →₀ M)) : (s.sum id).support ⊆ Finset.sup s Finsupp.support := by classical convert Multiset.support_sum_subset s.1; simp theorem List.mem_foldr_sup_support_iff [Zero M] {l : List (ι →₀ M)} {x : ι} : x ∈ l.foldr (Finsupp.support · ⊔ ·) ∅ ↔ ∃ f ∈ l, x ∈ f.support := by simp only [Finset.sup_eq_union, List.foldr_map, Finsupp.mem_support_iff, exists_prop] induction' l with hd tl IH · simp · simp only [foldr, Function.comp_apply, Finset.mem_union, Finsupp.mem_support_iff, ne_eq, IH, find?, mem_cons, exists_eq_or_imp] theorem Multiset.mem_sup_map_support_iff [Zero M] {s : Multiset (ι →₀ M)} {x : ι} : x ∈ (s.map Finsupp.support).sup ↔ ∃ f ∈ s, x ∈ f.support := Quot.inductionOn s fun _ ↦ by simpa only [Multiset.quot_mk_to_coe'', Multiset.map_coe, Multiset.sup_coe, List.foldr_map] using List.mem_foldr_sup_support_iff theorem Finset.mem_sup_support_iff [Zero M] {s : Finset (ι →₀ M)} {x : ι} : x ∈ s.sup Finsupp.support ↔ ∃ f ∈ s, x ∈ f.support := Multiset.mem_sup_map_support_iff theorem List.support_sum_eq [AddMonoid M] (l : List (ι →₀ M)) (hl : l.Pairwise (_root_.Disjoint on Finsupp.support)) : l.sum.support = l.foldr (Finsupp.support · ⊔ ·) ∅ := by induction' l with hd tl IH · simp · simp only [List.pairwise_cons] at hl simp only [List.sum_cons, List.foldr_cons, Function.comp_apply] rw [Finsupp.support_add_eq, IH hl.right, Finset.sup_eq_union] suffices _root_.Disjoint hd.support (tl.foldr (fun x y ↦ (Finsupp.support x ⊔ y)) ∅) by exact Finset.disjoint_of_subset_right (List.support_sum_subset _) this rw [← List.foldr_map, ← Finset.bot_eq_empty, List.foldr_sup_eq_sup_toFinset, Finset.disjoint_sup_right] intro f hf simp only [List.mem_toFinset, List.mem_map] at hf obtain ⟨f, hf, rfl⟩ := hf exact hl.left _ hf theorem Multiset.support_sum_eq [AddCommMonoid M] (s : Multiset (ι →₀ M)) (hs : s.Pairwise (_root_.Disjoint on Finsupp.support)) : s.sum.support = (s.map Finsupp.support).sup := by induction' s using Quot.inductionOn with a obtain ⟨l, hl, hd⟩ := hs suffices a.Pairwise (_root_.Disjoint on Finsupp.support) by convert List.support_sum_eq a this · simp only [Multiset.quot_mk_to_coe'', Multiset.sum_coe] · dsimp only [Function.comp_def] simp only [quot_mk_to_coe'', map_coe, sup_coe, Finset.le_eq_subset, Finset.sup_eq_union, Finset.bot_eq_empty, List.foldr_map] simp only [Multiset.quot_mk_to_coe'', Multiset.map_coe, Multiset.coe_eq_coe] at hl exact hl.symm.pairwise hd fun h ↦ _root_.Disjoint.symm h theorem Finset.support_sum_eq [AddCommMonoid M] (s : Finset (ι →₀ M)) (hs : (s : Set (ι →₀ M)).PairwiseDisjoint Finsupp.support) : (s.sum id).support = Finset.sup s Finsupp.support := by classical suffices s.1.Pairwise (_root_.Disjoint on Finsupp.support) by convert Multiset.support_sum_eq s.1 this exact (Finset.sum_val _).symm obtain ⟨l, hl, hn⟩ : ∃ l : List (ι →₀ M), l.toFinset = s ∧ l.Nodup := by refine ⟨s.toList, ?_, Finset.nodup_toList _⟩ simp subst hl rwa [List.toFinset_val, List.dedup_eq_self.mpr hn, Multiset.pairwise_coe_iff_pairwise, ← List.pairwiseDisjoint_iff_coe_toFinset_pairwise_disjoint hn] intro x y hxy exact symmetric_disjoint hxy
Data\Finsupp\Defs.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, Scott Morrison -/ import Mathlib.Algebra.Group.Indicator import Mathlib.Algebra.Group.Submonoid.Basic import Mathlib.Data.Set.Finite /-! # Type of functions with finite support For any type `α` and any type `M` with zero, we define the type `Finsupp α M` (notation: `α →₀ M`) of finitely supported functions from `α` to `M`, i.e. the functions which are zero everywhere on `α` except on a finite set. Functions with finite support are used (at least) in the following parts of the library: * `MonoidAlgebra R M` and `AddMonoidAlgebra R M` are defined as `M →₀ R`; * polynomials and multivariate polynomials are defined as `AddMonoidAlgebra`s, hence they use `Finsupp` under the hood; * the linear combination of a family of vectors `v i` with coefficients `f i` (as used, e.g., to define linearly independent family `LinearIndependent`) is defined as a map `Finsupp.total : (ι → M) → (ι →₀ R) →ₗ[R] M`. Some other constructions are naturally equivalent to `α →₀ M` with some `α` and `M` but are defined in a different way in the library: * `Multiset α ≃+ α →₀ ℕ`; * `FreeAbelianGroup α ≃+ α →₀ ℤ`. Most of the theory assumes that the range is a commutative additive monoid. This gives us the big sum operator as a powerful way to construct `Finsupp` elements, which is defined in `Algebra/BigOperators/Finsupp`. -- Porting note: the semireducibility remark no longer applies in Lean 4, afaict. Many constructions based on `α →₀ M` use `semireducible` type tags to avoid reusing unwanted type instances. E.g., `MonoidAlgebra`, `AddMonoidAlgebra`, and types based on these two have non-pointwise multiplication. ## Main declarations * `Finsupp`: The type of finitely supported functions from `α` to `β`. * `Finsupp.single`: The `Finsupp` which is nonzero in exactly one point. * `Finsupp.update`: Changes one value of a `Finsupp`. * `Finsupp.erase`: Replaces one value of a `Finsupp` by `0`. * `Finsupp.onFinset`: The restriction of a function to a `Finset` as a `Finsupp`. * `Finsupp.mapRange`: Composition of a `ZeroHom` with a `Finsupp`. * `Finsupp.embDomain`: Maps the domain of a `Finsupp` by an embedding. * `Finsupp.zipWith`: Postcomposition of two `Finsupp`s with a function `f` such that `f 0 0 = 0`. ## Notations This file adds `α →₀ M` as a global notation for `Finsupp α M`. We also use the following convention for `Type*` variables in this file * `α`, `β`, `γ`: types with no additional structure that appear as the first argument to `Finsupp` somewhere in the statement; * `ι` : an auxiliary index type; * `M`, `M'`, `N`, `P`: types with `Zero` or `(Add)(Comm)Monoid` structure; `M` is also used for a (semi)module over a (semi)ring. * `G`, `H`: groups (commutative or not, multiplicative or additive); * `R`, `S`: (semi)rings. ## Implementation notes This file is a `noncomputable theory` and uses classical logic throughout. ## TODO * Expand the list of definitions and important lemmas to the module docstring. -/ noncomputable section open Finset Function variable {α β γ ι M M' N P G H R S : Type*} /-- `Finsupp α M`, denoted `α →₀ M`, is the type of functions `f : α → M` such that `f x = 0` for all but finitely many `x`. -/ structure Finsupp (α : Type*) (M : Type*) [Zero M] where /-- The support of a finitely supported function (aka `Finsupp`). -/ support : Finset α /-- The underlying function of a bundled finitely supported function (aka `Finsupp`). -/ toFun : α → M /-- The witness that the support of a `Finsupp` is indeed the exact locus where its underlying function is nonzero. -/ mem_support_toFun : ∀ a, a ∈ support ↔ toFun a ≠ 0 @[inherit_doc] infixr:25 " →₀ " => Finsupp namespace Finsupp /-! ### Basic declarations about `Finsupp` -/ section Basic variable [Zero M] instance instFunLike : FunLike (α →₀ M) α M := ⟨toFun, by rintro ⟨s, f, hf⟩ ⟨t, g, hg⟩ (rfl : f = g) congr ext a exact (hf _).trans (hg _).symm⟩ /-- Helper instance for when there are too many metavariables to apply the `DFunLike` instance directly. -/ instance instCoeFun : CoeFun (α →₀ M) fun _ => α → M := inferInstance @[ext] theorem ext {f g : α →₀ M} (h : ∀ a, f a = g a) : f = g := DFunLike.ext _ _ h lemma ne_iff {f g : α →₀ M} : f ≠ g ↔ ∃ a, f a ≠ g a := DFunLike.ne_iff @[simp, norm_cast] theorem coe_mk (f : α → M) (s : Finset α) (h : ∀ a, a ∈ s ↔ f a ≠ 0) : ⇑(⟨s, f, h⟩ : α →₀ M) = f := rfl instance instZero : Zero (α →₀ M) := ⟨⟨∅, 0, fun _ => ⟨fun h ↦ (not_mem_empty _ h).elim, fun H => (H rfl).elim⟩⟩⟩ @[simp, norm_cast] lemma coe_zero : ⇑(0 : α →₀ M) = 0 := rfl theorem zero_apply {a : α} : (0 : α →₀ M) a = 0 := rfl @[simp] theorem support_zero : (0 : α →₀ M).support = ∅ := rfl instance instInhabited : Inhabited (α →₀ M) := ⟨0⟩ @[simp] theorem mem_support_iff {f : α →₀ M} : ∀ {a : α}, a ∈ f.support ↔ f a ≠ 0 := @(f.mem_support_toFun) @[simp, norm_cast] theorem fun_support_eq (f : α →₀ M) : Function.support f = f.support := Set.ext fun _x => mem_support_iff.symm theorem not_mem_support_iff {f : α →₀ M} {a} : a ∉ f.support ↔ f a = 0 := not_iff_comm.1 mem_support_iff.symm @[simp, norm_cast] theorem coe_eq_zero {f : α →₀ M} : (f : α → M) = 0 ↔ f = 0 := by rw [← coe_zero, DFunLike.coe_fn_eq] theorem ext_iff' {f g : α →₀ M} : f = g ↔ f.support = g.support ∧ ∀ x ∈ f.support, f x = g x := ⟨fun h => h ▸ ⟨rfl, fun _ _ => rfl⟩, fun ⟨h₁, h₂⟩ => ext fun a => by classical exact if h : a ∈ f.support then h₂ a h else by have hf : f a = 0 := not_mem_support_iff.1 h have hg : g a = 0 := by rwa [h₁, not_mem_support_iff] at h rw [hf, hg]⟩ @[simp] theorem support_eq_empty {f : α →₀ M} : f.support = ∅ ↔ f = 0 := mod_cast @Function.support_eq_empty_iff _ _ _ f theorem support_nonempty_iff {f : α →₀ M} : f.support.Nonempty ↔ f ≠ 0 := by simp only [Finsupp.support_eq_empty, Finset.nonempty_iff_ne_empty, Ne] theorem card_support_eq_zero {f : α →₀ M} : card f.support = 0 ↔ f = 0 := by simp instance instDecidableEq [DecidableEq α] [DecidableEq M] : DecidableEq (α →₀ M) := fun f g => decidable_of_iff (f.support = g.support ∧ ∀ a ∈ f.support, f a = g a) ext_iff'.symm theorem finite_support (f : α →₀ M) : Set.Finite (Function.support f) := f.fun_support_eq.symm ▸ f.support.finite_toSet theorem support_subset_iff {s : Set α} {f : α →₀ M} : ↑f.support ⊆ s ↔ ∀ a ∉ s, f a = 0 := by simp only [Set.subset_def, mem_coe, mem_support_iff]; exact forall_congr' fun a => not_imp_comm /-- Given `Finite α`, `equivFunOnFinite` is the `Equiv` between `α →₀ β` and `α → β`. (All functions on a finite type are finitely supported.) -/ @[simps] def equivFunOnFinite [Finite α] : (α →₀ M) ≃ (α → M) where toFun := (⇑) invFun f := mk (Function.support f).toFinite.toFinset f fun _a => Set.Finite.mem_toFinset _ left_inv _f := ext fun _x => rfl right_inv _f := rfl @[simp] theorem equivFunOnFinite_symm_coe {α} [Finite α] (f : α →₀ M) : equivFunOnFinite.symm f = f := equivFunOnFinite.symm_apply_apply f /-- If `α` has a unique term, the type of finitely supported functions `α →₀ β` is equivalent to `β`. -/ @[simps!] noncomputable def _root_.Equiv.finsuppUnique {ι : Type*} [Unique ι] : (ι →₀ M) ≃ M := Finsupp.equivFunOnFinite.trans (Equiv.funUnique ι M) @[ext] theorem unique_ext [Unique α] {f g : α →₀ M} (h : f default = g default) : f = g := ext fun a => by rwa [Unique.eq_default a] end Basic /-! ### Declarations about `single` -/ section Single variable [Zero M] {a a' : α} {b : M} /-- `single a b` is the finitely supported function with value `b` at `a` and zero otherwise. -/ def single (a : α) (b : M) : α →₀ M where support := haveI := Classical.decEq M if b = 0 then ∅ else {a} toFun := haveI := Classical.decEq α Pi.single a b mem_support_toFun a' := by classical obtain rfl | hb := eq_or_ne b 0 · simp [Pi.single, update] rw [if_neg hb, mem_singleton] obtain rfl | ha := eq_or_ne a' a · simp [hb, Pi.single, update] simp [Pi.single_eq_of_ne' ha.symm, ha] theorem single_apply [Decidable (a = a')] : single a b a' = if a = a' then b else 0 := by classical simp_rw [@eq_comm _ a a'] convert Pi.single_apply a b a' theorem single_apply_left {f : α → β} (hf : Function.Injective f) (x z : α) (y : M) : single (f x) y (f z) = single x y z := by classical simp only [single_apply, hf.eq_iff] theorem single_eq_set_indicator : ⇑(single a b) = Set.indicator {a} fun _ => b := by classical ext simp [single_apply, Set.indicator, @eq_comm _ a] @[simp] theorem single_eq_same : (single a b : α →₀ M) a = b := by classical exact Pi.single_eq_same (f := fun _ ↦ M) a b @[simp] theorem single_eq_of_ne (h : a ≠ a') : (single a b : α →₀ M) a' = 0 := by classical exact Pi.single_eq_of_ne' h _ theorem single_eq_update [DecidableEq α] (a : α) (b : M) : ⇑(single a b) = Function.update (0 : _) a b := by classical rw [single_eq_set_indicator, ← Set.piecewise_eq_indicator, Set.piecewise_singleton] theorem single_eq_pi_single [DecidableEq α] (a : α) (b : M) : ⇑(single a b) = Pi.single a b := single_eq_update a b @[simp] theorem single_zero (a : α) : (single a 0 : α →₀ M) = 0 := DFunLike.coe_injective <| by classical simpa only [single_eq_update, coe_zero] using Function.update_eq_self a (0 : α → M) theorem single_of_single_apply (a a' : α) (b : M) : single a ((single a' b) a) = single a' (single a' b) a := by classical rw [single_apply, single_apply] ext split_ifs with h · rw [h] · rw [zero_apply, single_apply, ite_self] theorem support_single_ne_zero (a : α) (hb : b ≠ 0) : (single a b).support = {a} := if_neg hb theorem support_single_subset : (single a b).support ⊆ {a} := by classical show ite _ _ _ ⊆ _; split_ifs <;> [exact empty_subset _; exact Subset.refl _] theorem single_apply_mem (x) : single a b x ∈ ({0, b} : Set M) := by rcases em (a = x) with (rfl | hx) <;> [simp; simp [single_eq_of_ne hx]] theorem range_single_subset : Set.range (single a b) ⊆ {0, b} := Set.range_subset_iff.2 single_apply_mem /-- `Finsupp.single a b` is injective in `b`. For the statement that it is injective in `a`, see `Finsupp.single_left_injective` -/ theorem single_injective (a : α) : Function.Injective (single a : M → α →₀ M) := fun b₁ b₂ eq => by have : (single a b₁ : α →₀ M) a = (single a b₂ : α →₀ M) a := by rw [eq] rwa [single_eq_same, single_eq_same] at this theorem single_apply_eq_zero {a x : α} {b : M} : single a b x = 0 ↔ x = a → b = 0 := by simp [single_eq_set_indicator] theorem single_apply_ne_zero {a x : α} {b : M} : single a b x ≠ 0 ↔ x = a ∧ b ≠ 0 := by simp [single_apply_eq_zero] theorem mem_support_single (a a' : α) (b : M) : a ∈ (single a' b).support ↔ a = a' ∧ b ≠ 0 := by simp [single_apply_eq_zero, not_or] theorem eq_single_iff {f : α →₀ M} {a b} : f = single a b ↔ f.support ⊆ {a} ∧ f a = b := by refine ⟨fun h => h.symm ▸ ⟨support_single_subset, single_eq_same⟩, ?_⟩ rintro ⟨h, rfl⟩ ext x by_cases hx : a = x <;> simp only [hx, single_eq_same, single_eq_of_ne, Ne, not_false_iff] exact not_mem_support_iff.1 (mt (fun hx => (mem_singleton.1 (h hx)).symm) hx) theorem single_eq_single_iff (a₁ a₂ : α) (b₁ b₂ : M) : single a₁ b₁ = single a₂ b₂ ↔ a₁ = a₂ ∧ b₁ = b₂ ∨ b₁ = 0 ∧ b₂ = 0 := by constructor · intro eq by_cases h : a₁ = a₂ · refine Or.inl ⟨h, ?_⟩ rwa [h, (single_injective a₂).eq_iff] at eq · rw [DFunLike.ext_iff] at eq have h₁ := eq a₁ have h₂ := eq a₂ simp only [single_eq_same, single_eq_of_ne h, single_eq_of_ne (Ne.symm h)] at h₁ h₂ exact Or.inr ⟨h₁, h₂.symm⟩ · rintro (⟨rfl, rfl⟩ | ⟨rfl, rfl⟩) · rfl · rw [single_zero, single_zero] /-- `Finsupp.single a b` is injective in `a`. For the statement that it is injective in `b`, see `Finsupp.single_injective` -/ theorem single_left_injective (h : b ≠ 0) : Function.Injective fun a : α => single a b := fun _a _a' H => (((single_eq_single_iff _ _ _ _).mp H).resolve_right fun hb => h hb.1).left theorem single_left_inj (h : b ≠ 0) : single a b = single a' b ↔ a = a' := (single_left_injective h).eq_iff theorem support_single_ne_bot (i : α) (h : b ≠ 0) : (single i b).support ≠ ⊥ := by simpa only [support_single_ne_zero _ h] using singleton_ne_empty _ theorem support_single_disjoint {b' : M} (hb : b ≠ 0) (hb' : b' ≠ 0) {i j : α} : Disjoint (single i b).support (single j b').support ↔ i ≠ j := by rw [support_single_ne_zero _ hb, support_single_ne_zero _ hb', disjoint_singleton] @[simp] theorem single_eq_zero : single a b = 0 ↔ b = 0 := by simp [DFunLike.ext_iff, single_eq_set_indicator] theorem single_swap (a₁ a₂ : α) (b : M) : single a₁ b a₂ = single a₂ b a₁ := by classical simp only [single_apply, eq_comm] instance instNontrivial [Nonempty α] [Nontrivial M] : Nontrivial (α →₀ M) := by inhabit α rcases exists_ne (0 : M) with ⟨x, hx⟩ exact nontrivial_of_ne (single default x) 0 (mt single_eq_zero.1 hx) theorem unique_single [Unique α] (x : α →₀ M) : x = single default (x default) := ext <| Unique.forall_iff.2 single_eq_same.symm @[simp] theorem unique_single_eq_iff [Unique α] {b' : M} : single a b = single a' b' ↔ b = b' := by rw [Finsupp.unique_ext_iff, Unique.eq_default a, Unique.eq_default a', single_eq_same, single_eq_same] lemma apply_single [AddCommMonoid N] [AddCommMonoid P] {F : Type*} [FunLike F N P] [AddMonoidHomClass F N P] (e : F) (a : α) (n : N) (b : α) : e ((single a n) b) = single a (e n) b := by classical simp only [single_apply] split_ifs · rfl · exact map_zero e theorem support_eq_singleton {f : α →₀ M} {a : α} : f.support = {a} ↔ f a ≠ 0 ∧ f = single a (f a) := ⟨fun h => ⟨mem_support_iff.1 <| h.symm ▸ Finset.mem_singleton_self a, eq_single_iff.2 ⟨subset_of_eq h, rfl⟩⟩, fun h => h.2.symm ▸ support_single_ne_zero _ h.1⟩ theorem support_eq_singleton' {f : α →₀ M} {a : α} : f.support = {a} ↔ ∃ b ≠ 0, f = single a b := ⟨fun h => let h := support_eq_singleton.1 h ⟨_, h.1, h.2⟩, fun ⟨_b, hb, hf⟩ => hf.symm ▸ support_single_ne_zero _ hb⟩ theorem card_support_eq_one {f : α →₀ M} : card f.support = 1 ↔ ∃ a, f a ≠ 0 ∧ f = single a (f a) := by simp only [card_eq_one, support_eq_singleton] theorem card_support_eq_one' {f : α →₀ M} : card f.support = 1 ↔ ∃ a, ∃ b ≠ 0, f = single a b := by simp only [card_eq_one, support_eq_singleton'] theorem support_subset_singleton {f : α →₀ M} {a : α} : f.support ⊆ {a} ↔ f = single a (f a) := ⟨fun h => eq_single_iff.mpr ⟨h, rfl⟩, fun h => (eq_single_iff.mp h).left⟩ theorem support_subset_singleton' {f : α →₀ M} {a : α} : f.support ⊆ {a} ↔ ∃ b, f = single a b := ⟨fun h => ⟨f a, support_subset_singleton.mp h⟩, fun ⟨b, hb⟩ => by rw [hb, support_subset_singleton, single_eq_same]⟩ theorem card_support_le_one [Nonempty α] {f : α →₀ M} : card f.support ≤ 1 ↔ ∃ a, f = single a (f a) := by simp only [card_le_one_iff_subset_singleton, support_subset_singleton] theorem card_support_le_one' [Nonempty α] {f : α →₀ M} : card f.support ≤ 1 ↔ ∃ a b, f = single a b := by simp only [card_le_one_iff_subset_singleton, support_subset_singleton'] @[simp] theorem equivFunOnFinite_single [DecidableEq α] [Finite α] (x : α) (m : M) : Finsupp.equivFunOnFinite (Finsupp.single x m) = Pi.single x m := by ext simp [Finsupp.single_eq_pi_single, equivFunOnFinite] @[simp] theorem equivFunOnFinite_symm_single [DecidableEq α] [Finite α] (x : α) (m : M) : Finsupp.equivFunOnFinite.symm (Pi.single x m) = Finsupp.single x m := by rw [← equivFunOnFinite_single, Equiv.symm_apply_apply] end Single /-! ### Declarations about `update` -/ section Update variable [Zero M] (f : α →₀ M) (a : α) (b : M) (i : α) /-- Replace the value of a `α →₀ M` at a given point `a : α` by a given value `b : M`. If `b = 0`, this amounts to removing `a` from the `Finsupp.support`. Otherwise, if `a` was not in the `Finsupp.support`, it is added to it. This is the finitely-supported version of `Function.update`. -/ def update (f : α →₀ M) (a : α) (b : M) : α →₀ M where support := by haveI := Classical.decEq α; haveI := Classical.decEq M exact if b = 0 then f.support.erase a else insert a f.support toFun := haveI := Classical.decEq α Function.update f a b mem_support_toFun i := by classical rw [Function.update] simp only [eq_rec_constant, dite_eq_ite, ne_eq] split_ifs with hb ha ha <;> try simp only [*, not_false_iff, iff_true, not_true, iff_false] · rw [Finset.mem_erase] simp · rw [Finset.mem_erase] simp [ha] · rw [Finset.mem_insert] simp [ha] · rw [Finset.mem_insert] simp [ha] @[simp, norm_cast] theorem coe_update [DecidableEq α] : (f.update a b : α → M) = Function.update f a b := by delta update Function.update ext dsimp split_ifs <;> simp @[simp] theorem update_self : f.update a (f a) = f := by classical ext simp @[simp] theorem zero_update : update 0 a b = single a b := by classical ext rw [single_eq_update] rfl theorem support_update [DecidableEq α] [DecidableEq M] : support (f.update a b) = if b = 0 then f.support.erase a else insert a f.support := by classical dsimp only [update] congr! @[simp] theorem support_update_zero [DecidableEq α] : support (f.update a 0) = f.support.erase a := by classical simp only [update, ite_true, mem_support_iff, ne_eq, not_not] congr! variable {b} theorem support_update_ne_zero [DecidableEq α] (h : b ≠ 0) : support (f.update a b) = insert a f.support := by classical simp only [update, h, ite_false, mem_support_iff, ne_eq] congr! theorem support_update_subset [DecidableEq α] : support (f.update a b) ⊆ insert a f.support := by classical rw [support_update] split_ifs · exact (erase_subset _ _).trans (subset_insert _ _) · rfl theorem update_comm (f : α →₀ M) {a₁ a₂ : α} (h : a₁ ≠ a₂) (m₁ m₂ : M) : update (update f a₁ m₁) a₂ m₂ = update (update f a₂ m₂) a₁ m₁ := letI := Classical.decEq α DFunLike.coe_injective <| Function.update_comm h _ _ _ @[simp] theorem update_idem (f : α →₀ M) (a : α) (b c : M) : update (update f a b) a c = update f a c := letI := Classical.decEq α DFunLike.coe_injective <| Function.update_idem _ _ _ end Update /-! ### Declarations about `erase` -/ section Erase variable [Zero M] /-- `erase a f` is the finitely supported function equal to `f` except at `a` where it is equal to `0`. If `a` is not in the support of `f` then `erase a f = f`. -/ def erase (a : α) (f : α →₀ M) : α →₀ M where support := haveI := Classical.decEq α f.support.erase a toFun a' := haveI := Classical.decEq α if a' = a then 0 else f a' mem_support_toFun a' := by classical rw [mem_erase, mem_support_iff]; dsimp split_ifs with h · exact ⟨fun H _ => H.1 h, fun H => (H rfl).elim⟩ · exact and_iff_right h @[simp] theorem support_erase [DecidableEq α] {a : α} {f : α →₀ M} : (f.erase a).support = f.support.erase a := by classical dsimp only [erase] congr! @[simp] theorem erase_same {a : α} {f : α →₀ M} : (f.erase a) a = 0 := by classical simp only [erase, coe_mk, ite_true] @[simp] theorem erase_ne {a a' : α} {f : α →₀ M} (h : a' ≠ a) : (f.erase a) a' = f a' := by classical simp only [erase, coe_mk, h, ite_false] theorem erase_apply [DecidableEq α] {a a' : α} {f : α →₀ M} : f.erase a a' = if a' = a then 0 else f a' := by rw [erase, coe_mk] convert rfl @[simp] theorem erase_single {a : α} {b : M} : erase a (single a b) = 0 := by ext s; by_cases hs : s = a · rw [hs, erase_same] rfl · rw [erase_ne hs] exact single_eq_of_ne (Ne.symm hs) theorem erase_single_ne {a a' : α} {b : M} (h : a ≠ a') : erase a (single a' b) = single a' b := by ext s; by_cases hs : s = a · rw [hs, erase_same, single_eq_of_ne h.symm] · rw [erase_ne hs] @[simp] theorem erase_of_not_mem_support {f : α →₀ M} {a} (haf : a ∉ f.support) : erase a f = f := by ext b; by_cases hab : b = a · rwa [hab, erase_same, eq_comm, ← not_mem_support_iff] · rw [erase_ne hab] @[simp, nolint simpNF] -- Porting note: simpNF linter claims simp can prove this, it can not theorem erase_zero (a : α) : erase a (0 : α →₀ M) = 0 := by classical rw [← support_eq_empty, support_erase, support_zero, erase_empty] theorem erase_eq_update_zero (f : α →₀ M) (a : α) : f.erase a = update f a 0 := letI := Classical.decEq α ext fun _ => (Function.update_apply _ _ _ _).symm -- The name matches `Finset.erase_insert_of_ne` theorem erase_update_of_ne (f : α →₀ M) {a a' : α} (ha : a ≠ a') (b : M) : erase a (update f a' b) = update (erase a f) a' b := by rw [erase_eq_update_zero, erase_eq_update_zero, update_comm _ ha] -- not `simp` as `erase_of_not_mem_support` can prove this theorem erase_idem (f : α →₀ M) (a : α) : erase a (erase a f) = erase a f := by rw [erase_eq_update_zero, erase_eq_update_zero, update_idem] @[simp] theorem update_erase_eq_update (f : α →₀ M) (a : α) (b : M) : update (erase a f) a b = update f a b := by rw [erase_eq_update_zero, update_idem] @[simp] theorem erase_update_eq_erase (f : α →₀ M) (a : α) (b : M) : erase a (update f a b) = erase a f := by rw [erase_eq_update_zero, erase_eq_update_zero, update_idem] end Erase /-! ### Declarations about `onFinset` -/ section OnFinset variable [Zero M] /-- `Finsupp.onFinset s f hf` is the finsupp function representing `f` restricted to the finset `s`. The function must be `0` outside of `s`. Use this when the set needs to be filtered anyways, otherwise a better set representation is often available. -/ def onFinset (s : Finset α) (f : α → M) (hf : ∀ a, f a ≠ 0 → a ∈ s) : α →₀ M where support := haveI := Classical.decEq M s.filter (f · ≠ 0) toFun := f mem_support_toFun := by classical simpa @[simp, norm_cast] lemma coe_onFinset (s : Finset α) (f : α → M) (hf) : onFinset s f hf = f := rfl @[simp] theorem onFinset_apply {s : Finset α} {f : α → M} {hf a} : (onFinset s f hf : α →₀ M) a = f a := rfl @[simp] theorem support_onFinset_subset {s : Finset α} {f : α → M} {hf} : (onFinset s f hf).support ⊆ s := by classical convert filter_subset (f · ≠ 0) s -- @[simp] -- Porting note (#10618): simp can prove this theorem mem_support_onFinset {s : Finset α} {f : α → M} (hf : ∀ a : α, f a ≠ 0 → a ∈ s) {a : α} : a ∈ (Finsupp.onFinset s f hf).support ↔ f a ≠ 0 := by rw [Finsupp.mem_support_iff, Finsupp.onFinset_apply] theorem support_onFinset [DecidableEq M] {s : Finset α} {f : α → M} (hf : ∀ a : α, f a ≠ 0 → a ∈ s) : (Finsupp.onFinset s f hf).support = s.filter fun a => f a ≠ 0 := by dsimp [onFinset]; congr end OnFinset section OfSupportFinite variable [Zero M] /-- The natural `Finsupp` induced by the function `f` given that it has finite support. -/ noncomputable def ofSupportFinite (f : α → M) (hf : (Function.support f).Finite) : α →₀ M where support := hf.toFinset toFun := f mem_support_toFun _ := hf.mem_toFinset theorem ofSupportFinite_coe {f : α → M} {hf : (Function.support f).Finite} : (ofSupportFinite f hf : α → M) = f := rfl instance instCanLift : CanLift (α → M) (α →₀ M) (⇑) fun f => (Function.support f).Finite where prf f hf := ⟨ofSupportFinite f hf, rfl⟩ end OfSupportFinite /-! ### Declarations about `mapRange` -/ section MapRange variable [Zero M] [Zero N] [Zero P] /-- The composition of `f : M → N` and `g : α →₀ M` is `mapRange f hf g : α →₀ N`, which is well-defined when `f 0 = 0`. This preserves the structure on `f`, and exists in various bundled forms for when `f` is itself bundled (defined in `Data/Finsupp/Basic`): * `Finsupp.mapRange.equiv` * `Finsupp.mapRange.zeroHom` * `Finsupp.mapRange.addMonoidHom` * `Finsupp.mapRange.addEquiv` * `Finsupp.mapRange.linearMap` * `Finsupp.mapRange.linearEquiv` -/ def mapRange (f : M → N) (hf : f 0 = 0) (g : α →₀ M) : α →₀ N := onFinset g.support (f ∘ g) fun a => by rw [mem_support_iff, not_imp_not]; exact fun H => (congr_arg f H).trans hf @[simp] theorem mapRange_apply {f : M → N} {hf : f 0 = 0} {g : α →₀ M} {a : α} : mapRange f hf g a = f (g a) := rfl @[simp] theorem mapRange_zero {f : M → N} {hf : f 0 = 0} : mapRange f hf (0 : α →₀ M) = 0 := ext fun _ => by simp only [hf, zero_apply, mapRange_apply] @[simp] theorem mapRange_id (g : α →₀ M) : mapRange id rfl g = g := ext fun _ => rfl theorem mapRange_comp (f : N → P) (hf : f 0 = 0) (f₂ : M → N) (hf₂ : f₂ 0 = 0) (h : (f ∘ f₂) 0 = 0) (g : α →₀ M) : mapRange (f ∘ f₂) h g = mapRange f hf (mapRange f₂ hf₂ g) := ext fun _ => rfl theorem support_mapRange {f : M → N} {hf : f 0 = 0} {g : α →₀ M} : (mapRange f hf g).support ⊆ g.support := support_onFinset_subset @[simp] theorem mapRange_single {f : M → N} {hf : f 0 = 0} {a : α} {b : M} : mapRange f hf (single a b) = single a (f b) := ext fun a' => by classical simpa only [single_eq_pi_single] using Pi.apply_single _ (fun _ => hf) a _ a' theorem support_mapRange_of_injective {e : M → N} (he0 : e 0 = 0) (f : ι →₀ M) (he : Function.Injective e) : (Finsupp.mapRange e he0 f).support = f.support := by ext simp only [Finsupp.mem_support_iff, Ne, Finsupp.mapRange_apply] exact he.ne_iff' he0 end MapRange /-! ### Declarations about `embDomain` -/ section EmbDomain variable [Zero M] [Zero N] /-- Given `f : α ↪ β` and `v : α →₀ M`, `Finsupp.embDomain f v : β →₀ M` is the finitely supported function whose value at `f a : β` is `v a`. For a `b : β` outside the range of `f`, it is zero. -/ def embDomain (f : α ↪ β) (v : α →₀ M) : β →₀ M where support := v.support.map f toFun a₂ := haveI := Classical.decEq β if h : a₂ ∈ v.support.map f then v (v.support.choose (fun a₁ => f a₁ = a₂) (by rcases Finset.mem_map.1 h with ⟨a, ha, rfl⟩ exact ExistsUnique.intro a ⟨ha, rfl⟩ fun b ⟨_, hb⟩ => f.injective hb)) else 0 mem_support_toFun a₂ := by dsimp split_ifs with h · simp only [h, true_iff_iff, Ne] rw [← not_mem_support_iff, not_not] classical apply Finset.choose_mem · simp only [h, Ne, ne_self_iff_false, not_true_eq_false] @[simp] theorem support_embDomain (f : α ↪ β) (v : α →₀ M) : (embDomain f v).support = v.support.map f := rfl @[simp] theorem embDomain_zero (f : α ↪ β) : (embDomain f 0 : β →₀ M) = 0 := rfl @[simp] theorem embDomain_apply (f : α ↪ β) (v : α →₀ M) (a : α) : embDomain f v (f a) = v a := by classical change dite _ _ _ = _ split_ifs with h <;> rw [Finset.mem_map' f] at h · refine congr_arg (v : α → M) (f.inj' ?_) exact Finset.choose_property (fun a₁ => f a₁ = f a) _ _ · exact (not_mem_support_iff.1 h).symm theorem embDomain_notin_range (f : α ↪ β) (v : α →₀ M) (a : β) (h : a ∉ Set.range f) : embDomain f v a = 0 := by classical refine dif_neg (mt (fun h => ?_) h) rcases Finset.mem_map.1 h with ⟨a, _h, rfl⟩ exact Set.mem_range_self a theorem embDomain_injective (f : α ↪ β) : Function.Injective (embDomain f : (α →₀ M) → β →₀ M) := fun l₁ l₂ h => ext fun a => by simpa only [embDomain_apply] using DFunLike.ext_iff.1 h (f a) @[simp] theorem embDomain_inj {f : α ↪ β} {l₁ l₂ : α →₀ M} : embDomain f l₁ = embDomain f l₂ ↔ l₁ = l₂ := (embDomain_injective f).eq_iff @[simp] theorem embDomain_eq_zero {f : α ↪ β} {l : α →₀ M} : embDomain f l = 0 ↔ l = 0 := (embDomain_injective f).eq_iff' <| embDomain_zero f theorem embDomain_mapRange (f : α ↪ β) (g : M → N) (p : α →₀ M) (hg : g 0 = 0) : embDomain f (mapRange g hg p) = mapRange g hg (embDomain f p) := by ext a by_cases h : a ∈ Set.range f · rcases h with ⟨a', rfl⟩ rw [mapRange_apply, embDomain_apply, embDomain_apply, mapRange_apply] · rw [mapRange_apply, embDomain_notin_range, embDomain_notin_range, ← hg] <;> assumption theorem single_of_embDomain_single (l : α →₀ M) (f : α ↪ β) (a : β) (b : M) (hb : b ≠ 0) (h : l.embDomain f = single a b) : ∃ x, l = single x b ∧ f x = a := by classical have h_map_support : Finset.map f l.support = {a} := by rw [← support_embDomain, h, support_single_ne_zero _ hb] have ha : a ∈ Finset.map f l.support := by simp only [h_map_support, Finset.mem_singleton] rcases Finset.mem_map.1 ha with ⟨c, _hc₁, hc₂⟩ use c constructor · ext d rw [← embDomain_apply f l, h] by_cases h_cases : c = d · simp only [Eq.symm h_cases, hc₂, single_eq_same] · rw [single_apply, single_apply, if_neg, if_neg h_cases] by_contra hfd exact h_cases (f.injective (hc₂.trans hfd)) · exact hc₂ @[simp] theorem embDomain_single (f : α ↪ β) (a : α) (m : M) : embDomain f (single a m) = single (f a) m := by classical ext b by_cases h : b ∈ Set.range f · rcases h with ⟨a', rfl⟩ simp [single_apply] · simp only [embDomain_notin_range, h, single_apply, not_false_iff] rw [if_neg] rintro rfl simp at h end EmbDomain /-! ### Declarations about `zipWith` -/ section ZipWith variable [Zero M] [Zero N] [Zero P] /-- Given finitely supported functions `g₁ : α →₀ M` and `g₂ : α →₀ N` and function `f : M → N → P`, `Finsupp.zipWith f hf g₁ g₂` is the finitely supported function `α →₀ P` satisfying `zipWith f hf g₁ g₂ a = f (g₁ a) (g₂ a)`, which is well-defined when `f 0 0 = 0`. -/ def zipWith (f : M → N → P) (hf : f 0 0 = 0) (g₁ : α →₀ M) (g₂ : α →₀ N) : α →₀ P := onFinset (haveI := Classical.decEq α; g₁.support ∪ g₂.support) (fun a => f (g₁ a) (g₂ a)) fun a (H : f _ _ ≠ 0) => by classical rw [mem_union, mem_support_iff, mem_support_iff, ← not_and_or] rintro ⟨h₁, h₂⟩; rw [h₁, h₂] at H; exact H hf @[simp] theorem zipWith_apply {f : M → N → P} {hf : f 0 0 = 0} {g₁ : α →₀ M} {g₂ : α →₀ N} {a : α} : zipWith f hf g₁ g₂ a = f (g₁ a) (g₂ a) := rfl theorem support_zipWith [D : DecidableEq α] {f : M → N → P} {hf : f 0 0 = 0} {g₁ : α →₀ M} {g₂ : α →₀ N} : (zipWith f hf g₁ g₂).support ⊆ g₁.support ∪ g₂.support := by convert support_onFinset_subset @[simp] theorem zipWith_single_single (f : M → N → P) (hf : f 0 0 = 0) (a : α) (m : M) (n : N) : zipWith f hf (single a m) (single a n) = single a (f m n) := by ext a' rw [zipWith_apply] obtain rfl | ha' := eq_or_ne a a' · rw [single_eq_same, single_eq_same, single_eq_same] · rw [single_eq_of_ne ha', single_eq_of_ne ha', single_eq_of_ne ha', hf] end ZipWith /-! ### Additive monoid structure on `α →₀ M` -/ section AddZeroClass variable [AddZeroClass M] instance instAdd : Add (α →₀ M) := ⟨zipWith (· + ·) (add_zero 0)⟩ @[simp, norm_cast] lemma coe_add (f g : α →₀ M) : ⇑(f + g) = f + g := rfl theorem add_apply (g₁ g₂ : α →₀ M) (a : α) : (g₁ + g₂) a = g₁ a + g₂ a := rfl theorem support_add [DecidableEq α] {g₁ g₂ : α →₀ M} : (g₁ + g₂).support ⊆ g₁.support ∪ g₂.support := support_zipWith theorem support_add_eq [DecidableEq α] {g₁ g₂ : α →₀ M} (h : Disjoint g₁.support g₂.support) : (g₁ + g₂).support = g₁.support ∪ g₂.support := le_antisymm support_zipWith fun a ha => (Finset.mem_union.1 ha).elim (fun ha => by have : a ∉ g₂.support := disjoint_left.1 h ha simp only [mem_support_iff, not_not] at *; simpa only [add_apply, this, add_zero] ) fun ha => by have : a ∉ g₁.support := disjoint_right.1 h ha simp only [mem_support_iff, not_not] at *; simpa only [add_apply, this, zero_add] @[simp] theorem single_add (a : α) (b₁ b₂ : M) : single a (b₁ + b₂) = single a b₁ + single a b₂ := (zipWith_single_single _ _ _ _ _).symm instance instAddZeroClass : AddZeroClass (α →₀ M) := DFunLike.coe_injective.addZeroClass _ coe_zero coe_add instance instIsLeftCancelAdd [IsLeftCancelAdd M] : IsLeftCancelAdd (α →₀ M) where add_left_cancel _ _ _ h := ext fun x => add_left_cancel <| DFunLike.congr_fun h x /-- When ι is finite and M is an AddMonoid, then Finsupp.equivFunOnFinite gives an AddEquiv -/ noncomputable def addEquivFunOnFinite {ι : Type*} [Finite ι] : (ι →₀ M) ≃+ (ι → M) where __ := Finsupp.equivFunOnFinite map_add' _ _ := rfl /-- AddEquiv between (ι →₀ M) and M, when ι has a unique element -/ noncomputable def _root_.AddEquiv.finsuppUnique {ι : Type*} [Unique ι] : (ι →₀ M) ≃+ M where __ := Equiv.finsuppUnique map_add' _ _ := rfl lemma _root_.AddEquiv.finsuppUnique_symm {M : Type*} [AddZeroClass M] (d : M) : AddEquiv.finsuppUnique.symm d = single () d := by rw [Finsupp.unique_single (AddEquiv.finsuppUnique.symm d), Finsupp.unique_single_eq_iff] simp [AddEquiv.finsuppUnique] instance instIsRightCancelAdd [IsRightCancelAdd M] : IsRightCancelAdd (α →₀ M) where add_right_cancel _ _ _ h := ext fun x => add_right_cancel <| DFunLike.congr_fun h x instance instIsCancelAdd [IsCancelAdd M] : IsCancelAdd (α →₀ M) where /-- `Finsupp.single` as an `AddMonoidHom`. See `Finsupp.lsingle` in `LinearAlgebra/Finsupp` for the stronger version as a linear map. -/ @[simps] def singleAddHom (a : α) : M →+ α →₀ M where toFun := single a map_zero' := single_zero a map_add' := single_add a /-- Evaluation of a function `f : α →₀ M` at a point as an additive monoid homomorphism. See `Finsupp.lapply` in `LinearAlgebra/Finsupp` for the stronger version as a linear map. -/ @[simps apply] def applyAddHom (a : α) : (α →₀ M) →+ M where toFun g := g a map_zero' := zero_apply map_add' _ _ := add_apply _ _ _ /-- Coercion from a `Finsupp` to a function type is an `AddMonoidHom`. -/ @[simps] noncomputable def coeFnAddHom : (α →₀ M) →+ α → M where toFun := (⇑) map_zero' := coe_zero map_add' := coe_add theorem update_eq_single_add_erase (f : α →₀ M) (a : α) (b : M) : f.update a b = single a b + f.erase a := by classical ext j rcases eq_or_ne a j with (rfl | h) · simp · simp [Function.update_noteq h.symm, single_apply, h, erase_ne, h.symm] theorem update_eq_erase_add_single (f : α →₀ M) (a : α) (b : M) : f.update a b = f.erase a + single a b := by classical ext j rcases eq_or_ne a j with (rfl | h) · simp · simp [Function.update_noteq h.symm, single_apply, h, erase_ne, h.symm] theorem single_add_erase (a : α) (f : α →₀ M) : single a (f a) + f.erase a = f := by rw [← update_eq_single_add_erase, update_self] theorem erase_add_single (a : α) (f : α →₀ M) : f.erase a + single a (f a) = f := by rw [← update_eq_erase_add_single, update_self] @[simp] theorem erase_add (a : α) (f f' : α →₀ M) : erase a (f + f') = erase a f + erase a f' := by ext s; by_cases hs : s = a · rw [hs, add_apply, erase_same, erase_same, erase_same, add_zero] rw [add_apply, erase_ne hs, erase_ne hs, erase_ne hs, add_apply] /-- `Finsupp.erase` as an `AddMonoidHom`. -/ @[simps] def eraseAddHom (a : α) : (α →₀ M) →+ α →₀ M where toFun := erase a map_zero' := erase_zero a map_add' := erase_add a @[elab_as_elim] protected theorem induction {p : (α →₀ M) → Prop} (f : α →₀ M) (h0 : p 0) (ha : ∀ (a b) (f : α →₀ M), a ∉ f.support → b ≠ 0 → p f → p (single a b + f)) : p f := suffices ∀ (s) (f : α →₀ M), f.support = s → p f from this _ _ rfl fun s => Finset.cons_induction_on s (fun f hf => by rwa [support_eq_empty.1 hf]) fun a s has ih f hf => by suffices p (single a (f a) + f.erase a) by rwa [single_add_erase] at this classical apply ha · rw [support_erase, mem_erase] exact fun H => H.1 rfl · rw [← mem_support_iff, hf] exact mem_cons_self _ _ · apply ih _ _ rw [support_erase, hf, Finset.erase_cons] theorem induction₂ {p : (α →₀ M) → Prop} (f : α →₀ M) (h0 : p 0) (ha : ∀ (a b) (f : α →₀ M), a ∉ f.support → b ≠ 0 → p f → p (f + single a b)) : p f := suffices ∀ (s) (f : α →₀ M), f.support = s → p f from this _ _ rfl fun s => Finset.cons_induction_on s (fun f hf => by rwa [support_eq_empty.1 hf]) fun a s has ih f hf => by suffices p (f.erase a + single a (f a)) by rwa [erase_add_single] at this classical apply ha · rw [support_erase, mem_erase] exact fun H => H.1 rfl · rw [← mem_support_iff, hf] exact mem_cons_self _ _ · apply ih _ _ rw [support_erase, hf, Finset.erase_cons] theorem induction_linear {p : (α →₀ M) → Prop} (f : α →₀ M) (h0 : p 0) (hadd : ∀ f g : α →₀ M, p f → p g → p (f + g)) (hsingle : ∀ a b, p (single a b)) : p f := induction₂ f h0 fun _a _b _f _ _ w => hadd _ _ w (hsingle _ _) @[simp] theorem add_closure_setOf_eq_single : AddSubmonoid.closure { f : α →₀ M | ∃ a b, f = single a b } = ⊤ := top_unique fun x _hx => Finsupp.induction x (AddSubmonoid.zero_mem _) fun a b _f _ha _hb hf => AddSubmonoid.add_mem _ (AddSubmonoid.subset_closure <| ⟨a, b, rfl⟩) hf /-- If two additive homomorphisms from `α →₀ M` are equal on each `single a b`, then they are equal. -/ theorem addHom_ext [AddZeroClass N] ⦃f g : (α →₀ M) →+ N⦄ (H : ∀ x y, f (single x y) = g (single x y)) : f = g := by refine AddMonoidHom.eq_of_eqOn_denseM add_closure_setOf_eq_single ?_ rintro _ ⟨x, y, rfl⟩ apply H /-- If two additive homomorphisms from `α →₀ M` are equal on each `single a b`, then they are equal. We formulate this using equality of `AddMonoidHom`s so that `ext` tactic can apply a type-specific extensionality lemma after this one. E.g., if the fiber `M` is `ℕ` or `ℤ`, then it suffices to verify `f (single a 1) = g (single a 1)`. -/ @[ext high] theorem addHom_ext' [AddZeroClass N] ⦃f g : (α →₀ M) →+ N⦄ (H : ∀ x, f.comp (singleAddHom x) = g.comp (singleAddHom x)) : f = g := addHom_ext fun x => DFunLike.congr_fun (H x) theorem mulHom_ext [MulOneClass N] ⦃f g : Multiplicative (α →₀ M) →* N⦄ (H : ∀ x y, f (Multiplicative.ofAdd <| single x y) = g (Multiplicative.ofAdd <| single x y)) : f = g := MonoidHom.ext <| DFunLike.congr_fun <| by have := @addHom_ext α M (Additive N) _ _ (MonoidHom.toAdditive'' f) (MonoidHom.toAdditive'' g) H ext rw [DFunLike.ext_iff] at this apply this @[ext] theorem mulHom_ext' [MulOneClass N] {f g : Multiplicative (α →₀ M) →* N} (H : ∀ x, f.comp (AddMonoidHom.toMultiplicative (singleAddHom x)) = g.comp (AddMonoidHom.toMultiplicative (singleAddHom x))) : f = g := mulHom_ext fun x => DFunLike.congr_fun (H x) theorem mapRange_add [AddZeroClass N] {f : M → N} {hf : f 0 = 0} (hf' : ∀ x y, f (x + y) = f x + f y) (v₁ v₂ : α →₀ M) : mapRange f hf (v₁ + v₂) = mapRange f hf v₁ + mapRange f hf v₂ := ext fun _ => by simp only [hf', add_apply, mapRange_apply] theorem mapRange_add' [AddZeroClass N] [FunLike β M N] [AddMonoidHomClass β M N] {f : β} (v₁ v₂ : α →₀ M) : mapRange f (map_zero f) (v₁ + v₂) = mapRange f (map_zero f) v₁ + mapRange f (map_zero f) v₂ := mapRange_add (map_add f) v₁ v₂ /-- Bundle `Finsupp.embDomain f` as an additive map from `α →₀ M` to `β →₀ M`. -/ @[simps] def embDomain.addMonoidHom (f : α ↪ β) : (α →₀ M) →+ β →₀ M where toFun v := embDomain f v map_zero' := by simp map_add' v w := by ext b by_cases h : b ∈ Set.range f · rcases h with ⟨a, rfl⟩ simp · simp only [Set.mem_range, not_exists, coe_add, Pi.add_apply, embDomain_notin_range _ _ _ h, add_zero] @[simp] theorem embDomain_add (f : α ↪ β) (v w : α →₀ M) : embDomain f (v + w) = embDomain f v + embDomain f w := (embDomain.addMonoidHom f).map_add v w end AddZeroClass section AddMonoid variable [AddMonoid M] /-- Note the general `SMul` instance for `Finsupp` doesn't apply as `ℕ` is not distributive unless `β i`'s addition is commutative. -/ instance instNatSMul : SMul ℕ (α →₀ M) := ⟨fun n v => v.mapRange (n • ·) (nsmul_zero _)⟩ instance instAddMonoid : AddMonoid (α →₀ M) := DFunLike.coe_injective.addMonoid _ coe_zero coe_add fun _ _ => rfl end AddMonoid instance instAddCommMonoid [AddCommMonoid M] : AddCommMonoid (α →₀ M) := --TODO: add reference to library note in PR #7432 { DFunLike.coe_injective.addCommMonoid (↑) coe_zero coe_add (fun _ _ => rfl) with toAddMonoid := Finsupp.instAddMonoid } instance instNeg [NegZeroClass G] : Neg (α →₀ G) := ⟨mapRange Neg.neg neg_zero⟩ @[simp, norm_cast] lemma coe_neg [NegZeroClass G] (g : α →₀ G) : ⇑(-g) = -g := rfl theorem neg_apply [NegZeroClass G] (g : α →₀ G) (a : α) : (-g) a = -g a := rfl theorem mapRange_neg [NegZeroClass G] [NegZeroClass H] {f : G → H} {hf : f 0 = 0} (hf' : ∀ x, f (-x) = -f x) (v : α →₀ G) : mapRange f hf (-v) = -mapRange f hf v := ext fun _ => by simp only [hf', neg_apply, mapRange_apply] theorem mapRange_neg' [AddGroup G] [SubtractionMonoid H] [FunLike β G H] [AddMonoidHomClass β G H] {f : β} (v : α →₀ G) : mapRange f (map_zero f) (-v) = -mapRange f (map_zero f) v := mapRange_neg (map_neg f) v instance instSub [SubNegZeroMonoid G] : Sub (α →₀ G) := ⟨zipWith Sub.sub (sub_zero _)⟩ @[simp, norm_cast] lemma coe_sub [SubNegZeroMonoid G] (g₁ g₂ : α →₀ G) : ⇑(g₁ - g₂) = g₁ - g₂ := rfl theorem sub_apply [SubNegZeroMonoid G] (g₁ g₂ : α →₀ G) (a : α) : (g₁ - g₂) a = g₁ a - g₂ a := rfl theorem mapRange_sub [SubNegZeroMonoid G] [SubNegZeroMonoid H] {f : G → H} {hf : f 0 = 0} (hf' : ∀ x y, f (x - y) = f x - f y) (v₁ v₂ : α →₀ G) : mapRange f hf (v₁ - v₂) = mapRange f hf v₁ - mapRange f hf v₂ := ext fun _ => by simp only [hf', sub_apply, mapRange_apply] theorem mapRange_sub' [AddGroup G] [SubtractionMonoid H] [FunLike β G H] [AddMonoidHomClass β G H] {f : β} (v₁ v₂ : α →₀ G) : mapRange f (map_zero f) (v₁ - v₂) = mapRange f (map_zero f) v₁ - mapRange f (map_zero f) v₂ := mapRange_sub (map_sub f) v₁ v₂ /-- Note the general `SMul` instance for `Finsupp` doesn't apply as `ℤ` is not distributive unless `β i`'s addition is commutative. -/ instance instIntSMul [AddGroup G] : SMul ℤ (α →₀ G) := ⟨fun n v => v.mapRange (n • ·) (zsmul_zero _)⟩ instance instAddGroup [AddGroup G] : AddGroup (α →₀ G) := --TODO: add reference to library note in PR #7432 { DFunLike.coe_injective.addGroup (↑) coe_zero coe_add coe_neg coe_sub (fun _ _ => rfl) fun _ _ => rfl with toAddMonoid := Finsupp.instAddMonoid } instance instAddCommGroup [AddCommGroup G] : AddCommGroup (α →₀ G) := --TODO: add reference to library note in PR #7432 { DFunLike.coe_injective.addCommGroup (↑) coe_zero coe_add coe_neg coe_sub (fun _ _ => rfl) fun _ _ => rfl with toAddGroup := Finsupp.instAddGroup } theorem single_add_single_eq_single_add_single [AddCommMonoid M] {k l m n : α} {u v : M} (hu : u ≠ 0) (hv : v ≠ 0) : single k u + single l v = single m u + single n v ↔ (k = m ∧ l = n) ∨ (u = v ∧ k = n ∧ l = m) ∨ (u + v = 0 ∧ k = l ∧ m = n) := by classical simp_rw [DFunLike.ext_iff, coe_add, single_eq_pi_single, ← funext_iff] exact Pi.single_add_single_eq_single_add_single hu hv @[simp] theorem support_neg [AddGroup G] (f : α →₀ G) : support (-f) = support f := Finset.Subset.antisymm support_mapRange (calc support f = support (- -f) := congr_arg support (neg_neg _).symm _ ⊆ support (-f) := support_mapRange ) theorem support_sub [DecidableEq α] [AddGroup G] {f g : α →₀ G} : support (f - g) ⊆ support f ∪ support g := by rw [sub_eq_add_neg, ← support_neg g] exact support_add theorem erase_eq_sub_single [AddGroup G] (f : α →₀ G) (a : α) : f.erase a = f - single a (f a) := by ext a' rcases eq_or_ne a a' with (rfl | h) · simp · simp [erase_ne h.symm, single_eq_of_ne h] theorem update_eq_sub_add_single [AddGroup G] (f : α →₀ G) (a : α) (b : G) : f.update a b = f - single a (f a) + single a b := by rw [update_eq_erase_add_single, erase_eq_sub_single] end Finsupp
Data\Finsupp\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.Finsupp.ToDFinsupp import Mathlib.Data.DFinsupp.Encodable /-! # `Encodable` and `Countable` instances for `α →₀ β` In this file we provide instances for `Encodable (α →₀ β)` and `Countable (α →₀ β)`. -/ instance {α β : Type*} [Encodable α] [Encodable β] [Zero β] [∀ x : β, Decidable (x ≠ 0)] : Encodable (α →₀ β) := letI : DecidableEq α := Encodable.decidableEqOfEncodable _ .ofEquiv _ finsuppEquivDFinsupp instance {α β : Type*} [Countable α] [Countable β] [Zero β] : Countable (α →₀ β) := by classical exact .of_equiv _ finsuppEquivDFinsupp.symm
Data\Finsupp\Fin.lean
/- Copyright (c) 2021 Ivan Sadofschi Costa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Ivan Sadofschi Costa -/ import Mathlib.Data.Finsupp.Defs /-! # `cons` and `tail` for maps `Fin n →₀ M` We interpret maps `Fin n →₀ M` as `n`-tuples of elements of `M`, We define the following operations: * `Finsupp.tail` : the tail of a map `Fin (n + 1) →₀ M`, i.e., its last `n` entries; * `Finsupp.cons` : adding an element at the beginning of an `n`-tuple, to get an `n + 1`-tuple; In this context, we prove some usual properties of `tail` and `cons`, analogous to those of `Data.Fin.Tuple.Basic`. -/ noncomputable section namespace Finsupp variable {n : ℕ} (i : Fin n) {M : Type*} [Zero M] (y : M) (t : Fin (n + 1) →₀ M) (s : Fin n →₀ M) /-- `tail` for maps `Fin (n + 1) →₀ M`. See `Fin.tail` for more details. -/ def tail (s : Fin (n + 1) →₀ M) : Fin n →₀ M := Finsupp.equivFunOnFinite.symm (Fin.tail s) /-- `cons` for maps `Fin n →₀ M`. See `Fin.cons` for more details. -/ def cons (y : M) (s : Fin n →₀ M) : Fin (n + 1) →₀ M := Finsupp.equivFunOnFinite.symm (Fin.cons y s : Fin (n + 1) → M) theorem tail_apply : tail t i = t i.succ := rfl @[simp] theorem cons_zero : cons y s 0 = y := rfl @[simp] theorem cons_succ : cons y s i.succ = s i := -- Porting note: was Fin.cons_succ _ _ _ rfl @[simp] theorem tail_cons : tail (cons y s) = s := ext fun k => by simp only [tail_apply, cons_succ] @[simp] theorem cons_tail : cons (t 0) (tail t) = t := by ext a by_cases c_a : a = 0 · rw [c_a, cons_zero] · rw [← Fin.succ_pred a c_a, cons_succ, ← tail_apply] @[simp] theorem cons_zero_zero : cons 0 (0 : Fin n →₀ M) = 0 := by ext a by_cases c : a = 0 · simp [c] · rw [← Fin.succ_pred a c, cons_succ] simp variable {s} {y} theorem cons_ne_zero_of_left (h : y ≠ 0) : cons y s ≠ 0 := by contrapose! h with c rw [← cons_zero y s, c, Finsupp.coe_zero, Pi.zero_apply] theorem cons_ne_zero_of_right (h : s ≠ 0) : cons y s ≠ 0 := by contrapose! h with c ext a simp [← cons_succ a y s, c] theorem cons_ne_zero_iff : cons y s ≠ 0 ↔ y ≠ 0 ∨ s ≠ 0 := by refine ⟨fun h => ?_, fun h => h.casesOn cons_ne_zero_of_left cons_ne_zero_of_right⟩ refine imp_iff_not_or.1 fun h' c => h ?_ rw [h', c, Finsupp.cons_zero_zero] lemma cons_support : (s.cons y).support ⊆ insert 0 (s.support.map (Fin.succEmb n)) := by intro i hi suffices i = 0 ∨ ∃ a, ¬s a = 0 ∧ a.succ = i by simpa apply (Fin.eq_zero_or_eq_succ i).imp id (Exists.imp _) rintro i rfl simpa [Finsupp.mem_support_iff] using hi end Finsupp
Data\Finsupp\Fintype.lean
/- Copyright (c) 2022 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen, Alex J. Best -/ import Mathlib.Data.Finsupp.Defs import Mathlib.Data.Fintype.Basic /-! # Finiteness and infiniteness of `Finsupp` Some lemmas on the combination of `Finsupp`, `Fintype` and `Infinite`. -/ noncomputable instance Finsupp.fintype {ι π : Sort _} [DecidableEq ι] [Zero π] [Fintype ι] [Fintype π] : Fintype (ι →₀ π) := Fintype.ofEquiv _ Finsupp.equivFunOnFinite.symm instance Finsupp.infinite_of_left {ι π : Sort _} [Nontrivial π] [Zero π] [Infinite ι] : Infinite (ι →₀ π) := let ⟨_, hm⟩ := exists_ne (0 : π) Infinite.of_injective _ <| Finsupp.single_left_injective hm instance Finsupp.infinite_of_right {ι π : Sort _} [Infinite π] [Zero π] [Nonempty ι] : Infinite (ι →₀ π) := Infinite.of_injective (fun i => Finsupp.single (Classical.arbitrary ι) i) (Finsupp.single_injective (Classical.arbitrary ι))
Data\Finsupp\Indicator.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.Data.Finsupp.Defs /-! # Building finitely supported functions off finsets This file defines `Finsupp.indicator` to help create finsupps from finsets. ## Main declarations * `Finsupp.indicator`: Turns a map from a `Finset` into a `Finsupp` from the entire type. -/ noncomputable section open Finset Function variable {ι α : Type*} namespace Finsupp variable [Zero α] {s : Finset ι} (f : ∀ i ∈ s, α) {i : ι} /-- Create an element of `ι →₀ α` from a finset `s` and a function `f` defined on this finset. -/ def indicator (s : Finset ι) (f : ∀ i ∈ s, α) : ι →₀ α where toFun i := haveI := Classical.decEq ι if H : i ∈ s then f i H else 0 support := haveI := Classical.decEq α (s.attach.filter fun i : s => f i.1 i.2 ≠ 0).map (Embedding.subtype _) mem_support_toFun i := by classical simp theorem indicator_of_mem (hi : i ∈ s) (f : ∀ i ∈ s, α) : indicator s f i = f i hi := @dif_pos _ (id _) hi _ _ _ theorem indicator_of_not_mem (hi : i ∉ s) (f : ∀ i ∈ s, α) : indicator s f i = 0 := @dif_neg _ (id _) hi _ _ _ variable (s i) @[simp] theorem indicator_apply [DecidableEq ι] : indicator s f i = if hi : i ∈ s then f i hi else 0 := by simp only [indicator, ne_eq, coe_mk] congr theorem indicator_injective : Injective fun f : ∀ i ∈ s, α => indicator s f := by intro a b h ext i hi rw [← indicator_of_mem hi a, ← indicator_of_mem hi b] exact DFunLike.congr_fun h i theorem support_indicator_subset : ((indicator s f).support : Set ι) ⊆ s := by intro i hi rw [mem_coe, mem_support_iff] at hi by_contra h exact hi (indicator_of_not_mem h _) lemma single_eq_indicator (b : α) : single i b = indicator {i} (fun _ _ => b) := by classical ext j simp [single_apply, indicator_apply, @eq_comm _ j] end Finsupp
Data\Finsupp\Interval.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.Data.Finset.Finsupp import Mathlib.Data.Finsupp.Order import Mathlib.Order.Interval.Finset.Basic /-! # Finite intervals of finitely supported functions This file provides the `LocallyFiniteOrder` instance for `ι →₀ α` when `α` itself is locally finite and calculates the cardinality of its finite intervals. ## Main declarations * `Finsupp.rangeSingleton`: Postcomposition with `Singleton.singleton` on `Finset` as a `Finsupp`. * `Finsupp.rangeIcc`: Postcomposition with `Finset.Icc` as a `Finsupp`. Both these definitions use the fact that `0 = {0}` to ensure that the resulting function is finitely supported. -/ noncomputable section open Finset Finsupp Function open scoped Classical open Pointwise variable {ι α : Type*} namespace Finsupp section RangeSingleton variable [Zero α] {f : ι →₀ α} {i : ι} {a : α} /-- Pointwise `Singleton.singleton` bundled as a `Finsupp`. -/ @[simps] def rangeSingleton (f : ι →₀ α) : ι →₀ Finset α where toFun i := {f i} support := f.support mem_support_toFun i := by rw [← not_iff_not, not_mem_support_iff, not_ne_iff] exact singleton_injective.eq_iff.symm theorem mem_rangeSingleton_apply_iff : a ∈ f.rangeSingleton i ↔ a = f i := mem_singleton end RangeSingleton section RangeIcc variable [Zero α] [PartialOrder α] [LocallyFiniteOrder α] {f g : ι →₀ α} {i : ι} {a : α} /-- Pointwise `Finset.Icc` bundled as a `Finsupp`. -/ @[simps toFun] def rangeIcc (f g : ι →₀ α) : ι →₀ Finset α where toFun i := Icc (f i) (g i) support := -- Porting note: Not needed (due to open scoped Classical), in mathlib3 too -- haveI := Classical.decEq ι f.support ∪ g.support mem_support_toFun i := by rw [mem_union, ← not_iff_not, not_or, not_mem_support_iff, not_mem_support_iff, not_ne_iff] exact Icc_eq_singleton_iff.symm -- Porting note: Added as alternative to rangeIcc_toFun to be used in proof of card_Icc lemma coe_rangeIcc (f g : ι →₀ α) : rangeIcc f g i = Icc (f i) (g i) := rfl @[simp] theorem rangeIcc_support (f g : ι →₀ α) : (rangeIcc f g).support = f.support ∪ g.support := rfl theorem mem_rangeIcc_apply_iff : a ∈ f.rangeIcc g i ↔ f i ≤ a ∧ a ≤ g i := mem_Icc end RangeIcc section PartialOrder variable [PartialOrder α] [Zero α] [LocallyFiniteOrder α] (f g : ι →₀ α) instance instLocallyFiniteOrder : LocallyFiniteOrder (ι →₀ α) := -- Porting note: Not needed (due to open scoped Classical), in mathlib3 too -- haveI := Classical.decEq ι -- haveI := Classical.decEq α LocallyFiniteOrder.ofIcc (ι →₀ α) (fun f g => (f.support ∪ g.support).finsupp <| f.rangeIcc g) fun f g x => by refine (mem_finsupp_iff_of_support_subset <| Finset.subset_of_eq <| rangeIcc_support _ _).trans ?_ simp_rw [mem_rangeIcc_apply_iff] exact forall_and theorem Icc_eq : Icc f g = (f.support ∪ g.support).finsupp (f.rangeIcc g) := rfl -- Porting note: removed [DecidableEq ι] theorem card_Icc : (Icc f g).card = ∏ i ∈ f.support ∪ g.support, (Icc (f i) (g i)).card := by simp_rw [Icc_eq, card_finsupp, coe_rangeIcc] -- Porting note: removed [DecidableEq ι] 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] -- Porting note: removed [DecidableEq ι] 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] -- Porting note: removed [DecidableEq ι] 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 [Lattice α] [Zero α] [LocallyFiniteOrder α] (f g : ι →₀ α) -- Porting note: removed [DecidableEq ι] 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 [CanonicallyOrderedAddCommMonoid α] [LocallyFiniteOrder α] variable (f : ι →₀ α) theorem card_Iic : (Iic f).card = ∏ i ∈ f.support, (Iic (f i)).card := by classical simp_rw [Iic_eq_Icc, card_Icc, Finsupp.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 Finsupp
Data\Finsupp\Lex.lean
/- Copyright (c) 2022 Damiano Testa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Damiano Testa -/ import Mathlib.Data.Finsupp.Order import Mathlib.Data.DFinsupp.Lex import Mathlib.Data.Finsupp.ToDFinsupp /-! # Lexicographic order on finitely supported functions This file defines the lexicographic order on `Finsupp`. -/ variable {α N : Type*} namespace Finsupp section NHasZero variable [Zero N] /-- `Finsupp.Lex r s` is the lexicographic relation on `α →₀ N`, where `α` is ordered by `r`, and `N` is ordered by `s`. The type synonym `Lex (α →₀ N)` has an order given by `Finsupp.Lex (· < ·) (· < ·)`. -/ protected def Lex (r : α → α → Prop) (s : N → N → Prop) (x y : α →₀ N) : Prop := Pi.Lex r s x y -- Porting note: Added `_root_` to better align with Lean 3. theorem _root_.Pi.lex_eq_finsupp_lex {r : α → α → Prop} {s : N → N → Prop} (a b : α →₀ N) : Pi.Lex r s a b = Finsupp.Lex r s a b := rfl theorem lex_def {r : α → α → Prop} {s : N → N → Prop} {a b : α →₀ N} : Finsupp.Lex r s a b ↔ ∃ j, (∀ d, r d j → a d = b d) ∧ s (a j) (b j) := Iff.rfl theorem lex_eq_invImage_dfinsupp_lex (r : α → α → Prop) (s : N → N → Prop) : Finsupp.Lex r s = InvImage (DFinsupp.Lex r fun _ ↦ s) toDFinsupp := rfl instance [LT α] [LT N] : LT (Lex (α →₀ N)) := ⟨fun f g ↦ Finsupp.Lex (· < ·) (· < ·) (ofLex f) (ofLex g)⟩ theorem lex_lt_of_lt_of_preorder [Preorder N] (r) [IsStrictOrder α r] {x y : α →₀ N} (hlt : x < y) : ∃ i, (∀ j, r j i → x j ≤ y j ∧ y j ≤ x j) ∧ x i < y i := DFinsupp.lex_lt_of_lt_of_preorder r (id hlt : x.toDFinsupp < y.toDFinsupp) theorem lex_lt_of_lt [PartialOrder N] (r) [IsStrictOrder α r] {x y : α →₀ N} (hlt : x < y) : Pi.Lex r (· < ·) x y := DFinsupp.lex_lt_of_lt r (id hlt : x.toDFinsupp < y.toDFinsupp) instance Lex.isStrictOrder [LinearOrder α] [PartialOrder N] : IsStrictOrder (Lex (α →₀ N)) (· < ·) := let i : IsStrictOrder (Lex (α → N)) (· < ·) := Pi.Lex.isStrictOrder { irrefl := toLex.surjective.forall.2 fun _ ↦ @irrefl _ _ i.toIsIrrefl _ trans := toLex.surjective.forall₃.2 fun _ _ _ ↦ @trans _ _ i.toIsTrans _ _ _ } variable [LinearOrder α] /-- The partial order on `Finsupp`s obtained by the lexicographic ordering. See `Finsupp.Lex.linearOrder` for a proof that this partial order is in fact linear. -/ instance Lex.partialOrder [PartialOrder N] : PartialOrder (Lex (α →₀ N)) where lt := (· < ·) le x y := ⇑(ofLex x) = ⇑(ofLex y) ∨ x < y __ := PartialOrder.lift (fun x : Lex (α →₀ N) ↦ toLex (⇑(ofLex x))) (DFunLike.coe_injective (F := Finsupp α N)) /-- The linear order on `Finsupp`s obtained by the lexicographic ordering. -/ instance Lex.linearOrder [LinearOrder N] : LinearOrder (Lex (α →₀ N)) where lt := (· < ·) le := (· ≤ ·) __ := LinearOrder.lift' (toLex ∘ toDFinsupp ∘ ofLex) finsuppEquivDFinsupp.injective variable [PartialOrder N] theorem toLex_monotone : Monotone (@toLex (α →₀ N)) := fun a b h ↦ DFinsupp.toLex_monotone (id h : ∀ i, ofLex (toDFinsupp a) i ≤ ofLex (toDFinsupp b) i) theorem lt_of_forall_lt_of_lt (a b : Lex (α →₀ N)) (i : α) : (∀ j < i, ofLex a j = ofLex b j) → ofLex a i < ofLex b i → a < b := fun h1 h2 ↦ ⟨i, h1, h2⟩ end NHasZero section Covariants variable [LinearOrder α] [AddMonoid N] [LinearOrder N] /-! 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 (α →₀ N)` may fail to be monotone, when it is "just" monotone on `N`. See `Counterexamples/ZeroDivisorsInAddMonoidAlgebras.lean` for a counterexample. -/ section Left variable [CovariantClass N N (· + ·) (· < ·)] instance Lex.covariantClass_lt_left : CovariantClass (Lex (α →₀ N)) (Lex (α →₀ N)) (· + ·) (· < ·) := ⟨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 (α →₀ N)) (Lex (α →₀ N)) (· + ·) (· ≤ ·) := covariantClass_le_of_lt _ _ _ end Left section Right variable [CovariantClass N N (Function.swap (· + ·)) (· < ·)] instance Lex.covariantClass_lt_right : CovariantClass (Lex (α →₀ N)) (Lex (α →₀ N)) (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 (α →₀ N)) (Lex (α →₀ N)) (Function.swap (· + ·)) (· ≤ ·) := covariantClass_le_of_lt _ _ _ end Right end Covariants section OrderedAddMonoid variable [LinearOrder α] instance Lex.orderBot [CanonicallyOrderedAddCommMonoid N] : OrderBot (Lex (α →₀ N)) where bot := 0 bot_le _ := Finsupp.toLex_monotone bot_le noncomputable instance Lex.orderedAddCancelCommMonoid [OrderedCancelAddCommMonoid N] : OrderedCancelAddCommMonoid (Lex (α →₀ N)) where add_le_add_left _ _ h _ := add_le_add_left (α := Lex (α → N)) h _ le_of_add_le_add_left _ _ _ := le_of_add_le_add_left (α := Lex (α → N)) noncomputable instance Lex.orderedAddCommGroup [OrderedAddCommGroup N] : OrderedAddCommGroup (Lex (α →₀ N)) where add_le_add_left _ _ := add_le_add_left noncomputable instance Lex.linearOrderedCancelAddCommMonoid [LinearOrderedCancelAddCommMonoid N] : LinearOrderedCancelAddCommMonoid (Lex (α →₀ N)) where __ : LinearOrder (Lex (α →₀ N)) := inferInstance __ : OrderedCancelAddCommMonoid (Lex (α →₀ N)) := inferInstance noncomputable instance Lex.linearOrderedAddCommGroup [LinearOrderedAddCommGroup N] : LinearOrderedAddCommGroup (Lex (α →₀ N)) where __ : LinearOrder (Lex (α →₀ N)) := inferInstance add_le_add_left _ _ := add_le_add_left end OrderedAddMonoid end Finsupp
Data\Finsupp\Multiset.lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import Mathlib.Data.Finsupp.Basic import Mathlib.Data.Finsupp.Order /-! # Equivalence between `Multiset` and `ℕ`-valued finitely supported functions This defines `Finsupp.toMultiset` the equivalence between `α →₀ ℕ` and `Multiset α`, along with `Multiset.toFinsupp` the reverse equivalence and `Finsupp.orderIsoMultiset` (the equivalence promoted to an order isomorphism). -/ open Finset variable {α β ι : Type*} namespace Finsupp /-- Given `f : α →₀ ℕ`, `f.toMultiset` is the multiset with multiplicities given by the values of `f` on the elements of `α`. We define this function as an `AddMonoidHom`. Under the additional assumption of `[DecidableEq α]`, this is available as `Multiset.toFinsupp : Multiset α ≃+ (α →₀ ℕ)`; the two declarations are separate as this assumption is only needed for one direction. -/ def toMultiset : (α →₀ ℕ) →+ Multiset α where toFun f := Finsupp.sum f fun a n => n • {a} -- Porting note: times out if h is not specified map_add' _f _g := sum_add_index' (h := fun a n => n • ({a} : Multiset α)) (fun _ ↦ zero_nsmul _) (fun _ ↦ add_nsmul _) map_zero' := sum_zero_index theorem toMultiset_zero : toMultiset (0 : α →₀ ℕ) = 0 := rfl theorem toMultiset_add (m n : α →₀ ℕ) : toMultiset (m + n) = toMultiset m + toMultiset n := toMultiset.map_add m n theorem toMultiset_apply (f : α →₀ ℕ) : toMultiset f = f.sum fun a n => n • {a} := rfl @[simp] theorem toMultiset_single (a : α) (n : ℕ) : toMultiset (single a n) = n • {a} := by rw [toMultiset_apply, sum_single_index]; apply zero_nsmul theorem toMultiset_sum {f : ι → α →₀ ℕ} (s : Finset ι) : Finsupp.toMultiset (∑ i ∈ s, f i) = ∑ i ∈ s, Finsupp.toMultiset (f i) := map_sum Finsupp.toMultiset _ _ theorem toMultiset_sum_single (s : Finset ι) (n : ℕ) : Finsupp.toMultiset (∑ i ∈ s, single i n) = n • s.val := by simp_rw [toMultiset_sum, Finsupp.toMultiset_single, sum_nsmul, sum_multiset_singleton] @[simp] theorem card_toMultiset (f : α →₀ ℕ) : Multiset.card (toMultiset f) = f.sum fun _ => id := by simp [toMultiset_apply, map_finsupp_sum, Function.id_def] theorem toMultiset_map (f : α →₀ ℕ) (g : α → β) : f.toMultiset.map g = toMultiset (f.mapDomain g) := by refine f.induction ?_ ?_ · rw [toMultiset_zero, Multiset.map_zero, mapDomain_zero, toMultiset_zero] · intro a n f _ _ ih rw [toMultiset_add, Multiset.map_add, ih, mapDomain_add, mapDomain_single, toMultiset_single, toMultiset_add, toMultiset_single, ← Multiset.coe_mapAddMonoidHom, (Multiset.mapAddMonoidHom g).map_nsmul] rfl @[to_additive (attr := simp)] theorem prod_toMultiset [CommMonoid α] (f : α →₀ ℕ) : f.toMultiset.prod = f.prod fun a n => a ^ n := by refine f.induction ?_ ?_ · rw [toMultiset_zero, Multiset.prod_zero, Finsupp.prod_zero_index] · intro a n f _ _ ih rw [toMultiset_add, Multiset.prod_add, ih, toMultiset_single, Multiset.prod_nsmul, Finsupp.prod_add_index' pow_zero pow_add, Finsupp.prod_single_index, Multiset.prod_singleton] exact pow_zero a @[simp] theorem toFinset_toMultiset [DecidableEq α] (f : α →₀ ℕ) : f.toMultiset.toFinset = f.support := by refine f.induction ?_ ?_ · rw [toMultiset_zero, Multiset.toFinset_zero, support_zero] · intro a n f ha hn ih rw [toMultiset_add, Multiset.toFinset_add, ih, toMultiset_single, support_add_eq, support_single_ne_zero _ hn, Multiset.toFinset_nsmul _ _ hn, Multiset.toFinset_singleton] refine Disjoint.mono_left support_single_subset ?_ rwa [Finset.disjoint_singleton_left] @[simp] theorem count_toMultiset [DecidableEq α] (f : α →₀ ℕ) (a : α) : (toMultiset f).count a = f a := calc (toMultiset f).count a = Finsupp.sum f (fun x n => (n • {x} : Multiset α).count a) := by rw [toMultiset_apply]; exact map_sum (Multiset.countAddMonoidHom a) _ f.support _ = f.sum fun x n => n * ({x} : Multiset α).count a := by simp only [Multiset.count_nsmul] _ = f a * ({a} : Multiset α).count a := sum_eq_single _ (fun a' _ H => by simp only [Multiset.count_singleton, if_false, H.symm, mul_zero]) (fun _ => zero_mul _) _ = f a := by rw [Multiset.count_singleton_self, mul_one] theorem toMultiset_sup [DecidableEq α] (f g : α →₀ ℕ) : toMultiset (f ⊔ g) = toMultiset f ∪ toMultiset g := by ext simp_rw [Multiset.count_union, Finsupp.count_toMultiset, Finsupp.sup_apply, sup_eq_max] theorem toMultiset_inf [DecidableEq α] (f g : α →₀ ℕ) : toMultiset (f ⊓ g) = toMultiset f ∩ toMultiset g := by ext simp_rw [Multiset.count_inter, Finsupp.count_toMultiset, Finsupp.inf_apply, inf_eq_min] @[simp] theorem mem_toMultiset (f : α →₀ ℕ) (i : α) : i ∈ toMultiset f ↔ i ∈ f.support := by classical rw [← Multiset.count_ne_zero, Finsupp.count_toMultiset, Finsupp.mem_support_iff] end Finsupp namespace Multiset variable [DecidableEq α] /-- Given a multiset `s`, `s.toFinsupp` returns the finitely supported function on `ℕ` given by the multiplicities of the elements of `s`. -/ @[simps symm_apply] def toFinsupp : Multiset α ≃+ (α →₀ ℕ) where toFun s := ⟨s.toFinset, fun a => s.count a, fun a => by simp⟩ invFun f := Finsupp.toMultiset f map_add' s t := Finsupp.ext fun _ => count_add _ _ _ right_inv f := Finsupp.ext fun a => by simp only [Finsupp.toMultiset_apply, Finsupp.sum, Multiset.count_sum', Multiset.count_singleton, mul_boole, Finsupp.coe_mk, Finsupp.mem_support_iff, Multiset.count_nsmul, Finset.sum_ite_eq, ite_not, ite_eq_right_iff] exact Eq.symm left_inv s := by simp only [Finsupp.toMultiset_apply, Finsupp.sum, Finsupp.coe_mk, Multiset.toFinset_sum_count_nsmul_eq] @[simp] theorem toFinsupp_support (s : Multiset α) : s.toFinsupp.support = s.toFinset := rfl @[simp] theorem toFinsupp_apply (s : Multiset α) (a : α) : toFinsupp s a = s.count a := rfl theorem toFinsupp_zero : toFinsupp (0 : Multiset α) = 0 := _root_.map_zero _ theorem toFinsupp_add (s t : Multiset α) : toFinsupp (s + t) = toFinsupp s + toFinsupp t := toFinsupp.map_add s t @[simp] theorem toFinsupp_singleton (a : α) : toFinsupp ({a} : Multiset α) = Finsupp.single a 1 := by ext; rw [toFinsupp_apply, count_singleton, Finsupp.single_eq_pi_single, Pi.single_apply] @[simp] theorem toFinsupp_toMultiset (s : Multiset α) : Finsupp.toMultiset (toFinsupp s) = s := Multiset.toFinsupp.symm_apply_apply s theorem toFinsupp_eq_iff {s : Multiset α} {f : α →₀ ℕ} : toFinsupp s = f ↔ s = Finsupp.toMultiset f := Multiset.toFinsupp.apply_eq_iff_symm_apply theorem toFinsupp_union (s t : Multiset α) : toFinsupp (s ∪ t) = toFinsupp s ⊔ toFinsupp t := by ext simp [sup_eq_max] theorem toFinsupp_inter (s t : Multiset α) : toFinsupp (s ∩ t) = toFinsupp s ⊓ toFinsupp t := by ext simp [inf_eq_min] @[simp] theorem toFinsupp_sum_eq (s : Multiset α) : s.toFinsupp.sum (fun _ ↦ id) = Multiset.card s := by rw [← Finsupp.card_toMultiset, toFinsupp_toMultiset] end Multiset @[simp] theorem Finsupp.toMultiset_toFinsupp [DecidableEq α] (f : α →₀ ℕ) : Multiset.toFinsupp (Finsupp.toMultiset f) = f := Multiset.toFinsupp.apply_symm_apply _ theorem Finsupp.toMultiset_eq_iff [DecidableEq α] {f : α →₀ ℕ} {s : Multiset α} : Finsupp.toMultiset f = s ↔ f = Multiset.toFinsupp s := Multiset.toFinsupp.symm_apply_eq /-! ### As an order isomorphism -/ namespace Finsupp /-- `Finsupp.toMultiset` as an order isomorphism. -/ def orderIsoMultiset [DecidableEq ι] : (ι →₀ ℕ) ≃o Multiset ι where toEquiv := Multiset.toFinsupp.symm.toEquiv map_rel_iff' {f g} := by simp [le_def, Multiset.le_iff_count] @[simp] theorem coe_orderIsoMultiset [DecidableEq ι] : ⇑(@orderIsoMultiset ι _) = toMultiset := rfl @[simp] theorem coe_orderIsoMultiset_symm [DecidableEq ι] : ⇑(@orderIsoMultiset ι).symm = Multiset.toFinsupp := rfl theorem toMultiset_strictMono : StrictMono (@toMultiset ι) := by classical exact (@orderIsoMultiset ι _).strictMono theorem sum_id_lt_of_lt (m n : ι →₀ ℕ) (h : m < n) : (m.sum fun _ => id) < n.sum fun _ => id := by rw [← card_toMultiset, ← card_toMultiset] apply Multiset.card_lt_card exact toMultiset_strictMono h variable (ι) /-- The order on `ι →₀ ℕ` is well-founded. -/ theorem lt_wf : WellFounded (@LT.lt (ι →₀ ℕ) _) := Subrelation.wf (sum_id_lt_of_lt _ _) <| InvImage.wf _ Nat.lt_wfRel.2 -- TODO: generalize to `[WellFoundedRelation α] → WellFoundedRelation (ι →₀ α)` instance : WellFoundedRelation (ι →₀ ℕ) where rel := (· < ·) wf := lt_wf _ end Finsupp theorem Multiset.toFinsupp_strictMono [DecidableEq ι] : StrictMono (@Multiset.toFinsupp ι _) := (@Finsupp.orderIsoMultiset ι).symm.strictMono namespace Sym variable (α) variable [DecidableEq α] (n : ℕ) /-- The `n`th symmetric power of a type `α` is naturally equivalent to the subtype of finitely-supported maps `α →₀ ℕ` with total mass `n`. See also `Sym.equivNatSumOfFintype` when `α` is finite. -/ def equivNatSum : Sym α n ≃ {P : α →₀ ℕ // P.sum (fun _ ↦ id) = n} := Multiset.toFinsupp.toEquiv.subtypeEquiv <| by simp @[simp] lemma coe_equivNatSum_apply_apply (s : Sym α n) (a : α) : (equivNatSum α n s : α →₀ ℕ) a = (s : Multiset α).count a := rfl @[simp] lemma coe_equivNatSum_symm_apply (P : {P : α →₀ ℕ // P.sum (fun _ ↦ id) = n}) : ((equivNatSum α n).symm P : Multiset α) = Finsupp.toMultiset P := rfl /-- The `n`th symmetric power of a finite type `α` is naturally equivalent to the subtype of maps `α → ℕ` with total mass `n`. See also `Sym.equivNatSum` when `α` is not necessarily finite. -/ noncomputable def equivNatSumOfFintype [Fintype α] : Sym α n ≃ {P : α → ℕ // ∑ i, P i = n} := (equivNatSum α n).trans <| Finsupp.equivFunOnFinite.subtypeEquiv <| by simp [Finsupp.sum_fintype] @[simp] lemma coe_equivNatSumOfFintype_apply_apply [Fintype α] (s : Sym α n) (a : α) : (equivNatSumOfFintype α n s : α → ℕ) a = (s : Multiset α).count a := rfl @[simp] lemma coe_equivNatSumOfFintype_symm_apply [Fintype α] (P : {P : α → ℕ // ∑ i, P i = n}) : ((equivNatSumOfFintype α n).symm P : Multiset α) = ∑ a, ((P : α → ℕ) a) • {a} := by obtain ⟨P, hP⟩ := P change Finsupp.toMultiset (Finsupp.equivFunOnFinite.symm P) = Multiset.sum _ ext a rw [Multiset.count_sum] simp [Multiset.count_singleton] end Sym
Data\Finsupp\NeLocus.lean
/- Copyright (c) 2022 Damiano Testa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Damiano Testa -/ import Mathlib.Data.Finsupp.Defs /-! # Locus of unequal values of finitely supported functions Let `α N` be two Types, assume that `N` has a `0` and let `f g : α →₀ N` be finitely supported functions. ## Main definition * `Finsupp.neLocus f g : Finset α`, the finite subset of `α` where `f` and `g` differ. In the case in which `N` is an additive group, `Finsupp.neLocus f g` coincides with `Finsupp.support (f - g)`. -/ variable {α M N P : Type*} namespace Finsupp variable [DecidableEq α] section NHasZero variable [DecidableEq N] [Zero N] (f g : α →₀ N) /-- 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 : α →₀ N) : Finset α := (f.support ∪ g.support).filter fun x => f x ≠ g x @[simp] theorem mem_neLocus {f g : α →₀ N} {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 : α →₀ N} {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 } := by ext exact mem_neLocus @[simp] theorem neLocus_eq_empty {f g : α →₀ N} : 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 : α →₀ N} : (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 : α →₀ N).neLocus f = f.support := (neLocus_comm _ _).trans (neLocus_zero_right _) end NHasZero section NeLocusAndMaps theorem subset_mapRange_neLocus [DecidableEq N] [Zero N] [DecidableEq M] [Zero M] (f g : α →₀ N) {F : N → M} (F0 : F 0 = 0) : (f.mapRange F F0).neLocus (g.mapRange F F0) ⊆ f.neLocus g := fun x => by simpa only [mem_neLocus, mapRange_apply, not_imp_not] using congr_arg F theorem zipWith_neLocus_eq_left [DecidableEq N] [Zero M] [DecidableEq P] [Zero P] [Zero N] {F : M → N → P} (F0 : F 0 0 = 0) (f : α →₀ M) (g₁ g₂ : α →₀ N) (hF : ∀ f, Function.Injective fun g => F f g) : (zipWith F F0 f g₁).neLocus (zipWith F F0 f g₂) = g₁.neLocus g₂ := by ext simpa only [mem_neLocus] using (hF _).ne_iff theorem zipWith_neLocus_eq_right [DecidableEq M] [Zero M] [DecidableEq P] [Zero P] [Zero N] {F : M → N → P} (F0 : F 0 0 = 0) (f₁ f₂ : α →₀ M) (g : α →₀ N) (hF : ∀ g, Function.Injective fun f => F f g) : (zipWith F F0 f₁ g).neLocus (zipWith F F0 f₂ g) = f₁.neLocus f₂ := by ext simpa only [mem_neLocus] using (hF _).ne_iff theorem mapRange_neLocus_eq [DecidableEq N] [DecidableEq M] [Zero M] [Zero N] (f g : α →₀ N) {F : N → M} (F0 : F 0 = 0) (hF : Function.Injective F) : (f.mapRange F F0).neLocus (g.mapRange F F0) = f.neLocus g := by ext simpa only [mem_neLocus] using hF.ne_iff end NeLocusAndMaps variable [DecidableEq N] @[simp] theorem neLocus_add_left [AddLeftCancelMonoid N] (f g h : α →₀ N) : (f + g).neLocus (f + h) = g.neLocus h := zipWith_neLocus_eq_left _ _ _ _ add_right_injective @[simp] theorem neLocus_add_right [AddRightCancelMonoid N] (f g h : α →₀ N) : (f + h).neLocus (g + h) = f.neLocus g := zipWith_neLocus_eq_right _ _ _ _ add_left_injective section AddGroup variable [AddGroup N] (f f₁ f₂ g g₁ g₂ : α →₀ N) @[simp] theorem neLocus_neg_neg : neLocus (-f) (-g) = f.neLocus g := mapRange_neLocus_eq _ _ neg_zero 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 _ _ (-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, 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 _ _ _ @[simp] theorem neLocus_self_add_right : neLocus f (f + g) = g.support := by rw [← neLocus_zero_left, ← neLocus_add_left 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 Finsupp
Data\Finsupp\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.Finsupp.Defs /-! # Notation for `Finsupp` This file provides `fun₀ | 3 => a | 7 => b` notation for `Finsupp`, which desugars to `Finsupp.update` and `Finsupp.single`, in the same way that `{a, b}` desugars to `insert` and `singleton`. -/ namespace Finsupp open Lean open Lean.Parser open Lean.Parser.Term -- A variant of `Lean.Parser.Term.matchAlts` with less line wrapping. @[nolint docBlame] -- we do not want any doc hover on this notation. def fun₀.matchAlts : Parser := leading_parser withPosition <| ppRealGroup <| many1Indent (ppSpace >> ppGroup matchAlt) /-- `fun₀ | i => a` is notation for `Finsupp.single i a`, and with multiple match arms, `fun₀ ... | i => a` is notation for `Finsupp.update (fun₀ ...) i a`. As a result, if multiple match arms coincide, the last one takes precedence. -/ @[term_parser] def fun₀ := leading_parser:maxPrec ppAllowUngrouped >> unicodeSymbol "λ₀" "fun₀" >> fun₀.matchAlts /-- Implementation detail for `fun₀`, used by both `Finsupp` and `DFinsupp` -/ local syntax:lead (name := stxSingle₀) "single₀" term:arg term:arg : term /-- Implementation detail for `fun₀`, used by both `Finsupp` and `DFinsupp` -/ local syntax:lead (name := stxUpdate₀) "update₀" term:arg term:arg term:arg : term /-- `Finsupp` elaborator for `single₀`. -/ @[term_elab stxSingle₀] def elabSingle₀ : Elab.Term.TermElab | `(term| single₀ $i $x) => fun ty => do Elab.Term.elabTerm (← `(Finsupp.single $i $x)) ty | _ => fun _ => Elab.throwUnsupportedSyntax /-- `Finsupp` elaborator for `update₀`. -/ @[term_elab stxUpdate₀] def elabUpdate₀ : Elab.Term.TermElab | `(term| update₀ $f $i $x) => fun ty => do Elab.Term.elabTerm (← `(Finsupp.update $f $i $x)) ty | _ => fun _ => Elab.throwUnsupportedSyntax macro_rules | `(term| fun₀ $x:matchAlt*) => do let mut stx : Term ← `(0) let mut fst : Bool := true for xi in x do for xii in (← Elab.Term.expandMatchAlt xi) do match xii with | `(matchAltExpr| | $pat => $val) => if fst then stx ← `(single₀ $pat $val) else stx ← `(update₀ $stx $pat $val) fst := false | _ => Macro.throwUnsupported pure stx /-- 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 `Finsupp` using `fun₀` notation. -/ unsafe instance instRepr {α β} [Repr α] [Repr β] [Zero β] : Repr (α →₀ β) where reprPrec f p := if f.support.card = 0 then "0" else let ret := "fun₀" ++ Std.Format.join (f.support.val.unquot.map <| fun a => " | " ++ repr a ++ " => " ++ repr (f a)) if p ≥ leadPrec then Format.paren ret else ret -- This cannot be put in `Mathlib.Data.DFinsupp.Notation` where it belongs, since doc-strings -- can only be added/modified in the file where the corresponding declaration is defined. extend_docs Finsupp.fun₀ after "If the expected type is `Π₀ i, α i` (`DFinsupp`) and `Mathlib.Data.DFinsupp.Notation` is imported, then this is notation for `DFinsupp.single` and `Dfinsupp.update` instead." end Finsupp
Data\Finsupp\Order.lean
/- Copyright (c) 2021 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Aaron Anderson -/ import Mathlib.Algebra.Order.Module.Defs import Mathlib.Data.Finsupp.Basic /-! # Pointwise order on finitely supported functions This file lifts order structures on `α` to `ι →₀ α`. ## Main declarations * `Finsupp.orderEmbeddingToFun`: The order embedding from finitely supported functions to functions. -/ noncomputable section open Finset variable {ι α β : Type*} namespace Finsupp /-! ### Order structures -/ section Zero variable [Zero α] section LE variable [LE α] {f g : ι →₀ α} instance instLEFinsupp : LE (ι →₀ α) := ⟨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 `Finsupp`s over a partial order embeds into the order on functions -/ def orderEmbeddingToFun : (ι →₀ α) ↪o (ι → α) where toFun f := f inj' f g h := Finsupp.ext fun i => by dsimp at h rw [h] map_rel_iff' := coe_le_coe @[simp] theorem orderEmbeddingToFun_apply {f : ι →₀ α} {i : ι} : orderEmbeddingToFun f i = f i := rfl end LE section Preorder variable [Preorder α] {f g : ι →₀ α} instance preorder : Preorder (ι →₀ α) := { Finsupp.instLEFinsupp 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 (Finsupp.toFun : (ι →₀ α) → ι → α) := fun _ _ ↦ id lemma coe_strictMono : Monotone (Finsupp.toFun : (ι →₀ α) → ι → α) := fun _ _ ↦ id end Preorder instance partialorder [PartialOrder α] : PartialOrder (ι →₀ α) := { Finsupp.preorder with le_antisymm := fun _f _g hfg hgf => ext fun i => (hfg i).antisymm (hgf i) } instance semilatticeInf [SemilatticeInf α] : SemilatticeInf (ι →₀ α) := { Finsupp.partialorder with inf := zipWith (· ⊓ ·) (inf_idem _) inf_le_left := fun _f _g _i => inf_le_left inf_le_right := fun _f _g _i => inf_le_right le_inf := fun _f _g _i h1 h2 s => le_inf (h1 s) (h2 s) } @[simp] theorem inf_apply [SemilatticeInf α] {i : ι} {f g : ι →₀ α} : (f ⊓ g) i = f i ⊓ g i := rfl instance semilatticeSup [SemilatticeSup α] : SemilatticeSup (ι →₀ α) := { Finsupp.partialorder with sup := zipWith (· ⊔ ·) (sup_idem _) le_sup_left := fun _f _g _i => le_sup_left le_sup_right := fun _f _g _i => le_sup_right sup_le := fun _f _g _h hf hg i => sup_le (hf i) (hg i) } @[simp] theorem sup_apply [SemilatticeSup α] {i : ι} {f g : ι →₀ α} : (f ⊔ g) i = f i ⊔ g i := rfl instance lattice [Lattice α] : Lattice (ι →₀ α) := { Finsupp.semilatticeInf, Finsupp.semilatticeSup with } section Lattice variable [DecidableEq ι] [Lattice α] (f g : ι →₀ α) 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 orderedAddCommMonoid [OrderedAddCommMonoid α] : OrderedAddCommMonoid (ι →₀ α) := { Finsupp.instAddCommMonoid, Finsupp.partialorder with add_le_add_left := fun _a _b h c s => add_le_add_left (h s) (c s) } instance orderedCancelAddCommMonoid [OrderedCancelAddCommMonoid α] : OrderedCancelAddCommMonoid (ι →₀ α) := { Finsupp.orderedAddCommMonoid with le_of_add_le_add_left := fun _f _g _i h s => le_of_add_le_add_left (h s) } instance contravariantClass [OrderedAddCommMonoid α] [ContravariantClass α α (· + ·) (· ≤ ·)] : ContravariantClass (ι →₀ α) (ι →₀ α) (· + ·) (· ≤ ·) := ⟨fun _f _g _h H x => le_of_add_le_add_left <| H x⟩ section SMulZeroClass variable [Zero α] [Preorder α] [Zero β] [Preorder β] [SMulZeroClass α β] instance instPosSMulMono [PosSMulMono α β] : PosSMulMono α (ι →₀ β) := PosSMulMono.lift _ coe_le_coe coe_smul instance instSMulPosMono [SMulPosMono α β] : SMulPosMono α (ι →₀ β) := SMulPosMono.lift _ coe_le_coe coe_smul coe_zero instance instPosSMulReflectLE [PosSMulReflectLE α β] : PosSMulReflectLE α (ι →₀ β) := PosSMulReflectLE.lift _ coe_le_coe coe_smul instance instSMulPosReflectLE [SMulPosReflectLE α β] : SMulPosReflectLE α (ι →₀ β) := SMulPosReflectLE.lift _ coe_le_coe coe_smul coe_zero end SMulZeroClass section SMulWithZero variable [Zero α] [PartialOrder α] [Zero β] [PartialOrder β] [SMulWithZero α β] instance instPosSMulStrictMono [PosSMulStrictMono α β] : PosSMulStrictMono α (ι →₀ β) := PosSMulStrictMono.lift _ coe_le_coe coe_smul instance instSMulPosStrictMono [SMulPosStrictMono α β] : SMulPosStrictMono α (ι →₀ β) := SMulPosStrictMono.lift _ coe_le_coe coe_smul coe_zero -- `PosSMulReflectLT α (ι →₀ β)` already follows from the other instances instance instSMulPosReflectLT [SMulPosReflectLT α β] : SMulPosReflectLT α (ι →₀ β) := SMulPosReflectLT.lift _ coe_le_coe coe_smul coe_zero end SMulWithZero section CanonicallyOrderedAddCommMonoid variable [CanonicallyOrderedAddCommMonoid α] {f g : ι →₀ α} instance orderBot : OrderBot (ι →₀ α) where bot := 0 bot_le := by simp only [le_def, coe_zero, Pi.zero_apply, imp_true_iff, zero_le] protected theorem bot_eq_zero : (⊥ : ι →₀ α) = 0 := rfl @[simp] theorem add_eq_zero_iff (f g : ι →₀ α) : f + g = 0 ↔ f = 0 ∧ g = 0 := by simp [DFunLike.ext_iff, forall_and] theorem le_iff' (f g : ι →₀ α) {s : Finset ι} (hf : f.support ⊆ s) : f ≤ g ↔ ∀ i ∈ s, f i ≤ g i := ⟨fun h s _hs => h s, fun h s => by classical exact 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 : ι →₀ α) : f ≤ g ↔ ∀ i ∈ f.support, f i ≤ g i := le_iff' f g <| Subset.refl _ lemma support_monotone : Monotone (support (α := ι) (M := α)) := 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 instance decidableLE [DecidableRel (@LE.le α _)] : DecidableRel (@LE.le (ι →₀ α) _) := fun f g => decidable_of_iff _ (le_iff f g).symm instance decidableLT [DecidableRel (@LE.le α _)] : DecidableRel (@LT.lt (ι →₀ α) _) := decidableLTOfDecidableLE @[simp] theorem single_le_iff {i : ι} {x : α} {f : ι →₀ α} : single i x ≤ f ↔ x ≤ f i := (le_iff' _ _ support_single_subset).trans <| by simp variable [Sub α] [OrderedSub α] {f g : ι →₀ α} {i : ι} {a b : α} /-- This is called `tsub` for truncated subtraction, to distinguish it with subtraction in an additive group. -/ instance tsub : Sub (ι →₀ α) := ⟨zipWith (fun m n => m - n) (tsub_self 0)⟩ instance orderedSub : OrderedSub (ι →₀ α) := ⟨fun _n _m _k => forall_congr' fun _x => tsub_le_iff_right⟩ instance : CanonicallyOrderedAddCommMonoid (ι →₀ α) := { Finsupp.orderBot, Finsupp.orderedAddCommMonoid with exists_add_of_le := fun {f g} h => ⟨g - f, ext fun x => (add_tsub_cancel_of_le <| h x).symm⟩ le_self_add := fun _f _g _x => le_self_add } @[simp, norm_cast] lemma coe_tsub (f g : ι →₀ α) : ⇑(f - g) = f - g := rfl theorem tsub_apply (f g : ι →₀ α) (a : ι) : (f - g) a = f a - g a := rfl @[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] theorem support_tsub {f1 f2 : ι →₀ α} : (f1 - f2).support ⊆ f1.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 [DecidableEq ι] {f1 f2 : ι →₀ α} : f1.support \ f2.support ⊆ (f1 - f2).support := by simp (config := { contextual := true }) [subset_iff] end CanonicallyOrderedAddCommMonoid section CanonicallyLinearOrderedAddCommMonoid variable [CanonicallyLinearOrderedAddCommMonoid α] @[simp] theorem support_inf [DecidableEq ι] (f g : ι →₀ α) : (f ⊓ g).support = f.support ∩ g.support := by ext simp only [inf_apply, mem_support_iff, Ne, Finset.mem_union, Finset.mem_filter, Finset.mem_inter] simp only [inf_eq_min, ← nonpos_iff_eq_zero, min_le_iff, not_or] @[simp] theorem support_sup [DecidableEq ι] (f g : ι →₀ α) : (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 {f g : ι →₀ α} : Disjoint f g ↔ Disjoint f.support g.support := by classical rw [disjoint_iff, disjoint_iff, Finsupp.bot_eq_zero, ← Finsupp.support_eq_empty, Finsupp.support_inf] rfl end CanonicallyLinearOrderedAddCommMonoid /-! ### Some lemmas about `ℕ` -/ section Nat theorem sub_single_one_add {a : ι} {u u' : ι →₀ ℕ} (h : u a ≠ 0) : u - single a 1 + u' = u + u' - single a 1 := tsub_add_eq_add_tsub <| single_le_iff.mpr <| Nat.one_le_iff_ne_zero.mpr h theorem add_sub_single_one {a : ι} {u u' : ι →₀ ℕ} (h : u' a ≠ 0) : u + (u' - single a 1) = u + u' - single a 1 := (add_tsub_assoc_of_le (single_le_iff.mpr <| Nat.one_le_iff_ne_zero.mpr h) _).symm end Nat end Finsupp
Data\Finsupp\Pointwise.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.Algebra.Module.Defs import Mathlib.Algebra.Ring.Pi import Mathlib.Data.Finsupp.Defs /-! # The pointwise product on `Finsupp`. For the convolution product on `Finsupp` when the domain has a binary operation, see the type synonyms `AddMonoidAlgebra` (which is in turn used to define `Polynomial` and `MvPolynomial`) and `MonoidAlgebra`. -/ noncomputable section open Finset universe u₁ u₂ u₃ u₄ u₅ variable {α : Type u₁} {β : Type u₂} {γ : Type u₃} {δ : Type u₄} {ι : Type u₅} namespace Finsupp /-! ### Declarations about the pointwise product on `Finsupp`s -/ section variable [MulZeroClass β] /-- The product of `f g : α →₀ β` is the finitely supported function whose value at `a` is `f a * g a`. -/ instance : Mul (α →₀ β) := ⟨zipWith (· * ·) (mul_zero 0)⟩ theorem coe_mul (g₁ g₂ : α →₀ β) : ⇑(g₁ * g₂) = g₁ * g₂ := rfl @[simp] theorem mul_apply {g₁ g₂ : α →₀ β} {a : α} : (g₁ * g₂) a = g₁ a * g₂ a := rfl @[simp] theorem single_mul (a : α) (b₁ b₂ : β) : single a (b₁ * b₂) = single a b₁ * single a b₂ := (zipWith_single_single _ _ _ _ _).symm theorem support_mul [DecidableEq α] {g₁ g₂ : α →₀ β} : (g₁ * g₂).support ⊆ g₁.support ∩ g₂.support := by intro a h simp only [mul_apply, mem_support_iff] at h simp only [mem_support_iff, mem_inter, Ne] rw [← not_or] intro w apply h cases' w with w w <;> (rw [w]; simp) instance : MulZeroClass (α →₀ β) := DFunLike.coe_injective.mulZeroClass _ coe_zero coe_mul end instance [SemigroupWithZero β] : SemigroupWithZero (α →₀ β) := DFunLike.coe_injective.semigroupWithZero _ coe_zero coe_mul instance [NonUnitalNonAssocSemiring β] : NonUnitalNonAssocSemiring (α →₀ β) := DFunLike.coe_injective.nonUnitalNonAssocSemiring _ coe_zero coe_add coe_mul fun _ _ ↦ rfl instance [NonUnitalSemiring β] : NonUnitalSemiring (α →₀ β) := DFunLike.coe_injective.nonUnitalSemiring _ coe_zero coe_add coe_mul fun _ _ ↦ rfl instance [NonUnitalCommSemiring β] : NonUnitalCommSemiring (α →₀ β) := DFunLike.coe_injective.nonUnitalCommSemiring _ coe_zero coe_add coe_mul fun _ _ ↦ rfl instance [NonUnitalNonAssocRing β] : NonUnitalNonAssocRing (α →₀ β) := DFunLike.coe_injective.nonUnitalNonAssocRing _ coe_zero coe_add coe_mul coe_neg coe_sub (fun _ _ ↦ rfl) fun _ _ ↦ rfl instance [NonUnitalRing β] : NonUnitalRing (α →₀ β) := DFunLike.coe_injective.nonUnitalRing _ coe_zero coe_add coe_mul coe_neg coe_sub (fun _ _ ↦ rfl) fun _ _ ↦ rfl instance [NonUnitalCommRing β] : NonUnitalCommRing (α →₀ β) := DFunLike.coe_injective.nonUnitalCommRing _ coe_zero coe_add coe_mul coe_neg coe_sub (fun _ _ ↦ rfl) fun _ _ ↦ rfl -- TODO can this be generalized in the direction of `Pi.smul'` -- (i.e. dependent functions and finsupps) -- TODO in theory this could be generalised, we only really need `smul_zero` for the definition instance pointwiseScalar [Semiring β] : SMul (α → β) (α →₀ β) where smul f g := Finsupp.ofSupportFinite (fun a ↦ f a • g a) (by apply Set.Finite.subset g.finite_support simp only [Function.support_subset_iff, Finsupp.mem_support_iff, Ne, Finsupp.fun_support_eq, Finset.mem_coe] intro x hx h apply hx rw [h, smul_zero]) @[simp] theorem coe_pointwise_smul [Semiring β] (f : α → β) (g : α →₀ β) : ⇑(f • g) = f • ⇑g := rfl /-- The pointwise multiplicative action of functions on finitely supported functions -/ instance pointwiseModule [Semiring β] : Module (α → β) (α →₀ β) := Function.Injective.module _ coeFnAddHom DFunLike.coe_injective coe_pointwise_smul end Finsupp
Data\Finsupp\PWO.lean
/- Copyright (c) 2022 Alex J. Best. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alex J. Best -/ import Mathlib.Data.Finsupp.Order import Mathlib.Order.WellFoundedSet /-! # Partial well ordering on finsupps This file contains the fact that finitely supported functions from a fintype are partially well ordered when the codomain is a linear order that is well ordered. It is in a separate file for now so as to not add imports to the file `Order.WellFoundedSet`. ## Main statements * `Finsupp.isPWO` - finitely supported functions from a fintype are partially well ordered when the codomain is a linear order that is well ordered ## Tags Dickson, order, partial well order -/ /-- A version of **Dickson's lemma** any subset of functions `σ →₀ α` is partially well ordered, when `σ` is `Finite` and `α` is a linear well order. This version uses finsupps on a finite type as it is intended for use with `MVPowerSeries`. -/ theorem Finsupp.isPWO {α σ : Type*} [Zero α] [LinearOrder α] [IsWellOrder α (· < ·)] [Finite σ] (S : Set (σ →₀ α)) : S.IsPWO := Finsupp.equivFunOnFinite.symm_image_image S ▸ Set.PartiallyWellOrderedOn.image_of_monotone_on (Pi.isPWO _) fun _a _b _ha _hb => id
Data\Finsupp\ToDFinsupp.lean
/- Copyright (c) 2021 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import Mathlib.Algebra.Module.Equiv.Defs import Mathlib.Data.DFinsupp.Basic import Mathlib.Data.Finsupp.Basic /-! # Conversion between `Finsupp` and homogenous `DFinsupp` This module provides conversions between `Finsupp` and `DFinsupp`. It is in its own file since neither `Finsupp` or `DFinsupp` depend on each other. ## Main definitions * "identity" maps between `Finsupp` and `DFinsupp`: * `Finsupp.toDFinsupp : (ι →₀ M) → (Π₀ i : ι, M)` * `DFinsupp.toFinsupp : (Π₀ i : ι, M) → (ι →₀ M)` * Bundled equiv versions of the above: * `finsuppEquivDFinsupp : (ι →₀ M) ≃ (Π₀ i : ι, M)` * `finsuppAddEquivDFinsupp : (ι →₀ M) ≃+ (Π₀ i : ι, M)` * `finsuppLequivDFinsupp R : (ι →₀ M) ≃ₗ[R] (Π₀ i : ι, M)` * stronger versions of `Finsupp.split`: * `sigmaFinsuppEquivDFinsupp : ((Σ i, η i) →₀ N) ≃ (Π₀ i, (η i →₀ N))` * `sigmaFinsuppAddEquivDFinsupp : ((Σ i, η i) →₀ N) ≃+ (Π₀ i, (η i →₀ N))` * `sigmaFinsuppLequivDFinsupp : ((Σ i, η i) →₀ N) ≃ₗ[R] (Π₀ i, (η i →₀ N))` ## Theorems The defining features of these operations is that they preserve the function and support: * `Finsupp.toDFinsupp_coe` * `Finsupp.toDFinsupp_support` * `DFinsupp.toFinsupp_coe` * `DFinsupp.toFinsupp_support` and therefore map `Finsupp.single` to `DFinsupp.single` and vice versa: * `Finsupp.toDFinsupp_single` * `DFinsupp.toFinsupp_single` as well as preserving arithmetic operations. For the bundled equivalences, we provide lemmas that they reduce to `Finsupp.toDFinsupp`: * `finsupp_add_equiv_dfinsupp_apply` * `finsupp_lequiv_dfinsupp_apply` * `finsupp_add_equiv_dfinsupp_symm_apply` * `finsupp_lequiv_dfinsupp_symm_apply` ## Implementation notes We provide `DFinsupp.toFinsupp` and `finsuppEquivDFinsupp` computably by adding `[DecidableEq ι]` and `[Π m : M, Decidable (m ≠ 0)]` arguments. To aid with definitional unfolding, these arguments are also present on the `noncomputable` equivs. -/ variable {ι : Type*} {R : Type*} {M : Type*} /-! ### Basic definitions and lemmas -/ section Defs /-- Interpret a `Finsupp` as a homogenous `DFinsupp`. -/ def Finsupp.toDFinsupp [Zero M] (f : ι →₀ M) : Π₀ _ : ι, M where toFun := f support' := Trunc.mk ⟨f.support.1, fun i => (Classical.em (f i = 0)).symm.imp_left Finsupp.mem_support_iff.mpr⟩ @[simp] theorem Finsupp.toDFinsupp_coe [Zero M] (f : ι →₀ M) : ⇑f.toDFinsupp = f := rfl section variable [DecidableEq ι] [Zero M] @[simp] theorem Finsupp.toDFinsupp_single (i : ι) (m : M) : (Finsupp.single i m).toDFinsupp = DFinsupp.single i m := by ext simp [Finsupp.single_apply, DFinsupp.single_apply] variable [∀ m : M, Decidable (m ≠ 0)] @[simp] theorem toDFinsupp_support (f : ι →₀ M) : f.toDFinsupp.support = f.support := by ext simp /-- Interpret a homogenous `DFinsupp` as a `Finsupp`. Note that the elaborator has a lot of trouble with this definition - it is often necessary to write `(DFinsupp.toFinsupp f : ι →₀ M)` instead of `f.toFinsupp`, as for some unknown reason using dot notation or omitting the type ascription prevents the type being resolved correctly. -/ def DFinsupp.toFinsupp (f : Π₀ _ : ι, M) : ι →₀ M := ⟨f.support, f, fun i => by simp only [DFinsupp.mem_support_iff]⟩ @[simp] theorem DFinsupp.toFinsupp_coe (f : Π₀ _ : ι, M) : ⇑f.toFinsupp = f := rfl @[simp] theorem DFinsupp.toFinsupp_support (f : Π₀ _ : ι, M) : f.toFinsupp.support = f.support := by ext simp @[simp] theorem DFinsupp.toFinsupp_single (i : ι) (m : M) : (DFinsupp.single i m : Π₀ _ : ι, M).toFinsupp = Finsupp.single i m := by ext simp [Finsupp.single_apply, DFinsupp.single_apply] @[simp] theorem Finsupp.toDFinsupp_toFinsupp (f : ι →₀ M) : f.toDFinsupp.toFinsupp = f := DFunLike.coe_injective rfl @[simp] theorem DFinsupp.toFinsupp_toDFinsupp (f : Π₀ _ : ι, M) : f.toFinsupp.toDFinsupp = f := DFunLike.coe_injective rfl end end Defs /-! ### Lemmas about arithmetic operations -/ section Lemmas namespace Finsupp @[simp] theorem toDFinsupp_zero [Zero M] : (0 : ι →₀ M).toDFinsupp = 0 := DFunLike.coe_injective rfl @[simp] theorem toDFinsupp_add [AddZeroClass M] (f g : ι →₀ M) : (f + g).toDFinsupp = f.toDFinsupp + g.toDFinsupp := DFunLike.coe_injective rfl @[simp] theorem toDFinsupp_neg [AddGroup M] (f : ι →₀ M) : (-f).toDFinsupp = -f.toDFinsupp := DFunLike.coe_injective rfl @[simp] theorem toDFinsupp_sub [AddGroup M] (f g : ι →₀ M) : (f - g).toDFinsupp = f.toDFinsupp - g.toDFinsupp := DFunLike.coe_injective rfl @[simp] theorem toDFinsupp_smul [Monoid R] [AddMonoid M] [DistribMulAction R M] (r : R) (f : ι →₀ M) : (r • f).toDFinsupp = r • f.toDFinsupp := DFunLike.coe_injective rfl end Finsupp namespace DFinsupp variable [DecidableEq ι] @[simp] theorem toFinsupp_zero [Zero M] [∀ m : M, Decidable (m ≠ 0)] : toFinsupp 0 = (0 : ι →₀ M) := DFunLike.coe_injective rfl @[simp] theorem toFinsupp_add [AddZeroClass M] [∀ m : M, Decidable (m ≠ 0)] (f g : Π₀ _ : ι, M) : (toFinsupp (f + g) : ι →₀ M) = toFinsupp f + toFinsupp g := DFunLike.coe_injective <| DFinsupp.coe_add _ _ @[simp] theorem toFinsupp_neg [AddGroup M] [∀ m : M, Decidable (m ≠ 0)] (f : Π₀ _ : ι, M) : (toFinsupp (-f) : ι →₀ M) = -toFinsupp f := DFunLike.coe_injective <| DFinsupp.coe_neg _ @[simp] theorem toFinsupp_sub [AddGroup M] [∀ m : M, Decidable (m ≠ 0)] (f g : Π₀ _ : ι, M) : (toFinsupp (f - g) : ι →₀ M) = toFinsupp f - toFinsupp g := DFunLike.coe_injective <| DFinsupp.coe_sub _ _ @[simp] theorem toFinsupp_smul [Monoid R] [AddMonoid M] [DistribMulAction R M] [∀ m : M, Decidable (m ≠ 0)] (r : R) (f : Π₀ _ : ι, M) : (toFinsupp (r • f) : ι →₀ M) = r • toFinsupp f := DFunLike.coe_injective <| DFinsupp.coe_smul _ _ end DFinsupp end Lemmas /-! ### Bundled `Equiv`s -/ section Equivs /-- `Finsupp.toDFinsupp` and `DFinsupp.toFinsupp` together form an equiv. -/ @[simps (config := .asFn)] def finsuppEquivDFinsupp [DecidableEq ι] [Zero M] [∀ m : M, Decidable (m ≠ 0)] : (ι →₀ M) ≃ Π₀ _ : ι, M where toFun := Finsupp.toDFinsupp invFun := DFinsupp.toFinsupp left_inv := Finsupp.toDFinsupp_toFinsupp right_inv := DFinsupp.toFinsupp_toDFinsupp /-- The additive version of `finsupp.toFinsupp`. Note that this is `noncomputable` because `Finsupp.add` is noncomputable. -/ @[simps (config := .asFn)] def finsuppAddEquivDFinsupp [DecidableEq ι] [AddZeroClass M] [∀ m : M, Decidable (m ≠ 0)] : (ι →₀ M) ≃+ Π₀ _ : ι, M := { finsuppEquivDFinsupp with toFun := Finsupp.toDFinsupp invFun := DFinsupp.toFinsupp map_add' := Finsupp.toDFinsupp_add } variable (R) /-- The additive version of `Finsupp.toFinsupp`. Note that this is `noncomputable` because `Finsupp.add` is noncomputable. -/ -- Porting note: `simps` generated lemmas that did not pass `simpNF` lints, manually added below --@[simps? (config := .asFn)] def finsuppLequivDFinsupp [DecidableEq ι] [Semiring R] [AddCommMonoid M] [∀ m : M, Decidable (m ≠ 0)] [Module R M] : (ι →₀ M) ≃ₗ[R] Π₀ _ : ι, M := { finsuppEquivDFinsupp with toFun := Finsupp.toDFinsupp invFun := DFinsupp.toFinsupp map_smul' := Finsupp.toDFinsupp_smul map_add' := Finsupp.toDFinsupp_add } -- Porting note: `simps` generated as `↑(finsuppLequivDFinsupp R).toLinearMap = Finsupp.toDFinsupp` @[simp] theorem finsuppLequivDFinsupp_apply_apply [DecidableEq ι] [Semiring R] [AddCommMonoid M] [∀ m : M, Decidable (m ≠ 0)] [Module R M] : (↑(finsuppLequivDFinsupp (M := M) R) : (ι →₀ M) → _) = Finsupp.toDFinsupp := rfl @[simp] theorem finsuppLequivDFinsupp_symm_apply [DecidableEq ι] [Semiring R] [AddCommMonoid M] [∀ m : M, Decidable (m ≠ 0)] [Module R M] : ↑(LinearEquiv.symm (finsuppLequivDFinsupp (ι := ι) (M := M) R)) = DFinsupp.toFinsupp := rfl -- Porting note: moved noncomputable declaration into section begin noncomputable section Sigma /-! ### Stronger versions of `Finsupp.split` -/ --noncomputable section variable {η : ι → Type*} {N : Type*} [Semiring R] open Finsupp /-- `Finsupp.split` is an equivalence between `(Σ i, η i) →₀ N` and `Π₀ i, (η i →₀ N)`. -/ def sigmaFinsuppEquivDFinsupp [Zero N] : ((Σi, η i) →₀ N) ≃ Π₀ i, η i →₀ N where toFun f := ⟨split f, Trunc.mk ⟨(splitSupport f : Finset ι).val, fun i => by rw [← Finset.mem_def, mem_splitSupport_iff_nonzero] exact (em _).symm⟩⟩ invFun f := by haveI := Classical.decEq ι haveI := fun i => Classical.decEq (η i →₀ N) refine onFinset (Finset.sigma f.support fun j => (f j).support) (fun ji => f ji.1 ji.2) fun g hg => Finset.mem_sigma.mpr ⟨?_, mem_support_iff.mpr hg⟩ simp only [Ne, DFinsupp.mem_support_toFun] intro h dsimp at hg rw [h] at hg simp only [coe_zero, Pi.zero_apply, not_true] at hg left_inv f := by ext; simp [split] right_inv f := by ext; simp [split] @[simp] theorem sigmaFinsuppEquivDFinsupp_apply [Zero N] (f : (Σi, η i) →₀ N) : (sigmaFinsuppEquivDFinsupp f : ∀ i, η i →₀ N) = Finsupp.split f := rfl @[simp] theorem sigmaFinsuppEquivDFinsupp_symm_apply [Zero N] (f : Π₀ i, η i →₀ N) (s : Σi, η i) : (sigmaFinsuppEquivDFinsupp.symm f : (Σi, η i) →₀ N) s = f s.1 s.2 := rfl @[simp] theorem sigmaFinsuppEquivDFinsupp_support [DecidableEq ι] [Zero N] [∀ (i : ι) (x : η i →₀ N), Decidable (x ≠ 0)] (f : (Σi, η i) →₀ N) : (sigmaFinsuppEquivDFinsupp f).support = Finsupp.splitSupport f := by ext rw [DFinsupp.mem_support_toFun] exact (Finsupp.mem_splitSupport_iff_nonzero _ _).symm @[simp] theorem sigmaFinsuppEquivDFinsupp_single [DecidableEq ι] [Zero N] (a : Σi, η i) (n : N) : sigmaFinsuppEquivDFinsupp (Finsupp.single a n) = @DFinsupp.single _ (fun i => η i →₀ N) _ _ a.1 (Finsupp.single a.2 n) := by obtain ⟨i, a⟩ := a ext j b by_cases h : i = j · subst h classical simp [split_apply, Finsupp.single_apply] suffices Finsupp.single (⟨i, a⟩ : Σi, η i) n ⟨j, b⟩ = 0 by simp [split_apply, dif_neg h, this] have H : (⟨i, a⟩ : Σi, η i) ≠ ⟨j, b⟩ := by simp [h] classical rw [Finsupp.single_apply, if_neg H] -- Without this Lean fails to find the `AddZeroClass` instance on `Π₀ i, (η i →₀ N)`. attribute [-instance] Finsupp.instZero @[simp] theorem sigmaFinsuppEquivDFinsupp_add [AddZeroClass N] (f g : (Σi, η i) →₀ N) : sigmaFinsuppEquivDFinsupp (f + g) = (sigmaFinsuppEquivDFinsupp f + sigmaFinsuppEquivDFinsupp g : Π₀ i : ι, η i →₀ N) := by ext rfl /-- `Finsupp.split` is an additive equivalence between `(Σ i, η i) →₀ N` and `Π₀ i, (η i →₀ N)`. -/ @[simps] def sigmaFinsuppAddEquivDFinsupp [AddZeroClass N] : ((Σi, η i) →₀ N) ≃+ Π₀ i, η i →₀ N := { sigmaFinsuppEquivDFinsupp with toFun := sigmaFinsuppEquivDFinsupp invFun := sigmaFinsuppEquivDFinsupp.symm map_add' := sigmaFinsuppEquivDFinsupp_add } attribute [-instance] Finsupp.instAddZeroClass @[simp] theorem sigmaFinsuppEquivDFinsupp_smul {R} [Monoid R] [AddMonoid N] [DistribMulAction R N] (r : R) (f : (Σ i, η i) →₀ N) : sigmaFinsuppEquivDFinsupp (r • f) = r • sigmaFinsuppEquivDFinsupp f := by ext rfl attribute [-instance] Finsupp.instAddMonoid /-- `Finsupp.split` is a linear equivalence between `(Σ i, η i) →₀ N` and `Π₀ i, (η i →₀ N)`. -/ @[simps] def sigmaFinsuppLequivDFinsupp [AddCommMonoid N] [Module R N] : ((Σi, η i) →₀ N) ≃ₗ[R] Π₀ i, η i →₀ N := -- Porting note: was -- sigmaFinsuppAddEquivDFinsupp with map_smul' := sigmaFinsuppEquivDFinsupp_smul -- but times out { sigmaFinsuppEquivDFinsupp with toFun := sigmaFinsuppEquivDFinsupp invFun := sigmaFinsuppEquivDFinsupp.symm map_add' := sigmaFinsuppEquivDFinsupp_add map_smul' := sigmaFinsuppEquivDFinsupp_smul } end Sigma end Equivs
Data\Finsupp\Weight.lean
/- Copyright (c) 2024 Antoine Chambert-Loir, María Inés de Frutos Fernández. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Antoine Chambert-Loir, María Inés de Frutos Fernández -/ import Mathlib.Algebra.Order.BigOperators.Group.Finset import Mathlib.Algebra.Order.Module.Defs import Mathlib.Algebra.Order.Ring.Defs import Mathlib.Algebra.Order.Monoid.Canonical.Defs import Mathlib.LinearAlgebra.Finsupp /-! # weights of Finsupp functions The theory of multivariate polynomials and power series is built on the type `σ →₀ ℕ` which gives the exponents of the monomials. Many aspects of the theory (degree, order, graded ring structure) require to classify these exponents according to their total sum `∑ i, f i`, or variants, and this files provides some API for that. ## Weight We fix a type `σ` and an `AddCommMonoid M`, as well as a function `w : σ → M`. - `Finsupp.weight` of a finitely supported function `f : σ →₀ ℕ` with respect to `w`: it is the sum `∑ (f i) • (w i)`. It is an `AddMonoidHom` map defined using `Finsupp.total`. - `Finsupp.le_weight`says that `f s ≤ f.weight w` when `M = ℕ`` - `Finsupp.le_weight_of_nonneg'` says that `w s ≤ f.weight w` for `OrderedAddCommMonoid M`, when `f s ≠ 0` and all `w i` are nonnegative. - `Finsupp.le_weight'` is the same statement for `CanonicallyOrderedAddCommMonoid M`. - `NonTorsionWeight`: all values `w s` are non torsion in `M`. - `Finsupp.weight_eq_zero_iff_eq_zero` says that `f.weight w = 0` iff `f = 0` for `NonTorsion Weight w` and `CanonicallyOrderedAddCommMonoid M`. ## Degree - `Finsupp.degree`: the weight when all components of `w` are equal to `1 : ℕ`. The present choice is to have it defined as a plain function. - `Finsupp.degree_eq_zero_iff` says that `f.degree = 0` iff `f = 0`. - `Finsupp.le_degree` says that `f s ≤ f.degree`. - `Finsupp.degree_eq_weight_one` says `f.degree = f.weight 1`. This is useful to access the additivity properties of `Finsupp.degree` ## TODO * The relevant generality of these constructions is not clear. It could probably be generalized to `w : σ → M` and `f : σ →₀ N`, provided `N` is a commutative semiring and `M`is an `N`-module. * Maybe `Finsupp.weight w` and `Finsupp.degree` should have similar types, both `AddCommMonoidHom` or both functions. -/ variable {σ M : Type*} (w : σ → M) namespace Finsupp section AddCommMonoid variable [AddCommMonoid M] /-- The `weight` of the finitely supported function `f : σ →₀ ℕ` with respect to `w : σ → M` is the sum `∑(f i)•(w i)`. -/ noncomputable def weight : (σ →₀ ℕ) →+ M := (Finsupp.total σ M ℕ w).toAddMonoidHom @[deprecated weight (since := "2024-07-20")] alias _root_.MvPolynomial.weightedDegree := weight theorem weight_apply (f : σ →₀ ℕ) : weight w f = Finsupp.sum f (fun i c => c • w i) := rfl @[deprecated weight_apply (since := "2024-07-20")] alias _root_.MvPolynomial.weightedDegree_apply := weight_apply /-- A weight function is nontorsion if its values are not torsion. -/ class NonTorsionWeight (w : σ → M) : Prop where eq_zero_of_smul_eq_zero {n : ℕ} {s : σ} (h : n • w s = 0) : n = 0 /-- Without zero divisors, nonzero weight is a `NonTorsionWeight` -/ theorem nonTorsionWeight_of [NoZeroSMulDivisors ℕ M] (hw : ∀ i : σ, w i ≠ 0) : NonTorsionWeight w where eq_zero_of_smul_eq_zero {n s} h := by rw [smul_eq_zero, or_iff_not_imp_right] at h exact h (hw s) theorem NonTorsionWeight.ne_zero [NonTorsionWeight w] (s : σ) : w s ≠ 0 := fun h ↦ by rw [← one_smul ℕ (w s)] at h apply Nat.zero_ne_one.symm exact NonTorsionWeight.eq_zero_of_smul_eq_zero h end AddCommMonoid section OrderedAddCommMonoid theorem le_weight (w : σ → ℕ) {s : σ} (hs : w s ≠ 0) (f : σ →₀ ℕ) : f s ≤ weight w f := by classical simp only [weight_apply, Finsupp.sum] by_cases h : s ∈ f.support · rw [Finset.sum_eq_add_sum_diff_singleton h] refine le_trans ?_ (Nat.le_add_right _ _) apply Nat.le_mul_of_pos_right exact Nat.zero_lt_of_ne_zero hs · simp only [not_mem_support_iff] at h rw [h] apply zero_le variable [OrderedAddCommMonoid M] (w : σ → M) instance : SMulPosMono ℕ M := ⟨fun b hb m m' h ↦ by rw [← Nat.add_sub_of_le h, add_smul] exact le_add_of_nonneg_right (nsmul_nonneg hb (m' - m))⟩ variable {w} in theorem le_weight_of_ne_zero (hw : ∀ s, 0 ≤ w s) {s : σ} {f : σ →₀ ℕ} (hs : f s ≠ 0) : w s ≤ weight w f := by classical simp only [weight_apply, Finsupp.sum] trans f s • w s · apply le_smul_of_one_le_left (hw s) exact Nat.one_le_iff_ne_zero.mpr hs · rw [← Finsupp.mem_support_iff] at hs rw [Finset.sum_eq_add_sum_diff_singleton hs] exact le_add_of_nonneg_right <| Finset.sum_nonneg <| fun i _ ↦ nsmul_nonneg (hw i) (f i) end OrderedAddCommMonoid section CanonicallyOrderedAddCommMonoid variable {M : Type*} [CanonicallyOrderedAddCommMonoid M] (w : σ → M) theorem le_weight_of_ne_zero' {s : σ} {f : σ →₀ ℕ} (hs : f s ≠ 0) : w s ≤ weight w f := le_weight_of_ne_zero w (fun _ ↦ zero_le _) hs /-- If `M` is a `CanonicallyOrderedAddCommMonoid`, then `weight f` is zero iff `f=0. -/ theorem weight_eq_zero_iff_eq_zero (w : σ → M) [NonTorsionWeight w] {f : σ →₀ ℕ} : weight w f = 0 ↔ f = 0 := by classical constructor · intro h ext s simp only [Finsupp.coe_zero, Pi.zero_apply] by_contra hs apply NonTorsionWeight.ne_zero w _ rw [← nonpos_iff_eq_zero, ← h] exact le_weight_of_ne_zero' w hs · intro h rw [h, map_zero] end CanonicallyOrderedAddCommMonoid /-- The degree of a finsupp function. -/ def degree (d : σ →₀ ℕ) := ∑ i ∈ d.support, d i @[deprecated degree (since := "2024-07-20")] alias _root_.MvPolynomial.degree := degree lemma degree_eq_zero_iff (d : σ →₀ ℕ) : degree d = 0 ↔ d = 0 := by simp only [degree, Finset.sum_eq_zero_iff, Finsupp.mem_support_iff, ne_eq, Decidable.not_imp_self, DFunLike.ext_iff, Finsupp.coe_zero, Pi.zero_apply] @[deprecated degree_eq_zero_iff (since := "2024-07-20")] alias _root_.MvPolynomial.degree_eq_zero_iff := degree_eq_zero_iff @[simp] theorem degree_zero : degree (0 : σ →₀ ℕ) = 0 := by rw [degree_eq_zero_iff] theorem degree_eq_weight_one : degree (σ := σ) = weight 1 := by ext d simp only [degree, weight_apply, Pi.one_apply, smul_eq_mul, mul_one, Finsupp.sum] @[deprecated degree_eq_weight_one (since := "2024-07-20")] alias _root_.MvPolynomial.weightedDegree_one := degree_eq_weight_one theorem le_degree (s : σ) (f : σ →₀ ℕ) : f s ≤ degree f := by rw [degree_eq_weight_one] apply le_weight simp only [Pi.one_apply, ne_eq, one_ne_zero, not_false_eq_true] end Finsupp
Data\Finsupp\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.WellFounded import Mathlib.Data.Finsupp.Lex /-! # Well-foundedness of the lexicographic and product orders on `Finsupp` `Finsupp.Lex.wellFounded` and the two variants that follow it essentially say that if `(· > ·)` is a well order on `α`, `(· < ·)` is well-founded on `N`, and `0` is a bottom element in `N`, then the lexicographic `(· < ·)` is well-founded on `α →₀ N`. `Finsupp.Lex.wellFoundedLT_of_finite` says that if `α` is finite and equipped with a linear order and `(· < ·)` is well-founded on `N`, then the lexicographic `(· < ·)` is well-founded on `α →₀ N`. `Finsupp.wellFoundedLT` and `wellFoundedLT_of_finite` state the same results for the product order `(· < ·)`, but without the ordering conditions on `α`. All results are transferred from `DFinsupp` via `Finsupp.toDFinsupp`. -/ variable {α N : Type*} namespace Finsupp variable [Zero N] {r : α → α → Prop} {s : N → N → Prop} /-- Transferred from `DFinsupp.Lex.acc`. See the top of that file for an explanation for the appearance of the relation `rᶜ ⊓ (≠)`. -/ theorem Lex.acc (hbot : ∀ ⦃n⦄, ¬s n 0) (hs : WellFounded s) (x : α →₀ N) (h : ∀ a ∈ x.support, Acc (rᶜ ⊓ (· ≠ ·)) a) : Acc (Finsupp.Lex r s) x := by rw [lex_eq_invImage_dfinsupp_lex] classical refine InvImage.accessible toDFinsupp (DFinsupp.Lex.acc (fun _ => hbot) (fun _ => hs) _ ?_) simpa only [toDFinsupp_support] using h theorem Lex.wellFounded (hbot : ∀ ⦃n⦄, ¬s n 0) (hs : WellFounded s) (hr : WellFounded <| rᶜ ⊓ (· ≠ ·)) : WellFounded (Finsupp.Lex r s) := ⟨fun x => Lex.acc hbot hs x fun a _ => hr.apply a⟩ theorem Lex.wellFounded' (hbot : ∀ ⦃n⦄, ¬s n 0) (hs : WellFounded s) [IsTrichotomous α r] (hr : WellFounded (Function.swap r)) : WellFounded (Finsupp.Lex r s) := (lex_eq_invImage_dfinsupp_lex r s).symm ▸ InvImage.wf _ (DFinsupp.Lex.wellFounded' (fun _ => hbot) (fun _ => hs) hr) instance Lex.wellFoundedLT {α N} [LT α] [IsTrichotomous α (· < ·)] [hα : WellFoundedGT α] [CanonicallyOrderedAddCommMonoid N] [hN : WellFoundedLT N] : WellFoundedLT (Lex (α →₀ N)) := ⟨Lex.wellFounded' (fun n => (zero_le n).not_lt) hN.wf hα.wf⟩ variable (r) theorem Lex.wellFounded_of_finite [IsStrictTotalOrder α r] [Finite α] (hs : WellFounded s) : WellFounded (Finsupp.Lex r s) := InvImage.wf (@equivFunOnFinite α N _ _) (Pi.Lex.wellFounded r fun _ => hs) theorem Lex.wellFoundedLT_of_finite [LinearOrder α] [Finite α] [LT N] [hwf : WellFoundedLT N] : WellFoundedLT (Lex (α →₀ N)) := ⟨Finsupp.Lex.wellFounded_of_finite (· < ·) hwf.1⟩ protected theorem wellFoundedLT [Preorder N] [WellFoundedLT N] (hbot : ∀ n : N, ¬n < 0) : WellFoundedLT (α →₀ N) := ⟨InvImage.wf toDFinsupp (DFinsupp.wellFoundedLT fun _ a => hbot a).wf⟩ instance wellFoundedLT' {N} [CanonicallyOrderedAddCommMonoid N] [WellFoundedLT N] : WellFoundedLT (α →₀ N) := Finsupp.wellFoundedLT fun a => (zero_le a).not_lt instance wellFoundedLT_of_finite [Finite α] [Preorder N] [WellFoundedLT N] : WellFoundedLT (α →₀ N) := ⟨InvImage.wf equivFunOnFinite Function.wellFoundedLT.wf⟩ end Finsupp
Data\Fintype\Basic.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.Finset.Image import Mathlib.Data.List.FinRange /-! # Finite types This file defines a typeclass to state that a type is finite. ## Main declarations * `Fintype α`: Typeclass saying that a type is finite. It takes as fields a `Finset` and a proof that all terms of type `α` are in it. * `Finset.univ`: The finset of all elements of a fintype. See `Data.Fintype.Card` for the cardinality of a fintype, the equivalence with `Fin (Fintype.card α)`, and pigeonhole principles. ## Instances Instances for `Fintype` for * `{x // p x}` are in this file as `Fintype.subtype` * `Option α` are in `Data.Fintype.Option` * `α × β` are in `Data.Fintype.Prod` * `α ⊕ β` are in `Data.Fintype.Sum` * `Σ (a : α), β a` are in `Data.Fintype.Sigma` These files also contain appropriate `Infinite` instances for these types. `Infinite` instances for `ℕ`, `ℤ`, `Multiset α`, and `List α` are in `Data.Fintype.Lattice`. Types which have a surjection from/an injection to a `Fintype` are themselves fintypes. See `Fintype.ofInjective` and `Fintype.ofSurjective`. -/ assert_not_exists MonoidWithZero assert_not_exists MulAction open Function open Nat universe u v variable {α β γ : Type*} /-- `Fintype α` means that `α` is finite, i.e. there are only finitely many distinct elements of type `α`. The evidence of this is a finset `elems` (a list up to permutation without duplicates), together with a proof that everything of type `α` is in the list. -/ class Fintype (α : Type*) where /-- The `Finset` containing all elements of a `Fintype` -/ elems : Finset α /-- A proof that `elems` contains every element of the type -/ complete : ∀ x : α, x ∈ elems namespace Finset variable [Fintype α] {s t : Finset α} /-- `univ` is the universal finite set of type `Finset α` implied from the assumption `Fintype α`. -/ def univ : Finset α := @Fintype.elems α _ @[simp] theorem mem_univ (x : α) : x ∈ (univ : Finset α) := Fintype.complete x -- Porting note: removing @[simp], simp can prove it theorem mem_univ_val : ∀ x, x ∈ (univ : Finset α).1 := mem_univ theorem eq_univ_iff_forall : s = univ ↔ ∀ x, x ∈ s := by simp [ext_iff] theorem eq_univ_of_forall : (∀ x, x ∈ s) → s = univ := eq_univ_iff_forall.2 @[simp, norm_cast] theorem coe_univ : ↑(univ : Finset α) = (Set.univ : Set α) := by ext; simp @[simp, norm_cast] theorem coe_eq_univ : (s : Set α) = Set.univ ↔ s = univ := by rw [← coe_univ, coe_inj] theorem Nonempty.eq_univ [Subsingleton α] : s.Nonempty → s = univ := by rintro ⟨x, hx⟩ exact eq_univ_of_forall fun y => by rwa [Subsingleton.elim y x] theorem univ_nonempty_iff : (univ : Finset α).Nonempty ↔ Nonempty α := by rw [← coe_nonempty, coe_univ, Set.nonempty_iff_univ_nonempty] @[aesop unsafe apply (rule_sets := [finsetNonempty])] theorem univ_nonempty [Nonempty α] : (univ : Finset α).Nonempty := univ_nonempty_iff.2 ‹_› theorem univ_eq_empty_iff : (univ : Finset α) = ∅ ↔ IsEmpty α := by rw [← not_nonempty_iff, ← univ_nonempty_iff, not_nonempty_iff_eq_empty] theorem univ_nontrivial_iff : (Finset.univ : Finset α).Nontrivial ↔ Nontrivial α := by rw [Finset.Nontrivial, Finset.coe_univ, Set.nontrivial_univ_iff] theorem univ_nontrivial [h : Nontrivial α] : (Finset.univ : Finset α).Nontrivial := univ_nontrivial_iff.mpr h @[simp] theorem univ_eq_empty [IsEmpty α] : (univ : Finset α) = ∅ := univ_eq_empty_iff.2 ‹_› @[simp] theorem univ_unique [Unique α] : (univ : Finset α) = {default} := Finset.ext fun x => iff_of_true (mem_univ _) <| mem_singleton.2 <| Subsingleton.elim x default @[simp] theorem subset_univ (s : Finset α) : s ⊆ univ := fun a _ => mem_univ a instance boundedOrder : BoundedOrder (Finset α) := { inferInstanceAs (OrderBot (Finset α)) with top := univ le_top := subset_univ } @[simp] theorem top_eq_univ : (⊤ : Finset α) = univ := rfl theorem ssubset_univ_iff {s : Finset α} : s ⊂ univ ↔ s ≠ univ := @lt_top_iff_ne_top _ _ _ s @[simp] theorem univ_subset_iff {s : Finset α} : univ ⊆ s ↔ s = univ := @top_le_iff _ _ _ s theorem codisjoint_left : Codisjoint s t ↔ ∀ ⦃a⦄, a ∉ s → a ∈ t := by classical simp [codisjoint_iff, eq_univ_iff_forall, or_iff_not_imp_left] theorem codisjoint_right : Codisjoint s t ↔ ∀ ⦃a⦄, a ∉ t → a ∈ s := Codisjoint_comm.trans codisjoint_left section BooleanAlgebra variable [DecidableEq α] {a : α} instance booleanAlgebra : BooleanAlgebra (Finset α) := GeneralizedBooleanAlgebra.toBooleanAlgebra theorem sdiff_eq_inter_compl (s t : Finset α) : s \ t = s ∩ tᶜ := sdiff_eq theorem compl_eq_univ_sdiff (s : Finset α) : sᶜ = univ \ s := rfl @[simp] theorem mem_compl : a ∈ sᶜ ↔ a ∉ s := by simp [compl_eq_univ_sdiff] theorem not_mem_compl : a ∉ sᶜ ↔ a ∈ s := by rw [mem_compl, not_not] @[simp, norm_cast] theorem coe_compl (s : Finset α) : ↑sᶜ = (↑s : Set α)ᶜ := Set.ext fun _ => mem_compl @[simp] lemma compl_subset_compl : sᶜ ⊆ tᶜ ↔ t ⊆ s := @compl_le_compl_iff_le (Finset α) _ _ _ @[simp] lemma compl_ssubset_compl : sᶜ ⊂ tᶜ ↔ t ⊂ s := @compl_lt_compl_iff_lt (Finset α) _ _ _ lemma subset_compl_comm : s ⊆ tᶜ ↔ t ⊆ sᶜ := le_compl_iff_le_compl (α := Finset α) @[simp] lemma subset_compl_singleton : s ⊆ {a}ᶜ ↔ a ∉ s := by rw [subset_compl_comm, singleton_subset_iff, mem_compl] @[simp] theorem compl_empty : (∅ : Finset α)ᶜ = univ := compl_bot @[simp] theorem compl_univ : (univ : Finset α)ᶜ = ∅ := compl_top @[simp] theorem compl_eq_empty_iff (s : Finset α) : sᶜ = ∅ ↔ s = univ := compl_eq_bot @[simp] theorem compl_eq_univ_iff (s : Finset α) : sᶜ = univ ↔ s = ∅ := compl_eq_top @[simp] theorem union_compl (s : Finset α) : s ∪ sᶜ = univ := sup_compl_eq_top @[simp] theorem inter_compl (s : Finset α) : s ∩ sᶜ = ∅ := inf_compl_eq_bot @[simp] theorem compl_union (s t : Finset α) : (s ∪ t)ᶜ = sᶜ ∩ tᶜ := compl_sup @[simp] theorem compl_inter (s t : Finset α) : (s ∩ t)ᶜ = sᶜ ∪ tᶜ := compl_inf @[simp] theorem compl_erase : (s.erase a)ᶜ = insert a sᶜ := by ext simp only [or_iff_not_imp_left, mem_insert, not_and, mem_compl, mem_erase] @[simp] theorem compl_insert : (insert a s)ᶜ = sᶜ.erase a := by ext simp only [not_or, mem_insert, iff_self_iff, mem_compl, mem_erase] theorem insert_compl_insert (ha : a ∉ s) : insert a (insert a s)ᶜ = sᶜ := by simp_rw [compl_insert, insert_erase (mem_compl.2 ha)] @[simp] theorem insert_compl_self (x : α) : insert x ({x}ᶜ : Finset α) = univ := by rw [← compl_erase, erase_singleton, compl_empty] @[simp] theorem compl_filter (p : α → Prop) [DecidablePred p] [∀ x, Decidable ¬p x] : (univ.filter p)ᶜ = univ.filter fun x => ¬p x := ext <| by simp theorem compl_ne_univ_iff_nonempty (s : Finset α) : sᶜ ≠ univ ↔ s.Nonempty := by simp [eq_univ_iff_forall, Finset.Nonempty] theorem compl_singleton (a : α) : ({a} : Finset α)ᶜ = univ.erase a := by rw [compl_eq_univ_sdiff, sdiff_singleton_eq_erase] theorem insert_inj_on' (s : Finset α) : Set.InjOn (fun a => insert a s) (sᶜ : Finset α) := by rw [coe_compl] exact s.insert_inj_on theorem image_univ_of_surjective [Fintype β] {f : β → α} (hf : Surjective f) : univ.image f = univ := eq_univ_of_forall <| hf.forall.2 fun _ => mem_image_of_mem _ <| mem_univ _ @[simp] theorem image_univ_equiv [Fintype β] (f : β ≃ α) : univ.image f = univ := Finset.image_univ_of_surjective f.surjective @[simp] lemma univ_inter (s : Finset α) : univ ∩ s = s := by ext a; simp @[simp] lemma inter_univ (s : Finset α) : s ∩ univ = s := by rw [inter_comm, univ_inter] @[simp] lemma inter_eq_univ : s ∩ t = univ ↔ s = univ ∧ t = univ := inf_eq_top_iff end BooleanAlgebra -- @[simp] --Note this would loop with `Finset.univ_unique` lemma singleton_eq_univ [Subsingleton α] (a : α) : ({a} : Finset α) = univ := by ext b; simp [Subsingleton.elim a b] theorem map_univ_of_surjective [Fintype β] {f : β ↪ α} (hf : Surjective f) : univ.map f = univ := eq_univ_of_forall <| hf.forall.2 fun _ => mem_map_of_mem _ <| mem_univ _ @[simp] theorem map_univ_equiv [Fintype β] (f : β ≃ α) : univ.map f.toEmbedding = univ := map_univ_of_surjective f.surjective theorem univ_map_equiv_to_embedding {α β : Type*} [Fintype α] [Fintype β] (e : α ≃ β) : univ.map e.toEmbedding = univ := eq_univ_iff_forall.mpr fun b => mem_map.mpr ⟨e.symm b, mem_univ _, by simp⟩ @[simp] theorem univ_filter_exists (f : α → β) [Fintype β] [DecidablePred fun y => ∃ x, f x = y] [DecidableEq β] : (Finset.univ.filter fun y => ∃ x, f x = y) = Finset.univ.image f := by ext simp /-- Note this is a special case of `(Finset.image_preimage f univ _).symm`. -/ theorem univ_filter_mem_range (f : α → β) [Fintype β] [DecidablePred fun y => y ∈ Set.range f] [DecidableEq β] : (Finset.univ.filter fun y => y ∈ Set.range f) = Finset.univ.image f := by letI : DecidablePred (fun y => ∃ x, f x = y) := by simpa using ‹_› exact univ_filter_exists f theorem coe_filter_univ (p : α → Prop) [DecidablePred p] : (univ.filter p : Set α) = { x | p x } := by simp end Finset namespace Finset variable {s t : Finset α} @[simp] lemma subtype_eq_univ {p : α → Prop} [DecidablePred p] [Fintype {a // p a}] : s.subtype p = univ ↔ ∀ ⦃a⦄, p a → a ∈ s := by simp [ext_iff] @[simp] lemma subtype_univ [Fintype α] (p : α → Prop) [DecidablePred p] [Fintype {a // p a}] : univ.subtype p = univ := by simp lemma univ_map_subtype [Fintype α] (p : α → Prop) [DecidablePred p] [Fintype {a // p a}] : univ.map (Function.Embedding.subtype p) = univ.filter p := by rw [← subtype_map, subtype_univ] lemma univ_val_map_subtype_val [Fintype α] (p : α → Prop) [DecidablePred p] [Fintype {a // p a}] : univ.val.map ((↑) : { a // p a } → α) = (univ.filter p).val := by apply (map_val (Function.Embedding.subtype p) univ).symm.trans apply congr_arg apply univ_map_subtype lemma univ_val_map_subtype_restrict [Fintype α] (f : α → β) (p : α → Prop) [DecidablePred p] [Fintype {a // p a}] : univ.val.map (Subtype.restrict p f) = (univ.filter p).val.map f := by rw [← univ_val_map_subtype_val, Multiset.map_map, Subtype.restrict_def] end Finset open Finset Function namespace Fintype instance decidablePiFintype {α} {β : α → Type*} [∀ a, DecidableEq (β a)] [Fintype α] : DecidableEq (∀ a, β a) := fun f g => decidable_of_iff (∀ a ∈ @Fintype.elems α _, f a = g a) (by simp [Function.funext_iff, Fintype.complete]) instance decidableForallFintype {p : α → Prop} [DecidablePred p] [Fintype α] : Decidable (∀ a, p a) := decidable_of_iff (∀ a ∈ @univ α _, p a) (by simp) instance decidableExistsFintype {p : α → Prop} [DecidablePred p] [Fintype α] : Decidable (∃ a, p a) := decidable_of_iff (∃ a ∈ @univ α _, p a) (by simp) instance decidableMemRangeFintype [Fintype α] [DecidableEq β] (f : α → β) : DecidablePred (· ∈ Set.range f) := fun _ => Fintype.decidableExistsFintype instance decidableSubsingleton [Fintype α] [DecidableEq α] {s : Set α} [DecidablePred (· ∈ s)] : Decidable s.Subsingleton := decidable_of_iff (∀ a ∈ s, ∀ b ∈ s, a = b) Iff.rfl section BundledHoms instance decidableEqEquivFintype [DecidableEq β] [Fintype α] : DecidableEq (α ≃ β) := fun a b => decidable_of_iff (a.1 = b.1) Equiv.coe_fn_injective.eq_iff instance decidableEqEmbeddingFintype [DecidableEq β] [Fintype α] : DecidableEq (α ↪ β) := fun a b => decidable_of_iff ((a : α → β) = b) Function.Embedding.coe_injective.eq_iff end BundledHoms instance decidableInjectiveFintype [DecidableEq α] [DecidableEq β] [Fintype α] : DecidablePred (Injective : (α → β) → Prop) := fun x => by unfold Injective; infer_instance instance decidableSurjectiveFintype [DecidableEq β] [Fintype α] [Fintype β] : DecidablePred (Surjective : (α → β) → Prop) := fun x => by unfold Surjective; infer_instance instance decidableBijectiveFintype [DecidableEq α] [DecidableEq β] [Fintype α] [Fintype β] : DecidablePred (Bijective : (α → β) → Prop) := fun x => by unfold Bijective; infer_instance instance decidableRightInverseFintype [DecidableEq α] [Fintype α] (f : α → β) (g : β → α) : Decidable (Function.RightInverse f g) := show Decidable (∀ x, g (f x) = x) by infer_instance instance decidableLeftInverseFintype [DecidableEq β] [Fintype β] (f : α → β) (g : β → α) : Decidable (Function.LeftInverse f g) := show Decidable (∀ x, f (g x) = x) by infer_instance /-- Construct a proof of `Fintype α` from a universal multiset -/ def ofMultiset [DecidableEq α] (s : Multiset α) (H : ∀ x : α, x ∈ s) : Fintype α := ⟨s.toFinset, by simpa using H⟩ /-- Construct a proof of `Fintype α` from a universal list -/ def ofList [DecidableEq α] (l : List α) (H : ∀ x : α, x ∈ l) : Fintype α := ⟨l.toFinset, by simpa using H⟩ instance subsingleton (α : Type*) : Subsingleton (Fintype α) := ⟨fun ⟨s₁, h₁⟩ ⟨s₂, h₂⟩ => by congr; simp [Finset.ext_iff, h₁, h₂]⟩ instance (α : Type*) : Lean.Meta.FastSubsingleton (Fintype α) := {} /-- Given a predicate that can be represented by a finset, the subtype associated to the predicate is a fintype. -/ protected def subtype {p : α → Prop} (s : Finset α) (H : ∀ x : α, x ∈ s ↔ p x) : Fintype { x // p x } := ⟨⟨s.1.pmap Subtype.mk fun x => (H x).1, s.nodup.pmap fun _ _ _ _ => congr_arg Subtype.val⟩, fun ⟨x, px⟩ => Multiset.mem_pmap.2 ⟨x, (H x).2 px, rfl⟩⟩ /-- Construct a fintype from a finset with the same elements. -/ def ofFinset {p : Set α} (s : Finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) : Fintype p := Fintype.subtype s H /-- If `f : α → β` is a bijection and `α` is a fintype, then `β` is also a fintype. -/ def ofBijective [Fintype α] (f : α → β) (H : Function.Bijective f) : Fintype β := ⟨univ.map ⟨f, H.1⟩, fun b => let ⟨_, e⟩ := H.2 b e ▸ mem_map_of_mem _ (mem_univ _)⟩ /-- If `f : α → β` is a surjection and `α` is a fintype, then `β` is also a fintype. -/ def ofSurjective [DecidableEq β] [Fintype α] (f : α → β) (H : Function.Surjective f) : Fintype β := ⟨univ.image f, fun b => let ⟨_, e⟩ := H b e ▸ mem_image_of_mem _ (mem_univ _)⟩ end Fintype namespace Finset variable [Fintype α] [DecidableEq α] {s t : Finset α} @[simp] lemma filter_univ_mem (s : Finset α) : univ.filter (· ∈ s) = s := by simp [filter_mem_eq_inter] instance decidableCodisjoint : Decidable (Codisjoint s t) := decidable_of_iff _ codisjoint_left.symm instance decidableIsCompl : Decidable (IsCompl s t) := decidable_of_iff' _ isCompl_iff end Finset section Inv namespace Function variable [Fintype α] [DecidableEq β] namespace Injective variable {f : α → β} (hf : Function.Injective f) /-- The inverse of an `hf : injective` function `f : α → β`, of the type `↥(Set.range f) → α`. This is the computable version of `Function.invFun` that requires `Fintype α` and `DecidableEq β`, or the function version of applying `(Equiv.ofInjective f hf).symm`. This function should not usually be used for actual computation because for most cases, an explicit inverse can be stated that has better computational properties. This function computes by checking all terms `a : α` to find the `f a = b`, so it is O(N) where `N = Fintype.card α`. -/ def invOfMemRange : Set.range f → α := fun b => Finset.choose (fun a => f a = b) Finset.univ ((existsUnique_congr (by simp)).mp (hf.exists_unique_of_mem_range b.property)) theorem left_inv_of_invOfMemRange (b : Set.range f) : f (hf.invOfMemRange b) = b := (Finset.choose_spec (fun a => f a = b) _ _).right @[simp] theorem right_inv_of_invOfMemRange (a : α) : hf.invOfMemRange ⟨f a, Set.mem_range_self a⟩ = a := hf (Finset.choose_spec (fun a' => f a' = f a) _ _).right theorem invFun_restrict [Nonempty α] : (Set.range f).restrict (invFun f) = hf.invOfMemRange := by ext ⟨b, h⟩ apply hf simp [hf.left_inv_of_invOfMemRange, @invFun_eq _ _ _ f b (Set.mem_range.mp h)] theorem invOfMemRange_surjective : Function.Surjective hf.invOfMemRange := fun a => ⟨⟨f a, Set.mem_range_self a⟩, by simp⟩ end Injective namespace Embedding variable (f : α ↪ β) (b : Set.range f) /-- The inverse of an embedding `f : α ↪ β`, of the type `↥(Set.range f) → α`. This is the computable version of `Function.invFun` that requires `Fintype α` and `DecidableEq β`, or the function version of applying `(Equiv.ofInjective f f.injective).symm`. This function should not usually be used for actual computation because for most cases, an explicit inverse can be stated that has better computational properties. This function computes by checking all terms `a : α` to find the `f a = b`, so it is O(N) where `N = Fintype.card α`. -/ def invOfMemRange : α := f.injective.invOfMemRange b @[simp] theorem left_inv_of_invOfMemRange : f (f.invOfMemRange b) = b := f.injective.left_inv_of_invOfMemRange b @[simp] theorem right_inv_of_invOfMemRange (a : α) : f.invOfMemRange ⟨f a, Set.mem_range_self a⟩ = a := f.injective.right_inv_of_invOfMemRange a theorem invFun_restrict [Nonempty α] : (Set.range f).restrict (invFun f) = f.invOfMemRange := by ext ⟨b, h⟩ apply f.injective simp [f.left_inv_of_invOfMemRange, @invFun_eq _ _ _ f b (Set.mem_range.mp h)] theorem invOfMemRange_surjective : Function.Surjective f.invOfMemRange := fun a => ⟨⟨f a, Set.mem_range_self a⟩, by simp⟩ end Embedding end Function end Inv namespace Fintype /-- Given an injective function to a fintype, the domain is also a fintype. This is noncomputable because injectivity alone cannot be used to construct preimages. -/ noncomputable def ofInjective [Fintype β] (f : α → β) (H : Function.Injective f) : Fintype α := letI := Classical.dec if hα : Nonempty α then letI := Classical.inhabited_of_nonempty hα ofSurjective (invFun f) (invFun_surjective H) else ⟨∅, fun x => (hα ⟨x⟩).elim⟩ /-- If `f : α ≃ β` and `α` is a fintype, then `β` is also a fintype. -/ def ofEquiv (α : Type*) [Fintype α] (f : α ≃ β) : Fintype β := ofBijective _ f.bijective /-- Any subsingleton type with a witness is a fintype (with one term). -/ def ofSubsingleton (a : α) [Subsingleton α] : Fintype α := ⟨{a}, fun _ => Finset.mem_singleton.2 (Subsingleton.elim _ _)⟩ -- In principle, this could be a `simp` theorem but it applies to any occurence of `univ` and -- required unification of the (possibly very complex) `Fintype` instances. theorem univ_ofSubsingleton (a : α) [Subsingleton α] : @univ _ (ofSubsingleton a) = {a} := rfl /-- An empty type is a fintype. Not registered as an instance, to make sure that there aren't two conflicting `Fintype ι` instances around when casing over whether a fintype `ι` is empty or not. -/ def ofIsEmpty [IsEmpty α] : Fintype α := ⟨∅, isEmptyElim⟩ /-- Note: this lemma is specifically about `Fintype.ofIsEmpty`. For a statement about arbitrary `Fintype` instances, use `Finset.univ_eq_empty`. -/ theorem univ_ofIsEmpty [IsEmpty α] : @univ α Fintype.ofIsEmpty = ∅ := rfl instance : Fintype Empty := Fintype.ofIsEmpty instance : Fintype PEmpty := Fintype.ofIsEmpty end Fintype namespace Set variable {s t : Set α} /-- Construct a finset enumerating a set `s`, given a `Fintype` instance. -/ def toFinset (s : Set α) [Fintype s] : Finset α := (@Finset.univ s _).map <| Function.Embedding.subtype _ @[congr] theorem toFinset_congr {s t : Set α} [Fintype s] [Fintype t] (h : s = t) : toFinset s = toFinset t := by subst h; congr! @[simp] theorem mem_toFinset {s : Set α} [Fintype s] {a : α} : a ∈ s.toFinset ↔ a ∈ s := by simp [toFinset] /-- Many `Fintype` instances for sets are defined using an extensionally equal `Finset`. Rewriting `s.toFinset` with `Set.toFinset_ofFinset` replaces the term with such a `Finset`. -/ theorem toFinset_ofFinset {p : Set α} (s : Finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) : @Set.toFinset _ p (Fintype.ofFinset s H) = s := Finset.ext fun x => by rw [@mem_toFinset _ _ (id _), H] /-- Membership of a set with a `Fintype` instance is decidable. Using this as an instance leads to potential loops with `Subtype.fintype` under certain decidability assumptions, so it should only be declared a local instance. -/ def decidableMemOfFintype [DecidableEq α] (s : Set α) [Fintype s] (a) : Decidable (a ∈ s) := decidable_of_iff _ mem_toFinset @[simp] theorem coe_toFinset (s : Set α) [Fintype s] : (↑s.toFinset : Set α) = s := Set.ext fun _ => mem_toFinset @[simp, aesop safe apply (rule_sets := [finsetNonempty])] theorem toFinset_nonempty {s : Set α} [Fintype s] : s.toFinset.Nonempty ↔ s.Nonempty := by rw [← Finset.coe_nonempty, coe_toFinset] @[simp] theorem toFinset_inj {s t : Set α} [Fintype s] [Fintype t] : s.toFinset = t.toFinset ↔ s = t := ⟨fun h => by rw [← s.coe_toFinset, h, t.coe_toFinset], fun h => by simp [h]⟩ @[mono] theorem toFinset_subset_toFinset [Fintype s] [Fintype t] : s.toFinset ⊆ t.toFinset ↔ s ⊆ t := by simp [Finset.subset_iff, Set.subset_def] @[simp] theorem toFinset_ssubset [Fintype s] {t : Finset α} : s.toFinset ⊂ t ↔ s ⊂ t := by rw [← Finset.coe_ssubset, coe_toFinset] @[simp] theorem subset_toFinset {s : Finset α} [Fintype t] : s ⊆ t.toFinset ↔ ↑s ⊆ t := by rw [← Finset.coe_subset, coe_toFinset] @[simp] theorem ssubset_toFinset {s : Finset α} [Fintype t] : s ⊂ t.toFinset ↔ ↑s ⊂ t := by rw [← Finset.coe_ssubset, coe_toFinset] @[mono] theorem toFinset_ssubset_toFinset [Fintype s] [Fintype t] : s.toFinset ⊂ t.toFinset ↔ s ⊂ t := by simp only [Finset.ssubset_def, toFinset_subset_toFinset, ssubset_def] @[simp] theorem toFinset_subset [Fintype s] {t : Finset α} : s.toFinset ⊆ t ↔ s ⊆ t := by rw [← Finset.coe_subset, coe_toFinset] alias ⟨_, toFinset_mono⟩ := toFinset_subset_toFinset alias ⟨_, toFinset_strict_mono⟩ := toFinset_ssubset_toFinset @[simp] theorem disjoint_toFinset [Fintype s] [Fintype t] : Disjoint s.toFinset t.toFinset ↔ Disjoint s t := by simp only [← disjoint_coe, coe_toFinset] section DecidableEq variable [DecidableEq α] (s t) [Fintype s] [Fintype t] @[simp] theorem toFinset_inter [Fintype (s ∩ t : Set _)] : (s ∩ t).toFinset = s.toFinset ∩ t.toFinset := by ext simp @[simp] theorem toFinset_union [Fintype (s ∪ t : Set _)] : (s ∪ t).toFinset = s.toFinset ∪ t.toFinset := by ext simp @[simp] theorem toFinset_diff [Fintype (s \ t : Set _)] : (s \ t).toFinset = s.toFinset \ t.toFinset := by ext simp open scoped symmDiff in @[simp] theorem toFinset_symmDiff [Fintype (s ∆ t : Set _)] : (s ∆ t).toFinset = s.toFinset ∆ t.toFinset := by ext simp [mem_symmDiff, Finset.mem_symmDiff] @[simp] theorem toFinset_compl [Fintype α] [Fintype (sᶜ : Set _)] : sᶜ.toFinset = s.toFinsetᶜ := by ext simp end DecidableEq -- TODO The `↥` circumvents an elaboration bug. See comment on `Set.toFinset_univ`. @[simp] theorem toFinset_empty [Fintype (∅ : Set α)] : (∅ : Set α).toFinset = ∅ := by ext simp /- TODO Without the coercion arrow (`↥`) there is an elaboration bug in the following two; it essentially infers `Fintype.{v} (Set.univ.{u} : Set α)` with `v` and `u` distinct. Reported in leanprover-community/lean#672 -/ @[simp] theorem toFinset_univ [Fintype α] [Fintype (Set.univ : Set α)] : (Set.univ : Set α).toFinset = Finset.univ := by ext simp @[simp] theorem toFinset_eq_empty [Fintype s] : s.toFinset = ∅ ↔ s = ∅ := by let A : Fintype (∅ : Set α) := Fintype.ofIsEmpty rw [← toFinset_empty, toFinset_inj] @[simp] theorem toFinset_eq_univ [Fintype α] [Fintype s] : s.toFinset = Finset.univ ↔ s = univ := by rw [← coe_inj, coe_toFinset, coe_univ] @[simp] theorem toFinset_setOf [Fintype α] (p : α → Prop) [DecidablePred p] [Fintype { x | p x }] : { x | p x }.toFinset = Finset.univ.filter p := by ext simp --@[simp] Porting note: removing simp, simp can prove it theorem toFinset_ssubset_univ [Fintype α] {s : Set α} [Fintype s] : s.toFinset ⊂ Finset.univ ↔ s ⊂ univ := by rw [← coe_ssubset, coe_toFinset, coe_univ] @[simp] theorem toFinset_image [DecidableEq β] (f : α → β) (s : Set α) [Fintype s] [Fintype (f '' s)] : (f '' s).toFinset = s.toFinset.image f := Finset.coe_injective <| by simp @[simp] theorem toFinset_range [DecidableEq α] [Fintype β] (f : β → α) [Fintype (Set.range f)] : (Set.range f).toFinset = Finset.univ.image f := by ext simp @[simp] -- Porting note: new attribute theorem toFinset_singleton (a : α) [Fintype ({a} : Set α)] : ({a} : Set α).toFinset = {a} := by ext simp @[simp] theorem toFinset_insert [DecidableEq α] {a : α} {s : Set α} [Fintype (insert a s : Set α)] [Fintype s] : (insert a s).toFinset = insert a s.toFinset := by ext simp theorem filter_mem_univ_eq_toFinset [Fintype α] (s : Set α) [Fintype s] [DecidablePred (· ∈ s)] : Finset.univ.filter (· ∈ s) = s.toFinset := by ext simp only [Finset.mem_univ, decide_eq_true_eq, forall_true_left, mem_filter, true_and, mem_toFinset] end Set @[simp] theorem Finset.toFinset_coe (s : Finset α) [Fintype (s : Set α)] : (s : Set α).toFinset = s := ext fun _ => Set.mem_toFinset instance Fin.fintype (n : ℕ) : Fintype (Fin n) := ⟨⟨List.finRange n, List.nodup_finRange n⟩, List.mem_finRange⟩ theorem Fin.univ_def (n : ℕ) : (univ : Finset (Fin n)) = ⟨List.finRange n, List.nodup_finRange n⟩ := rfl @[simp] theorem List.toFinset_finRange (n : ℕ) : (List.finRange n).toFinset = Finset.univ := by ext; simp @[simp] theorem Fin.univ_val_map {n : ℕ} (f : Fin n → α) : Finset.univ.val.map f = List.ofFn f := by simp [List.ofFn_eq_map, univ_def] theorem Fin.univ_image_def {n : ℕ} [DecidableEq α] (f : Fin n → α) : Finset.univ.image f = (List.ofFn f).toFinset := by simp [Finset.image] theorem Fin.univ_map_def {n : ℕ} (f : Fin n ↪ α) : Finset.univ.map f = ⟨List.ofFn f, List.nodup_ofFn.mpr f.injective⟩ := by simp [Finset.map] @[simp] theorem Fin.image_succAbove_univ {n : ℕ} (i : Fin (n + 1)) : univ.image i.succAbove = {i}ᶜ := by ext m simp @[simp] theorem Fin.image_succ_univ (n : ℕ) : (univ : Finset (Fin n)).image Fin.succ = {0}ᶜ := by rw [← Fin.succAbove_zero, Fin.image_succAbove_univ] @[simp] theorem Fin.image_castSucc (n : ℕ) : (univ : Finset (Fin n)).image Fin.castSucc = {Fin.last n}ᶜ := by rw [← Fin.succAbove_last, Fin.image_succAbove_univ] /- The following three lemmas use `Finset.cons` instead of `insert` and `Finset.map` instead of `Finset.image` to reduce proof obligations downstream. -/ /-- Embed `Fin n` into `Fin (n + 1)` by prepending zero to the `univ` -/ theorem Fin.univ_succ (n : ℕ) : (univ : Finset (Fin (n + 1))) = Finset.cons 0 (univ.map ⟨Fin.succ, Fin.succ_injective _⟩) (by simp [map_eq_image]) := by simp [map_eq_image] /-- Embed `Fin n` into `Fin (n + 1)` by appending a new `Fin.last n` to the `univ` -/ theorem Fin.univ_castSuccEmb (n : ℕ) : (univ : Finset (Fin (n + 1))) = Finset.cons (Fin.last n) (univ.map Fin.castSuccEmb) (by simp [map_eq_image]) := by simp [map_eq_image] /-- Embed `Fin n` into `Fin (n + 1)` by inserting around a specified pivot `p : Fin (n + 1)` into the `univ` -/ theorem Fin.univ_succAbove (n : ℕ) (p : Fin (n + 1)) : (univ : Finset (Fin (n + 1))) = Finset.cons p (univ.map <| Fin.succAboveEmb p) (by simp) := by simp [map_eq_image] @[simp] theorem Fin.univ_image_get [DecidableEq α] (l : List α) : Finset.univ.image l.get = l.toFinset := by simp [univ_image_def] @[simp] theorem Fin.univ_image_getElem' [DecidableEq β] (l : List α) (f : α → β) : Finset.univ.image (fun i : Fin l.length => f <| l[(i : Nat)]) = (l.map f).toFinset := by simp only [univ_image_def, List.ofFn_getElem_eq_map] theorem Fin.univ_image_get' [DecidableEq β] (l : List α) (f : α → β) : Finset.univ.image (f <| l.get ·) = (l.map f).toFinset := by simp @[instance] def Unique.fintype {α : Type*} [Unique α] : Fintype α := Fintype.ofSubsingleton default /-- Short-circuit instance to decrease search for `Unique.fintype`, since that relies on a subsingleton elimination for `Unique`. -/ instance Fintype.subtypeEq (y : α) : Fintype { x // x = y } := Fintype.subtype {y} (by simp) /-- Short-circuit instance to decrease search for `Unique.fintype`, since that relies on a subsingleton elimination for `Unique`. -/ instance Fintype.subtypeEq' (y : α) : Fintype { x // y = x } := Fintype.subtype {y} (by simp [eq_comm]) -- Porting note: removing @[simp], simp can prove it theorem Fintype.univ_empty : @univ Empty _ = ∅ := rfl --@[simp] Porting note: removing simp, simp can prove it theorem Fintype.univ_pempty : @univ PEmpty _ = ∅ := rfl instance Unit.fintype : Fintype Unit := Fintype.ofSubsingleton () theorem Fintype.univ_unit : @univ Unit _ = {()} := rfl instance PUnit.fintype : Fintype PUnit := Fintype.ofSubsingleton PUnit.unit --@[simp] Porting note: removing simp, simp can prove it theorem Fintype.univ_punit : @univ PUnit _ = {PUnit.unit} := rfl instance Bool.fintype : Fintype Bool := ⟨⟨{true, false}, by simp⟩, fun x => by cases x <;> simp⟩ @[simp] theorem Fintype.univ_bool : @univ Bool _ = {true, false} := rfl instance Additive.fintype : ∀ [Fintype α], Fintype (Additive α) := Fintype.ofEquiv α Additive.ofMul instance Multiplicative.fintype : ∀ [Fintype α], Fintype (Multiplicative α) := Fintype.ofEquiv α Multiplicative.ofAdd /-- Given that `α × β` is a fintype, `α` is also a fintype. -/ def Fintype.prodLeft {α β} [DecidableEq α] [Fintype (α × β)] [Nonempty β] : Fintype α := ⟨(@univ (α × β) _).image Prod.fst, fun a => by simp⟩ /-- Given that `α × β` is a fintype, `β` is also a fintype. -/ def Fintype.prodRight {α β} [DecidableEq β] [Fintype (α × β)] [Nonempty α] : Fintype β := ⟨(@univ (α × β) _).image Prod.snd, fun b => by simp⟩ instance ULift.fintype (α : Type*) [Fintype α] : Fintype (ULift α) := Fintype.ofEquiv _ Equiv.ulift.symm instance PLift.fintype (α : Type*) [Fintype α] : Fintype (PLift α) := Fintype.ofEquiv _ Equiv.plift.symm instance OrderDual.fintype (α : Type*) [Fintype α] : Fintype αᵒᵈ := ‹Fintype α› instance OrderDual.finite (α : Type*) [Finite α] : Finite αᵒᵈ := ‹Finite α› instance Lex.fintype (α : Type*) [Fintype α] : Fintype (Lex α) := ‹Fintype α› section Finset /-! ### `Fintype (s : Finset α)` -/ instance Finset.fintypeCoeSort {α : Type u} (s : Finset α) : Fintype s := ⟨s.attach, s.mem_attach⟩ @[simp] theorem Finset.univ_eq_attach {α : Type u} (s : Finset α) : (univ : Finset s) = s.attach := rfl end Finset theorem Fintype.coe_image_univ [Fintype α] [DecidableEq β] {f : α → β} : ↑(Finset.image f Finset.univ) = Set.range f := by ext x simp instance List.Subtype.fintype [DecidableEq α] (l : List α) : Fintype { x // x ∈ l } := Fintype.ofList l.attach l.mem_attach instance Multiset.Subtype.fintype [DecidableEq α] (s : Multiset α) : Fintype { x // x ∈ s } := Fintype.ofMultiset s.attach s.mem_attach instance Finset.Subtype.fintype (s : Finset α) : Fintype { x // x ∈ s } := ⟨s.attach, s.mem_attach⟩ instance FinsetCoe.fintype (s : Finset α) : Fintype (↑s : Set α) := Finset.Subtype.fintype s theorem Finset.attach_eq_univ {s : Finset α} : s.attach = Finset.univ := rfl instance PLift.fintypeProp (p : Prop) [Decidable p] : Fintype (PLift p) := ⟨if h : p then {⟨h⟩} else ∅, fun ⟨h⟩ => by simp [h]⟩ instance Prop.fintype : Fintype Prop := ⟨⟨{True, False}, by simp [true_ne_false]⟩, by simpa using em⟩ @[simp] theorem Fintype.univ_Prop : (Finset.univ : Finset Prop) = {True, False} := Finset.eq_of_veq <| by simp; rfl instance Subtype.fintype (p : α → Prop) [DecidablePred p] [Fintype α] : Fintype { x // p x } := Fintype.subtype (univ.filter p) (by simp) /-- A set on a fintype, when coerced to a type, is a fintype. -/ def setFintype [Fintype α] (s : Set α) [DecidablePred (· ∈ s)] : Fintype s := Subtype.fintype fun x => x ∈ s namespace Fintype variable [Fintype α] /-- Given `Fintype α`, `finsetEquivSet` is the equiv between `Finset α` and `Set α`. (All sets on a finite type are finite.) -/ noncomputable def finsetEquivSet : Finset α ≃ Set α where toFun := (↑) invFun := by classical exact fun s => s.toFinset left_inv s := by convert Finset.toFinset_coe s right_inv s := by classical exact s.coe_toFinset @[simp, norm_cast] lemma coe_finsetEquivSet : ⇑finsetEquivSet = ((↑) : Finset α → Set α) := rfl @[simp] lemma finsetEquivSet_apply (s : Finset α) : finsetEquivSet s = s := rfl @[simp] lemma finsetEquivSet_symm_apply (s : Set α) [Fintype s] : finsetEquivSet.symm s = s.toFinset := by simp [finsetEquivSet] /-- Given a fintype `α`, `finsetOrderIsoSet` is the order isomorphism between `Finset α` and `Set α` (all sets on a finite type are finite). -/ @[simps toEquiv] noncomputable def finsetOrderIsoSet : Finset α ≃o Set α where toEquiv := finsetEquivSet map_rel_iff' := Finset.coe_subset @[simp, norm_cast] lemma coe_finsetOrderIsoSet : ⇑finsetOrderIsoSet = ((↑) : Finset α → Set α) := rfl @[simp] lemma coe_finsetOrderIsoSet_symm : ⇑(finsetOrderIsoSet : Finset α ≃o Set α).symm = ⇑finsetEquivSet.symm := rfl end Fintype instance Quotient.fintype [Fintype α] (s : Setoid α) [DecidableRel ((· ≈ ·) : α → α → Prop)] : Fintype (Quotient s) := Fintype.ofSurjective Quotient.mk'' Quotient.surjective_Quotient_mk'' instance PSigma.fintypePropLeft {α : Prop} {β : α → Type*} [Decidable α] [∀ a, Fintype (β a)] : Fintype (Σ'a, β a) := if h : α then Fintype.ofEquiv (β h) ⟨fun x => ⟨h, x⟩, PSigma.snd, fun _ => rfl, fun ⟨_, _⟩ => rfl⟩ else ⟨∅, fun x => (h x.1).elim⟩ instance PSigma.fintypePropRight {α : Type*} {β : α → Prop} [∀ a, Decidable (β a)] [Fintype α] : Fintype (Σ'a, β a) := Fintype.ofEquiv { a // β a } ⟨fun ⟨x, y⟩ => ⟨x, y⟩, fun ⟨x, y⟩ => ⟨x, y⟩, fun ⟨_, _⟩ => rfl, fun ⟨_, _⟩ => rfl⟩ instance PSigma.fintypePropProp {α : Prop} {β : α → Prop} [Decidable α] [∀ a, Decidable (β a)] : Fintype (Σ'a, β a) := if h : ∃ a, β a then ⟨{⟨h.fst, h.snd⟩}, fun ⟨_, _⟩ => by simp⟩ else ⟨∅, fun ⟨x, y⟩ => (h ⟨x, y⟩).elim⟩ instance pfunFintype (p : Prop) [Decidable p] (α : p → Type*) [∀ hp, Fintype (α hp)] : Fintype (∀ hp : p, α hp) := if hp : p then Fintype.ofEquiv (α hp) ⟨fun a _ => a, fun f => f hp, fun _ => rfl, fun _ => rfl⟩ else ⟨singleton fun h => (hp h).elim, fun h => mem_singleton.2 (funext fun x => by contradiction)⟩ theorem mem_image_univ_iff_mem_range {α β : Type*} [Fintype α] [DecidableEq β] {f : α → β} {b : β} : b ∈ univ.image f ↔ b ∈ Set.range f := by simp namespace Fintype section Choose open Fintype Equiv variable [Fintype α] (p : α → Prop) [DecidablePred p] /-- Given a fintype `α` and a predicate `p`, associate to a proof that there is a unique element of `α` satisfying `p` this unique element, as an element of the corresponding subtype. -/ def chooseX (hp : ∃! a : α, p a) : { a // p a } := ⟨Finset.choose p univ (by simpa), Finset.choose_property _ _ _⟩ /-- Given a fintype `α` and a predicate `p`, associate to a proof that there is a unique element of `α` satisfying `p` this unique element, as an element of `α`. -/ def choose (hp : ∃! a, p a) : α := chooseX p hp theorem choose_spec (hp : ∃! a, p a) : p (choose p hp) := (chooseX p hp).property -- @[simp] Porting note: removing simp, never applies theorem choose_subtype_eq {α : Type*} (p : α → Prop) [Fintype { a : α // p a }] [DecidableEq α] (x : { a : α // p a }) (h : ∃! a : { a // p a }, (a : α) = x := ⟨x, rfl, fun y hy => by simpa [Subtype.ext_iff] using hy⟩) : Fintype.choose (fun y : { a : α // p a } => (y : α) = x) h = x := by rw [Subtype.ext_iff, Fintype.choose_spec (fun y : { a : α // p a } => (y : α) = x) _] end Choose section BijectionInverse open Function variable [Fintype α] [DecidableEq β] {f : α → β} /-- `bijInv f` is the unique inverse to a bijection `f`. This acts as a computable alternative to `Function.invFun`. -/ def bijInv (f_bij : Bijective f) (b : β) : α := Fintype.choose (fun a => f a = b) (by rcases f_bij.right b with ⟨a', fa_eq_b⟩ rw [← fa_eq_b] exact ⟨a', ⟨rfl, fun a h => f_bij.left h⟩⟩) theorem leftInverse_bijInv (f_bij : Bijective f) : LeftInverse (bijInv f_bij) f := fun a => f_bij.left (choose_spec (fun a' => f a' = f a) _) theorem rightInverse_bijInv (f_bij : Bijective f) : RightInverse (bijInv f_bij) f := fun b => choose_spec (fun a' => f a' = b) _ theorem bijective_bijInv (f_bij : Bijective f) : Bijective (bijInv f_bij) := ⟨(rightInverse_bijInv _).injective, (leftInverse_bijInv _).surjective⟩ end BijectionInverse end Fintype section Trunc /-- For `s : Multiset α`, we can lift the existential statement that `∃ x, x ∈ s` to a `Trunc α`. -/ def truncOfMultisetExistsMem {α} (s : Multiset α) : (∃ x, x ∈ s) → Trunc α := Quotient.recOnSubsingleton s fun l h => match l, h with | [], _ => False.elim (by tauto) | a :: _, _ => Trunc.mk a /-- A `Nonempty` `Fintype` constructively contains an element. -/ def truncOfNonemptyFintype (α) [Nonempty α] [Fintype α] : Trunc α := truncOfMultisetExistsMem Finset.univ.val (by simp) /-- By iterating over the elements of a fintype, we can lift an existential statement `∃ a, P a` to `Trunc (Σ' a, P a)`, containing data. -/ def truncSigmaOfExists {α} [Fintype α] {P : α → Prop} [DecidablePred P] (h : ∃ a, P a) : Trunc (Σ'a, P a) := @truncOfNonemptyFintype (Σ'a, P a) ((Exists.elim h) fun a ha => ⟨⟨a, ha⟩⟩) _ end Trunc namespace Multiset variable [Fintype α] [Fintype β] @[simp] theorem count_univ [DecidableEq α] (a : α) : count a Finset.univ.val = 1 := count_eq_one_of_mem Finset.univ.nodup (Finset.mem_univ _) @[simp] theorem map_univ_val_equiv (e : α ≃ β) : map e univ.val = univ.val := by rw [← congr_arg Finset.val (Finset.map_univ_equiv e), Finset.map_val, Equiv.coe_toEmbedding] /-- For functions on finite sets, they are bijections iff they map universes into universes. -/ @[simp] theorem bijective_iff_map_univ_eq_univ (f : α → β) : f.Bijective ↔ map f (Finset.univ : Finset α).val = univ.val := ⟨fun bij ↦ congr_arg (·.val) (map_univ_equiv <| Equiv.ofBijective f bij), fun eq ↦ ⟨ fun a₁ a₂ ↦ inj_on_of_nodup_map (eq.symm ▸ univ.nodup) _ (mem_univ a₁) _ (mem_univ a₂), fun b ↦ have ⟨a, _, h⟩ := mem_map.mp (eq.symm ▸ mem_univ_val b); ⟨a, h⟩⟩⟩ end Multiset /-- Auxiliary definition to show `exists_seq_of_forall_finset_exists`. -/ noncomputable def seqOfForallFinsetExistsAux {α : Type*} [DecidableEq α] (P : α → Prop) (r : α → α → Prop) (h : ∀ s : Finset α, ∃ y, (∀ x ∈ s, P x) → P y ∧ ∀ x ∈ s, r x y) : ℕ → α | n => Classical.choose (h (Finset.image (fun i : Fin n => seqOfForallFinsetExistsAux P r h i) (Finset.univ : Finset (Fin n)))) /-- Induction principle to build a sequence, by adding one point at a time satisfying a given relation with respect to all the previously chosen points. More precisely, Assume that, for any finite set `s`, one can find another point satisfying some relation `r` with respect to all the points in `s`. Then one may construct a function `f : ℕ → α` such that `r (f m) (f n)` holds whenever `m < n`. We also ensure that all constructed points satisfy a given predicate `P`. -/ theorem exists_seq_of_forall_finset_exists {α : Type*} (P : α → Prop) (r : α → α → Prop) (h : ∀ s : Finset α, (∀ x ∈ s, P x) → ∃ y, P y ∧ ∀ x ∈ s, r x y) : ∃ f : ℕ → α, (∀ n, P (f n)) ∧ ∀ m n, m < n → r (f m) (f n) := by classical have : Nonempty α := by rcases h ∅ (by simp) with ⟨y, _⟩ exact ⟨y⟩ choose! F hF using h have h' : ∀ s : Finset α, ∃ y, (∀ x ∈ s, P x) → P y ∧ ∀ x ∈ s, r x y := fun s => ⟨F s, hF s⟩ set f := seqOfForallFinsetExistsAux P r h' with hf have A : ∀ n : ℕ, P (f n) := by intro n induction' n using Nat.strong_induction_on with n IH have IH' : ∀ x : Fin n, P (f x) := fun n => IH n.1 n.2 rw [hf, seqOfForallFinsetExistsAux] exact (Classical.choose_spec (h' (Finset.image (fun i : Fin n => f i) (Finset.univ : Finset (Fin n)))) (by simp [IH'])).1 refine ⟨f, A, fun m n hmn => ?_⟩ conv_rhs => rw [hf] rw [seqOfForallFinsetExistsAux] apply (Classical.choose_spec (h' (Finset.image (fun i : Fin n => f i) (Finset.univ : Finset (Fin n)))) (by simp [A])).2 exact Finset.mem_image.2 ⟨⟨m, hmn⟩, Finset.mem_univ _, rfl⟩ /-- Induction principle to build a sequence, by adding one point at a time satisfying a given symmetric relation with respect to all the previously chosen points. More precisely, Assume that, for any finite set `s`, one can find another point satisfying some relation `r` with respect to all the points in `s`. Then one may construct a function `f : ℕ → α` such that `r (f m) (f n)` holds whenever `m ≠ n`. We also ensure that all constructed points satisfy a given predicate `P`. -/ theorem exists_seq_of_forall_finset_exists' {α : Type*} (P : α → Prop) (r : α → α → Prop) [IsSymm α r] (h : ∀ s : Finset α, (∀ x ∈ s, P x) → ∃ y, P y ∧ ∀ x ∈ s, r x y) : ∃ f : ℕ → α, (∀ n, P (f n)) ∧ Pairwise fun m n => r (f m) (f n) := by rcases exists_seq_of_forall_finset_exists P r h with ⟨f, hf, hf'⟩ refine ⟨f, hf, fun m n hmn => ?_⟩ rcases lt_trichotomy m n with (h | rfl | h) · exact hf' m n h · exact (hmn rfl).elim · apply symm exact hf' n m h open Batteries.ExtendedBinder Lean Meta /-- `finset% t` elaborates `t` as a `Finset`. If `t` is a `Set`, then inserts `Set.toFinset`. Does not make use of the expected type; useful for big operators over finsets. ``` #check finset% Finset.range 2 -- Finset Nat #check finset% (Set.univ : Set Bool) -- Finset Bool ``` -/ elab (name := finsetStx) "finset% " t:term : term => do let u ← mkFreshLevelMVar let ty ← mkFreshExprMVar (mkSort (.succ u)) let x ← Elab.Term.elabTerm t (mkApp (.const ``Finset [u]) ty) let xty ← whnfR (← inferType x) if xty.isAppOfArity ``Set 1 then Elab.Term.elabAppArgs (.const ``Set.toFinset [u]) #[] #[.expr x] none false false else return x open Lean.Elab.Term.Quotation in /-- `quot_precheck` for the `finset%` syntax. -/ @[quot_precheck finsetStx] def precheckFinsetStx : Precheck | `(finset% $t) => precheck t | _ => Elab.throwUnsupportedSyntax
Data\Fintype\BigOperators.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.Fintype.Option import Mathlib.Data.Fintype.Sigma import Mathlib.Data.Fintype.Sum import Mathlib.Data.Fintype.Prod import Mathlib.Data.Fintype.Vector import Mathlib.Algebra.BigOperators.Option /-! Results about "big operations" over a `Fintype`, and consequent results about cardinalities of certain types. ## Implementation note This content had previously been in `Data.Fintype.Basic`, but was moved here to avoid requiring `Algebra.BigOperators` (and hence many other imports) as a dependency of `Fintype`. However many of the results here really belong in `Algebra.BigOperators.Group.Finset` and should be moved at some point. -/ open Mathlib assert_not_exists MulAction universe u v variable {α : Type*} {β : Type*} {γ : Type*} namespace Fintype @[to_additive] theorem prod_bool [CommMonoid α] (f : Bool → α) : ∏ b, f b = f true * f false := by simp theorem card_eq_sum_ones {α} [Fintype α] : Fintype.card α = ∑ _a : α, 1 := Finset.card_eq_sum_ones _ section open Finset variable {ι : Type*} [DecidableEq ι] [Fintype ι] @[to_additive] theorem prod_extend_by_one [CommMonoid α] (s : Finset ι) (f : ι → α) : ∏ i, (if i ∈ s then f i else 1) = ∏ i ∈ s, f i := by rw [← prod_filter, filter_mem_eq_inter, univ_inter] end section variable {M : Type*} [Fintype α] [CommMonoid M] @[to_additive] theorem prod_eq_one (f : α → M) (h : ∀ a, f a = 1) : ∏ a, f a = 1 := Finset.prod_eq_one fun a _ha => h a @[to_additive] theorem prod_congr (f g : α → M) (h : ∀ a, f a = g a) : ∏ a, f a = ∏ a, g a := Finset.prod_congr rfl fun a _ha => h a @[to_additive] theorem prod_eq_single {f : α → M} (a : α) (h : ∀ x ≠ a, f x = 1) : ∏ x, f x = f a := Finset.prod_eq_single a (fun x _ hx => h x hx) fun ha => (ha (Finset.mem_univ a)).elim @[to_additive] theorem prod_eq_mul {f : α → M} (a b : α) (h₁ : a ≠ b) (h₂ : ∀ x, x ≠ a ∧ x ≠ b → f x = 1) : ∏ x, f x = f a * f b := by apply Finset.prod_eq_mul a b h₁ fun x _ hx => h₂ x hx <;> exact fun hc => (hc (Finset.mem_univ _)).elim /-- If a product of a `Finset` of a subsingleton type has a given value, so do the terms in that product. -/ @[to_additive "If a sum of a `Finset` of a subsingleton type has a given value, so do the terms in that sum."] theorem eq_of_subsingleton_of_prod_eq {ι : Type*} [Subsingleton ι] {s : Finset ι} {f : ι → M} {b : M} (h : ∏ i ∈ s, f i = b) : ∀ i ∈ s, f i = b := Finset.eq_of_card_le_one_of_prod_eq (Finset.card_le_one_of_subsingleton s) h end end Fintype open Finset section variable {M : Type*} [Fintype α] [CommMonoid M] @[to_additive (attr := simp)] theorem Fintype.prod_option (f : Option α → M) : ∏ i, f i = f none * ∏ i, f (some i) := Finset.prod_insertNone f univ end open Finset section Pi variable {ι κ : Type*} {α : ι → Type*} [DecidableEq ι] [DecidableEq κ] @[simp] lemma Finset.card_pi (s : Finset ι) (t : ∀ i, Finset (α i)) : (s.pi t).card = ∏ i ∈ s, card (t i) := Multiset.card_pi _ _ namespace Fintype variable [Fintype ι] @[simp] lemma card_piFinset (s : ∀ i, Finset (α i)) : (piFinset s).card = ∏ i, (s i).card := by simp [piFinset, card_map] /-- This lemma is specifically designed to be used backwards, whence the specialisation to `Fin n` as the indexing type doesn't matter in practice. The more general forward direction lemma here is `Fintype.card_piFinset`. -/ lemma card_piFinset_const {α : Type*} (s : Finset α) (n : ℕ) : (piFinset fun _ : Fin n ↦ s).card = s.card ^ n := by simp @[simp] lemma card_pi [∀ i, Fintype (α i)] : card (∀ i, α i) = ∏ i, card (α i) := card_piFinset _ /-- This lemma is specifically designed to be used backwards, whence the specialisation to `Fin n` as the indexing type doesn't matter in practice. The more general forward direction lemma here is `Fintype.card_pi`. -/ lemma card_pi_const (α : Type*) [Fintype α] (n : ℕ) : card (Fin n → α) = card α ^ n := card_piFinset_const _ _ @[simp] nonrec lemma card_sigma {ι} {α : ι → Type*} [Fintype ι] [∀ i, Fintype (α i)] : card (Sigma α) = ∑ i, card (α i) := card_sigma _ _ /-- The number of dependent maps `f : Π j, s j` for which the `i` component is `a` is the product over all `j ≠ i` of `(s j).card`. Note that this is just a composition of easier lemmas, but there's some glue missing to make that smooth enough not to need this lemma. -/ lemma card_filter_piFinset_eq_of_mem [∀ i, DecidableEq (α i)] (s : ∀ i, Finset (α i)) (i : ι) {a : α i} (ha : a ∈ s i) : ((piFinset s).filter fun f ↦ f i = a).card = ∏ j ∈ univ.erase i, (s j).card := by calc _ = ∏ j, (Function.update s i {a} j).card := by rw [← piFinset_update_singleton_eq_filter_piFinset_eq _ _ ha, Fintype.card_piFinset] _ = ∏ j, Function.update (fun j ↦ (s j).card) i 1 j := Fintype.prod_congr _ _ fun j ↦ by obtain rfl | hji := eq_or_ne j i <;> simp [*] _ = _ := by simp [prod_update_of_mem, erase_eq] lemma card_filter_piFinset_const_eq_of_mem (s : Finset κ) (i : ι) {x : κ} (hx : x ∈ s) : ((piFinset fun _ ↦ s).filter fun f ↦ f i = x).card = s.card ^ (card ι - 1) := (card_filter_piFinset_eq_of_mem _ _ hx).trans $ by rw [prod_const s.card, card_erase_of_mem (mem_univ _), card_univ] lemma card_filter_piFinset_eq [∀ i, DecidableEq (α i)] (s : ∀ i, Finset (α i)) (i : ι) (a : α i) : ((piFinset s).filter fun f ↦ f i = a).card = if a ∈ s i then ∏ b ∈ univ.erase i, (s b).card else 0 := by split_ifs with h · rw [card_filter_piFinset_eq_of_mem _ _ h] · rw [filter_piFinset_of_not_mem _ _ _ h, Finset.card_empty] lemma card_filter_piFinset_const (s : Finset κ) (i : ι) (j : κ) : ((piFinset fun _ ↦ s).filter fun f ↦ f i = j).card = if j ∈ s then s.card ^ (card ι - 1) else 0 := (card_filter_piFinset_eq _ _ _).trans $ by rw [prod_const s.card, card_erase_of_mem (mem_univ _), card_univ] end Fintype end Pi -- TODO: this is a basic thereom about `Fintype.card`, -- and ideally could be moved to `Mathlib.Data.Fintype.Card`. theorem Fintype.card_fun [DecidableEq α] [Fintype α] [Fintype β] : Fintype.card (α → β) = Fintype.card β ^ Fintype.card α := by simp @[simp] theorem card_vector [Fintype α] (n : ℕ) : Fintype.card (Vector α n) = Fintype.card α ^ n := by rw [Fintype.ofEquiv_card]; simp /-- It is equivalent to compute the product of a function over `Fin n` or `Finset.range n`. -/ @[to_additive "It is equivalent to sum a function over `fin n` or `finset.range n`."] theorem Fin.prod_univ_eq_prod_range [CommMonoid α] (f : ℕ → α) (n : ℕ) : ∏ i : Fin n, f i = ∏ i ∈ range n, f i := calc ∏ i : Fin n, f i = ∏ i : { x // x ∈ range n }, f i := Fintype.prod_equiv (Fin.equivSubtype.trans (Equiv.subtypeEquivRight (by simp))) _ _ (by simp) _ = ∏ i ∈ range n, f i := by rw [← attach_eq_univ, prod_attach] @[to_additive] theorem Finset.prod_fin_eq_prod_range [CommMonoid β] {n : ℕ} (c : Fin n → β) : ∏ i, c i = ∏ i ∈ Finset.range n, if h : i < n then c ⟨i, h⟩ else 1 := by rw [← Fin.prod_univ_eq_prod_range, Finset.prod_congr rfl] rintro ⟨i, hi⟩ _ simp only [hi, dif_pos] @[to_additive] theorem Finset.prod_toFinset_eq_subtype {M : Type*} [CommMonoid M] [Fintype α] (p : α → Prop) [DecidablePred p] (f : α → M) : ∏ a ∈ { x | p x }.toFinset, f a = ∏ a : Subtype p, f a := by rw [← Finset.prod_subtype] simp_rw [Set.mem_toFinset]; intro; rfl nonrec theorem Fintype.prod_dite [Fintype α] {p : α → Prop} [DecidablePred p] [CommMonoid β] (f : ∀ a, p a → β) (g : ∀ a, ¬p a → β) : (∏ a, dite (p a) (f a) (g a)) = (∏ a : { a // p a }, f a a.2) * ∏ a : { a // ¬p a }, g a a.2 := by simp only [prod_dite, attach_eq_univ] congr 1 · exact (Equiv.subtypeEquivRight <| by simp).prod_comp fun x : { x // p x } => f x x.2 · exact (Equiv.subtypeEquivRight <| by simp).prod_comp fun x : { x // ¬p x } => g x x.2 section open Finset variable {α₁ : Type*} {α₂ : Type*} {M : Type*} [Fintype α₁] [Fintype α₂] [CommMonoid M] @[to_additive] theorem Fintype.prod_sum_elim (f : α₁ → M) (g : α₂ → M) : ∏ x, Sum.elim f g x = (∏ a₁, f a₁) * ∏ a₂, g a₂ := prod_disj_sum _ _ _ @[to_additive (attr := simp)] theorem Fintype.prod_sum_type (f : α₁ ⊕ α₂ → M) : ∏ x, f x = (∏ a₁, f (Sum.inl a₁)) * ∏ a₂, f (Sum.inr a₂) := prod_disj_sum _ _ _ @[to_additive (attr := simp) Fintype.sum_prod_type] theorem Fintype.prod_prod_type [CommMonoid γ] {f : α₁ × α₂ → γ} : ∏ x, f x = ∏ x, ∏ y, f (x, y) := Finset.prod_product /-- An uncurried version of `Finset.prod_prod_type`. -/ @[to_additive Fintype.sum_prod_type' "An uncurried version of `Finset.sum_prod_type`"] theorem Fintype.prod_prod_type' [CommMonoid γ] {f : α₁ → α₂ → γ} : ∏ x : α₁ × α₂, f x.1 x.2 = ∏ x, ∏ y, f x y := Finset.prod_product' @[to_additive Fintype.sum_prod_type_right] theorem Fintype.prod_prod_type_right [CommMonoid γ] {f : α₁ × α₂ → γ} : ∏ x, f x = ∏ y, ∏ x, f (x, y) := Finset.prod_product_right /-- An uncurried version of `Finset.prod_prod_type_right`. -/ @[to_additive Fintype.sum_prod_type_right' "An uncurried version of `Finset.sum_prod_type_right`"] theorem Fintype.prod_prod_type_right' [CommMonoid γ] {f : α₁ → α₂ → γ} : ∏ x : α₁ × α₂, f x.1 x.2 = ∏ y, ∏ x, f x y := Finset.prod_product_right' end
Data\Fintype\Card.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.Fintype.Basic import Mathlib.Data.Finset.Card import Mathlib.Data.List.NodupEquivFin import Mathlib.Data.Set.Image import Mathlib.Order.WellFounded /-! # Cardinalities of finite types ## Main declarations * `Fintype.card α`: Cardinality of a fintype. Equal to `Finset.univ.card`. * `Fintype.truncEquivFin`: A fintype `α` is computably equivalent to `Fin (card α)`. The `Trunc`-free, noncomputable version is `Fintype.equivFin`. * `Fintype.truncEquivOfCardEq` `Fintype.equivOfCardEq`: Two fintypes of same cardinality are equivalent. See above. * `Fin.equiv_iff_eq`: `Fin m ≃ Fin n` iff `m = n`. * `Infinite.natEmbedding`: An embedding of `ℕ` into an infinite type. We also provide the following versions of the pigeonholes principle. * `Fintype.exists_ne_map_eq_of_card_lt` and `isEmpty_of_card_lt`: Finitely many pigeons and pigeonholes. Weak formulation. * `Finite.exists_ne_map_eq_of_infinite`: Infinitely many pigeons in finitely many pigeonholes. Weak formulation. * `Finite.exists_infinite_fiber`: Infinitely many pigeons in finitely many pigeonholes. Strong formulation. Some more pigeonhole-like statements can be found in `Data.Fintype.CardEmbedding`. Types which have an injection from/a surjection to an `Infinite` type are themselves `Infinite`. See `Infinite.of_injective` and `Infinite.of_surjective`. ## Instances We provide `Infinite` instances for * specific types: `ℕ`, `ℤ`, `String` * type constructors: `Multiset α`, `List α` -/ assert_not_exists MonoidWithZero assert_not_exists MulAction open Function open Nat universe u v variable {α β γ : Type*} open Finset Function namespace Fintype /-- `card α` is the number of elements in `α`, defined when `α` is a fintype. -/ def card (α) [Fintype α] : ℕ := (@univ α _).card /-- There is (computably) an equivalence between `α` and `Fin (card α)`. Since it is not unique and depends on which permutation of the universe list is used, the equivalence is wrapped in `Trunc` to preserve computability. See `Fintype.equivFin` for the noncomputable version, and `Fintype.truncEquivFinOfCardEq` and `Fintype.equivFinOfCardEq` for an equiv `α ≃ Fin n` given `Fintype.card α = n`. See `Fintype.truncFinBijection` for a version without `[DecidableEq α]`. -/ def truncEquivFin (α) [DecidableEq α] [Fintype α] : Trunc (α ≃ Fin (card α)) := by unfold card Finset.card exact Quot.recOnSubsingleton' (motive := fun s : Multiset α => (∀ x : α, x ∈ s) → s.Nodup → Trunc (α ≃ Fin (Multiset.card s))) univ.val (fun l (h : ∀ x : α, x ∈ l) (nd : l.Nodup) => Trunc.mk (nd.getEquivOfForallMemList _ h).symm) mem_univ_val univ.2 /-- There is (noncomputably) an equivalence between `α` and `Fin (card α)`. See `Fintype.truncEquivFin` for the computable version, and `Fintype.truncEquivFinOfCardEq` and `Fintype.equivFinOfCardEq` for an equiv `α ≃ Fin n` given `Fintype.card α = n`. -/ noncomputable def equivFin (α) [Fintype α] : α ≃ Fin (card α) := letI := Classical.decEq α (truncEquivFin α).out /-- There is (computably) a bijection between `Fin (card α)` and `α`. Since it is not unique and depends on which permutation of the universe list is used, the bijection is wrapped in `Trunc` to preserve computability. See `Fintype.truncEquivFin` for a version that gives an equivalence given `[DecidableEq α]`. -/ def truncFinBijection (α) [Fintype α] : Trunc { f : Fin (card α) → α // Bijective f } := by unfold card Finset.card refine Quot.recOnSubsingleton' (motive := fun s : Multiset α => (∀ x : α, x ∈ s) → s.Nodup → Trunc {f : Fin (Multiset.card s) → α // Bijective f}) univ.val (fun l (h : ∀ x : α, x ∈ l) (nd : l.Nodup) => Trunc.mk (nd.getBijectionOfForallMemList _ h)) mem_univ_val univ.2 theorem subtype_card {p : α → Prop} (s : Finset α) (H : ∀ x : α, x ∈ s ↔ p x) : @card { x // p x } (Fintype.subtype s H) = s.card := Multiset.card_pmap _ _ _ theorem card_of_subtype {p : α → Prop} (s : Finset α) (H : ∀ x : α, x ∈ s ↔ p x) [Fintype { x // p x }] : card { x // p x } = s.card := by rw [← subtype_card s H] congr! @[simp] theorem card_ofFinset {p : Set α} (s : Finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) : @Fintype.card p (ofFinset s H) = s.card := Fintype.subtype_card s H theorem card_of_finset' {p : Set α} (s : Finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) [Fintype p] : Fintype.card p = s.card := by rw [← card_ofFinset s H]; congr! end Fintype namespace Fintype theorem ofEquiv_card [Fintype α] (f : α ≃ β) : @card β (ofEquiv α f) = card α := Multiset.card_map _ _ theorem card_congr {α β} [Fintype α] [Fintype β] (f : α ≃ β) : card α = card β := by rw [← ofEquiv_card f]; congr! @[congr] theorem card_congr' {α β} [Fintype α] [Fintype β] (h : α = β) : card α = card β := card_congr (by rw [h]) section variable [Fintype α] [Fintype β] /-- If the cardinality of `α` is `n`, there is computably a bijection between `α` and `Fin n`. See `Fintype.equivFinOfCardEq` for the noncomputable definition, and `Fintype.truncEquivFin` and `Fintype.equivFin` for the bijection `α ≃ Fin (card α)`. -/ def truncEquivFinOfCardEq [DecidableEq α] {n : ℕ} (h : Fintype.card α = n) : Trunc (α ≃ Fin n) := (truncEquivFin α).map fun e => e.trans (finCongr h) /-- If the cardinality of `α` is `n`, there is noncomputably a bijection between `α` and `Fin n`. See `Fintype.truncEquivFinOfCardEq` for the computable definition, and `Fintype.truncEquivFin` and `Fintype.equivFin` for the bijection `α ≃ Fin (card α)`. -/ noncomputable def equivFinOfCardEq {n : ℕ} (h : Fintype.card α = n) : α ≃ Fin n := letI := Classical.decEq α (truncEquivFinOfCardEq h).out /-- Two `Fintype`s with the same cardinality are (computably) in bijection. See `Fintype.equivOfCardEq` for the noncomputable version, and `Fintype.truncEquivFinOfCardEq` and `Fintype.equivFinOfCardEq` for the specialization to `Fin`. -/ def truncEquivOfCardEq [DecidableEq α] [DecidableEq β] (h : card α = card β) : Trunc (α ≃ β) := (truncEquivFinOfCardEq h).bind fun e => (truncEquivFin β).map fun e' => e.trans e'.symm /-- Two `Fintype`s with the same cardinality are (noncomputably) in bijection. See `Fintype.truncEquivOfCardEq` for the computable version, and `Fintype.truncEquivFinOfCardEq` and `Fintype.equivFinOfCardEq` for the specialization to `Fin`. -/ noncomputable def equivOfCardEq (h : card α = card β) : α ≃ β := by letI := Classical.decEq α letI := Classical.decEq β exact (truncEquivOfCardEq h).out end theorem card_eq {α β} [_F : Fintype α] [_G : Fintype β] : card α = card β ↔ Nonempty (α ≃ β) := ⟨fun h => haveI := Classical.propDecidable (truncEquivOfCardEq h).nonempty, fun ⟨f⟩ => card_congr f⟩ /-- Note: this lemma is specifically about `Fintype.ofSubsingleton`. For a statement about arbitrary `Fintype` instances, use either `Fintype.card_le_one_iff_subsingleton` or `Fintype.card_unique`. -/ @[simp] theorem card_ofSubsingleton (a : α) [Subsingleton α] : @Fintype.card _ (ofSubsingleton a) = 1 := rfl @[simp] theorem card_unique [Unique α] [h : Fintype α] : Fintype.card α = 1 := Subsingleton.elim (ofSubsingleton default) h ▸ card_ofSubsingleton _ /-- Note: this lemma is specifically about `Fintype.ofIsEmpty`. For a statement about arbitrary `Fintype` instances, use `Fintype.card_eq_zero`. -/ @[simp] theorem card_ofIsEmpty [IsEmpty α] : @Fintype.card α Fintype.ofIsEmpty = 0 := rfl end Fintype namespace Set variable {s t : Set α} -- We use an arbitrary `[Fintype s]` instance here, -- not necessarily coming from a `[Fintype α]`. @[simp] theorem toFinset_card {α : Type*} (s : Set α) [Fintype s] : s.toFinset.card = Fintype.card s := Multiset.card_map Subtype.val Finset.univ.val end Set @[simp] theorem Finset.card_univ [Fintype α] : (Finset.univ : Finset α).card = Fintype.card α := rfl theorem Finset.eq_univ_of_card [Fintype α] (s : Finset α) (hs : s.card = Fintype.card α) : s = univ := eq_of_subset_of_card_le (subset_univ _) <| by rw [hs, Finset.card_univ] theorem Finset.card_eq_iff_eq_univ [Fintype α] (s : Finset α) : s.card = Fintype.card α ↔ s = Finset.univ := ⟨s.eq_univ_of_card, by rintro rfl exact Finset.card_univ⟩ theorem Finset.card_le_univ [Fintype α] (s : Finset α) : s.card ≤ Fintype.card α := card_le_card (subset_univ s) theorem Finset.card_lt_univ_of_not_mem [Fintype α] {s : Finset α} {x : α} (hx : x ∉ s) : s.card < Fintype.card α := card_lt_card ⟨subset_univ s, not_forall.2 ⟨x, fun hx' => hx (hx' <| mem_univ x)⟩⟩ theorem Finset.card_lt_iff_ne_univ [Fintype α] (s : Finset α) : s.card < Fintype.card α ↔ s ≠ Finset.univ := s.card_le_univ.lt_iff_ne.trans (not_congr s.card_eq_iff_eq_univ) theorem Finset.card_compl_lt_iff_nonempty [Fintype α] [DecidableEq α] (s : Finset α) : sᶜ.card < Fintype.card α ↔ s.Nonempty := sᶜ.card_lt_iff_ne_univ.trans s.compl_ne_univ_iff_nonempty theorem Finset.card_univ_diff [DecidableEq α] [Fintype α] (s : Finset α) : (Finset.univ \ s).card = Fintype.card α - s.card := Finset.card_sdiff (subset_univ s) theorem Finset.card_compl [DecidableEq α] [Fintype α] (s : Finset α) : sᶜ.card = Fintype.card α - s.card := Finset.card_univ_diff s @[simp] theorem Finset.card_add_card_compl [DecidableEq α] [Fintype α] (s : Finset α) : s.card + sᶜ.card = Fintype.card α := by rw [Finset.card_compl, ← Nat.add_sub_assoc (card_le_univ s), Nat.add_sub_cancel_left] @[simp] theorem Finset.card_compl_add_card [DecidableEq α] [Fintype α] (s : Finset α) : sᶜ.card + s.card = Fintype.card α := by rw [add_comm, card_add_card_compl] theorem Fintype.card_compl_set [Fintype α] (s : Set α) [Fintype s] [Fintype (↥sᶜ : Sort _)] : Fintype.card (↥sᶜ : Sort _) = Fintype.card α - Fintype.card s := by classical rw [← Set.toFinset_card, ← Set.toFinset_card, ← Finset.card_compl, Set.toFinset_compl] @[simp] theorem Fintype.card_fin (n : ℕ) : Fintype.card (Fin n) = n := List.length_finRange n theorem Fintype.card_fin_lt_of_le {m n : ℕ} (h : m ≤ n) : Fintype.card {i : Fin n // i < m} = m := by conv_rhs => rw [← Fintype.card_fin m] apply Fintype.card_congr exact { toFun := fun ⟨⟨i, _⟩, hi⟩ ↦ ⟨i, hi⟩ invFun := fun ⟨i, hi⟩ ↦ ⟨⟨i, lt_of_lt_of_le hi h⟩, hi⟩ left_inv := fun i ↦ rfl right_inv := fun i ↦ rfl } theorem Finset.card_fin (n : ℕ) : Finset.card (Finset.univ : Finset (Fin n)) = n := by simp /-- `Fin` as a map from `ℕ` to `Type` is injective. Note that since this is a statement about equality of types, using it should be avoided if possible. -/ theorem fin_injective : Function.Injective Fin := fun m n h => (Fintype.card_fin m).symm.trans <| (Fintype.card_congr <| Equiv.cast h).trans (Fintype.card_fin n) /-- A reversed version of `Fin.cast_eq_cast` that is easier to rewrite with. -/ theorem Fin.cast_eq_cast' {n m : ℕ} (h : Fin n = Fin m) : _root_.cast h = Fin.cast (fin_injective h) := by cases fin_injective h rfl theorem card_finset_fin_le {n : ℕ} (s : Finset (Fin n)) : s.card ≤ n := by simpa only [Fintype.card_fin] using s.card_le_univ --@[simp] Porting note (#10618): simp can prove it theorem Fintype.card_subtype_eq (y : α) [Fintype { x // x = y }] : Fintype.card { x // x = y } = 1 := Fintype.card_unique --@[simp] Porting note (#10618): simp can prove it theorem Fintype.card_subtype_eq' (y : α) [Fintype { x // y = x }] : Fintype.card { x // y = x } = 1 := Fintype.card_unique theorem Fintype.card_empty : Fintype.card Empty = 0 := rfl theorem Fintype.card_pempty : Fintype.card PEmpty = 0 := rfl theorem Fintype.card_unit : Fintype.card Unit = 1 := rfl @[simp] theorem Fintype.card_punit : Fintype.card PUnit = 1 := rfl @[simp] theorem Fintype.card_bool : Fintype.card Bool = 2 := rfl @[simp] theorem Fintype.card_ulift (α : Type*) [Fintype α] : Fintype.card (ULift α) = Fintype.card α := Fintype.ofEquiv_card _ @[simp] theorem Fintype.card_plift (α : Type*) [Fintype α] : Fintype.card (PLift α) = Fintype.card α := Fintype.ofEquiv_card _ @[simp] theorem Fintype.card_orderDual (α : Type*) [Fintype α] : Fintype.card αᵒᵈ = Fintype.card α := rfl @[simp] theorem Fintype.card_lex (α : Type*) [Fintype α] : Fintype.card (Lex α) = Fintype.card α := rfl @[simp] lemma Fintype.card_multiplicative (α : Type*) [Fintype α] : card (Multiplicative α) = card α := Finset.card_map _ @[simp] lemma Fintype.card_additive (α : Type*) [Fintype α] : card (Additive α) = card α := Finset.card_map _ /-- Given that `α ⊕ β` is a fintype, `α` is also a fintype. This is non-computable as it uses that `Sum.inl` is an injection, but there's no clear inverse if `α` is empty. -/ noncomputable def Fintype.sumLeft {α β} [Fintype (α ⊕ β)] : Fintype α := Fintype.ofInjective (Sum.inl : α → α ⊕ β) Sum.inl_injective /-- Given that `α ⊕ β` is a fintype, `β` is also a fintype. This is non-computable as it uses that `Sum.inr` is an injection, but there's no clear inverse if `β` is empty. -/ noncomputable def Fintype.sumRight {α β} [Fintype (α ⊕ β)] : Fintype β := Fintype.ofInjective (Sum.inr : β → α ⊕ β) Sum.inr_injective /-! ### Relation to `Finite` In this section we prove that `α : Type*` is `Finite` if and only if `Fintype α` is nonempty. -/ -- @[nolint fintype_finite] -- Porting note: do we need this protected theorem Fintype.finite {α : Type*} (_inst : Fintype α) : Finite α := ⟨Fintype.equivFin α⟩ /-- For efficiency reasons, we want `Finite` instances to have higher priority than ones coming from `Fintype` instances. -/ -- @[nolint fintype_finite] -- Porting note: do we need this instance (priority := 900) Finite.of_fintype (α : Type*) [Fintype α] : Finite α := Fintype.finite ‹_› theorem finite_iff_nonempty_fintype (α : Type*) : Finite α ↔ Nonempty (Fintype α) := ⟨fun h => let ⟨_k, ⟨e⟩⟩ := @Finite.exists_equiv_fin α h ⟨Fintype.ofEquiv _ e.symm⟩, fun ⟨_⟩ => inferInstance⟩ /-- See also `nonempty_encodable`, `nonempty_denumerable`. -/ theorem nonempty_fintype (α : Type*) [Finite α] : Nonempty (Fintype α) := (finite_iff_nonempty_fintype α).mp ‹_› /-- Noncomputably get a `Fintype` instance from a `Finite` instance. This is not an instance because we want `Fintype` instances to be useful for computations. -/ noncomputable def Fintype.ofFinite (α : Type*) [Finite α] : Fintype α := (nonempty_fintype α).some theorem Finite.of_injective {α β : Sort*} [Finite β] (f : α → β) (H : Injective f) : Finite α := by rcases Finite.exists_equiv_fin β with ⟨n, ⟨e⟩⟩ classical exact .of_equiv (Set.range (e ∘ f)) (Equiv.ofInjective _ (e.injective.comp H)).symm /-- This instance also provides `[Finite s]` for `s : Set α`. -/ instance Subtype.finite {α : Sort*} [Finite α] {p : α → Prop} : Finite { x // p x } := Finite.of_injective (↑) Subtype.coe_injective theorem Finite.of_surjective {α β : Sort*} [Finite α] (f : α → β) (H : Surjective f) : Finite β := Finite.of_injective _ <| injective_surjInv H theorem Finite.exists_univ_list (α) [Finite α] : ∃ l : List α, l.Nodup ∧ ∀ x : α, x ∈ l := by cases nonempty_fintype α obtain ⟨l, e⟩ := Quotient.exists_rep (@univ α _).1 have := And.intro (@univ α _).2 (@mem_univ_val α _) exact ⟨_, by rwa [← e] at this⟩ theorem List.Nodup.length_le_card {α : Type*} [Fintype α] {l : List α} (h : l.Nodup) : l.length ≤ Fintype.card α := by classical exact List.toFinset_card_of_nodup h ▸ l.toFinset.card_le_univ namespace Fintype variable [Fintype α] [Fintype β] theorem card_le_of_injective (f : α → β) (hf : Function.Injective f) : card α ≤ card β := Finset.card_le_card_of_injOn f (fun _ _ => Finset.mem_univ _) fun _ _ _ _ h => hf h theorem card_le_of_embedding (f : α ↪ β) : card α ≤ card β := card_le_of_injective f f.2 theorem card_lt_of_injective_of_not_mem (f : α → β) (h : Function.Injective f) {b : β} (w : b ∉ Set.range f) : card α < card β := calc card α = (univ.map ⟨f, h⟩).card := (card_map _).symm _ < card β := Finset.card_lt_univ_of_not_mem (x := b) <| by rwa [← mem_coe, coe_map, coe_univ, Set.image_univ] theorem card_lt_of_injective_not_surjective (f : α → β) (h : Function.Injective f) (h' : ¬Function.Surjective f) : card α < card β := let ⟨_y, hy⟩ := not_forall.1 h' card_lt_of_injective_of_not_mem f h hy theorem card_le_of_surjective (f : α → β) (h : Function.Surjective f) : card β ≤ card α := card_le_of_injective _ (Function.injective_surjInv h) theorem card_range_le {α β : Type*} (f : α → β) [Fintype α] [Fintype (Set.range f)] : Fintype.card (Set.range f) ≤ Fintype.card α := Fintype.card_le_of_surjective (fun a => ⟨f a, by simp⟩) fun ⟨_, a, ha⟩ => ⟨a, by simpa using ha⟩ theorem card_range {α β F : Type*} [FunLike F α β] [EmbeddingLike F α β] (f : F) [Fintype α] [Fintype (Set.range f)] : Fintype.card (Set.range f) = Fintype.card α := Eq.symm <| Fintype.card_congr <| Equiv.ofInjective _ <| EmbeddingLike.injective f /-- The pigeonhole principle for finitely many pigeons and pigeonholes. This is the `Fintype` version of `Finset.exists_ne_map_eq_of_card_lt_of_maps_to`. -/ theorem exists_ne_map_eq_of_card_lt (f : α → β) (h : Fintype.card β < Fintype.card α) : ∃ x y, x ≠ y ∧ f x = f y := let ⟨x, _, y, _, h⟩ := Finset.exists_ne_map_eq_of_card_lt_of_maps_to h fun x _ => mem_univ (f x) ⟨x, y, h⟩ theorem card_eq_one_iff : card α = 1 ↔ ∃ x : α, ∀ y, y = x := by rw [← card_unit, card_eq] exact ⟨fun ⟨a⟩ => ⟨a.symm (), fun y => a.injective (Subsingleton.elim _ _)⟩, fun ⟨x, hx⟩ => ⟨⟨fun _ => (), fun _ => x, fun _ => (hx _).trans (hx _).symm, fun _ => Subsingleton.elim _ _⟩⟩⟩ theorem card_eq_zero_iff : card α = 0 ↔ IsEmpty α := by rw [card, Finset.card_eq_zero, univ_eq_empty_iff] @[simp] theorem card_eq_zero [IsEmpty α] : card α = 0 := card_eq_zero_iff.2 ‹_› alias card_of_isEmpty := card_eq_zero theorem card_eq_one_iff_nonempty_unique : card α = 1 ↔ Nonempty (Unique α) := ⟨fun h => let ⟨d, h⟩ := Fintype.card_eq_one_iff.mp h ⟨{ default := d uniq := h }⟩, fun ⟨_h⟩ => Fintype.card_unique⟩ /-- A `Fintype` with cardinality zero is equivalent to `Empty`. -/ def cardEqZeroEquivEquivEmpty : card α = 0 ≃ (α ≃ Empty) := (Equiv.ofIff card_eq_zero_iff).trans (Equiv.equivEmptyEquiv α).symm theorem card_pos_iff : 0 < card α ↔ Nonempty α := Nat.pos_iff_ne_zero.trans <| not_iff_comm.mp <| not_nonempty_iff.trans card_eq_zero_iff.symm theorem card_pos [h : Nonempty α] : 0 < card α := card_pos_iff.mpr h @[simp] theorem card_ne_zero [Nonempty α] : card α ≠ 0 := _root_.ne_of_gt card_pos instance [Nonempty α] : NeZero (card α) := ⟨card_ne_zero⟩ theorem card_le_one_iff : card α ≤ 1 ↔ ∀ a b : α, a = b := let n := card α have hn : n = card α := rfl match n, hn with | 0, ha => ⟨fun _h => fun a => (card_eq_zero_iff.1 ha.symm).elim a, fun _ => ha ▸ Nat.le_succ _⟩ | 1, ha => ⟨fun _h => fun a b => by let ⟨x, hx⟩ := card_eq_one_iff.1 ha.symm rw [hx a, hx b], fun _ => ha ▸ le_rfl⟩ | n + 2, ha => ⟨fun h => False.elim <| by rw [← ha] at h; cases h with | step h => cases h; , fun h => card_unit ▸ card_le_of_injective (fun _ => ()) fun _ _ _ => h _ _⟩ theorem card_le_one_iff_subsingleton : card α ≤ 1 ↔ Subsingleton α := card_le_one_iff.trans subsingleton_iff.symm theorem one_lt_card_iff_nontrivial : 1 < card α ↔ Nontrivial α := by rw [← not_iff_not, not_lt, not_nontrivial_iff_subsingleton, card_le_one_iff_subsingleton] theorem exists_ne_of_one_lt_card (h : 1 < card α) (a : α) : ∃ b : α, b ≠ a := haveI : Nontrivial α := one_lt_card_iff_nontrivial.1 h exists_ne a theorem exists_pair_of_one_lt_card (h : 1 < card α) : ∃ a b : α, a ≠ b := haveI : Nontrivial α := one_lt_card_iff_nontrivial.1 h exists_pair_ne α theorem card_eq_one_of_forall_eq {i : α} (h : ∀ j, j = i) : card α = 1 := Fintype.card_eq_one_iff.2 ⟨i, h⟩ theorem exists_unique_iff_card_one {α} [Fintype α] (p : α → Prop) [DecidablePred p] : (∃! a : α, p a) ↔ (Finset.univ.filter p).card = 1 := by rw [Finset.card_eq_one] refine exists_congr fun x => ?_ simp only [forall_true_left, Subset.antisymm_iff, subset_singleton_iff', singleton_subset_iff, true_and, and_comm, mem_univ, mem_filter] theorem one_lt_card [h : Nontrivial α] : 1 < Fintype.card α := Fintype.one_lt_card_iff_nontrivial.mpr h theorem one_lt_card_iff : 1 < card α ↔ ∃ a b : α, a ≠ b := one_lt_card_iff_nontrivial.trans nontrivial_iff nonrec theorem two_lt_card_iff : 2 < card α ↔ ∃ a b c : α, a ≠ b ∧ a ≠ c ∧ b ≠ c := by simp_rw [← Finset.card_univ, two_lt_card_iff, mem_univ, true_and_iff] theorem card_of_bijective {f : α → β} (hf : Bijective f) : card α = card β := card_congr (Equiv.ofBijective f hf) end Fintype namespace Finite variable [Finite α] theorem surjective_of_injective {f : α → α} (hinj : Injective f) : Surjective f := by intro x have := Classical.propDecidable cases nonempty_fintype α have h₁ : image f univ = univ := eq_of_subset_of_card_le (subset_univ _) ((card_image_of_injective univ hinj).symm ▸ le_rfl) have h₂ : x ∈ image f univ := h₁.symm ▸ mem_univ x obtain ⟨y, h⟩ := mem_image.1 h₂ exact ⟨y, h.2⟩ theorem injective_iff_surjective {f : α → α} : Injective f ↔ Surjective f := ⟨surjective_of_injective, fun hsurj => HasLeftInverse.injective ⟨surjInv hsurj, leftInverse_of_surjective_of_rightInverse (surjective_of_injective (injective_surjInv _)) (rightInverse_surjInv _)⟩⟩ theorem injective_iff_bijective {f : α → α} : Injective f ↔ Bijective f := by simp [Bijective, injective_iff_surjective] theorem surjective_iff_bijective {f : α → α} : Surjective f ↔ Bijective f := by simp [Bijective, injective_iff_surjective] theorem injective_iff_surjective_of_equiv {f : α → β} (e : α ≃ β) : Injective f ↔ Surjective f := have : Injective (e.symm ∘ f) ↔ Surjective (e.symm ∘ f) := injective_iff_surjective ⟨fun hinj => by simpa [Function.comp] using e.surjective.comp (this.1 (e.symm.injective.comp hinj)), fun hsurj => by simpa [Function.comp] using e.injective.comp (this.2 (e.symm.surjective.comp hsurj))⟩ alias ⟨_root_.Function.Injective.bijective_of_finite, _⟩ := injective_iff_bijective alias ⟨_root_.Function.Surjective.bijective_of_finite, _⟩ := surjective_iff_bijective alias ⟨_root_.Function.Injective.surjective_of_fintype, _root_.Function.Surjective.injective_of_fintype⟩ := injective_iff_surjective_of_equiv end Finite namespace Fintype variable [Fintype α] [Fintype β] theorem bijective_iff_injective_and_card (f : α → β) : Bijective f ↔ Injective f ∧ card α = card β := ⟨fun h => ⟨h.1, card_of_bijective h⟩, fun h => ⟨h.1, h.1.surjective_of_fintype <| equivOfCardEq h.2⟩⟩ theorem bijective_iff_surjective_and_card (f : α → β) : Bijective f ↔ Surjective f ∧ card α = card β := ⟨fun h => ⟨h.2, card_of_bijective h⟩, fun h => ⟨h.1.injective_of_fintype <| equivOfCardEq h.2, h.1⟩⟩ theorem _root_.Function.LeftInverse.rightInverse_of_card_le {f : α → β} {g : β → α} (hfg : LeftInverse f g) (hcard : card α ≤ card β) : RightInverse f g := have hsurj : Surjective f := surjective_iff_hasRightInverse.2 ⟨g, hfg⟩ rightInverse_of_injective_of_leftInverse ((bijective_iff_surjective_and_card _).2 ⟨hsurj, le_antisymm hcard (card_le_of_surjective f hsurj)⟩).1 hfg theorem _root_.Function.RightInverse.leftInverse_of_card_le {f : α → β} {g : β → α} (hfg : RightInverse f g) (hcard : card β ≤ card α) : LeftInverse f g := Function.LeftInverse.rightInverse_of_card_le hfg hcard end Fintype namespace Equiv variable [Fintype α] [Fintype β] open Fintype /-- Construct an equivalence from functions that are inverse to each other. -/ @[simps] def ofLeftInverseOfCardLE (hβα : card β ≤ card α) (f : α → β) (g : β → α) (h : LeftInverse g f) : α ≃ β where toFun := f invFun := g left_inv := h right_inv := h.rightInverse_of_card_le hβα /-- Construct an equivalence from functions that are inverse to each other. -/ @[simps] def ofRightInverseOfCardLE (hαβ : card α ≤ card β) (f : α → β) (g : β → α) (h : RightInverse g f) : α ≃ β where toFun := f invFun := g left_inv := h.leftInverse_of_card_le hαβ right_inv := h end Equiv @[simp] theorem Fintype.card_coe (s : Finset α) [Fintype s] : Fintype.card s = s.card := @Fintype.card_of_finset' _ _ _ (fun _ => Iff.rfl) (id _) /-- Noncomputable equivalence between a finset `s` coerced to a type and `Fin s.card`. -/ noncomputable def Finset.equivFin (s : Finset α) : s ≃ Fin s.card := Fintype.equivFinOfCardEq (Fintype.card_coe _) /-- Noncomputable equivalence between a finset `s` as a fintype and `Fin n`, when there is a proof that `s.card = n`. -/ noncomputable def Finset.equivFinOfCardEq {s : Finset α} {n : ℕ} (h : s.card = n) : s ≃ Fin n := Fintype.equivFinOfCardEq ((Fintype.card_coe _).trans h) theorem Finset.card_eq_of_equiv_fin {s : Finset α} {n : ℕ} (i : s ≃ Fin n) : s.card = n := Fin.equiv_iff_eq.1 ⟨s.equivFin.symm.trans i⟩ theorem Finset.card_eq_of_equiv_fintype {s : Finset α} [Fintype β] (i : s ≃ β) : s.card = Fintype.card β := card_eq_of_equiv_fin <| i.trans <| Fintype.equivFin β /-- Noncomputable equivalence between two finsets `s` and `t` as fintypes when there is a proof that `s.card = t.card`. -/ noncomputable def Finset.equivOfCardEq {s : Finset α} {t : Finset β} (h : s.card = t.card) : s ≃ t := Fintype.equivOfCardEq ((Fintype.card_coe _).trans (h.trans (Fintype.card_coe _).symm)) theorem Finset.card_eq_of_equiv {s : Finset α} {t : Finset β} (i : s ≃ t) : s.card = t.card := (card_eq_of_equiv_fintype i).trans (Fintype.card_coe _) /-- We can inflate a set `s` to any bigger size. -/ lemma Finset.exists_superset_card_eq [Fintype α] {n : ℕ} {s : Finset α} (hsn : s.card ≤ n) (hnα : n ≤ Fintype.card α) : ∃ t, s ⊆ t ∧ t.card = n := by simpa using exists_subsuperset_card_eq s.subset_univ hsn hnα @[simp] theorem Fintype.card_prop : Fintype.card Prop = 2 := rfl theorem set_fintype_card_le_univ [Fintype α] (s : Set α) [Fintype s] : Fintype.card s ≤ Fintype.card α := Fintype.card_le_of_embedding (Function.Embedding.subtype s) theorem set_fintype_card_eq_univ_iff [Fintype α] (s : Set α) [Fintype s] : Fintype.card s = Fintype.card α ↔ s = Set.univ := by rw [← Set.toFinset_card, Finset.card_eq_iff_eq_univ, ← Set.toFinset_univ, Set.toFinset_inj] namespace Function.Embedding /-- An embedding from a `Fintype` to itself can be promoted to an equivalence. -/ noncomputable def equivOfFintypeSelfEmbedding [Finite α] (e : α ↪ α) : α ≃ α := Equiv.ofBijective e e.2.bijective_of_finite @[simp] theorem equiv_of_fintype_self_embedding_to_embedding [Finite α] (e : α ↪ α) : e.equivOfFintypeSelfEmbedding.toEmbedding = e := by ext rfl /-- If `‖β‖ < ‖α‖` there are no embeddings `α ↪ β`. This is a formulation of the pigeonhole principle. Note this cannot be an instance as it needs `h`. -/ @[simp] theorem isEmpty_of_card_lt [Fintype α] [Fintype β] (h : Fintype.card β < Fintype.card α) : IsEmpty (α ↪ β) := ⟨fun f => let ⟨_x, _y, ne, feq⟩ := Fintype.exists_ne_map_eq_of_card_lt f h ne <| f.injective feq⟩ /-- A constructive embedding of a fintype `α` in another fintype `β` when `card α ≤ card β`. -/ def truncOfCardLE [Fintype α] [Fintype β] [DecidableEq α] [DecidableEq β] (h : Fintype.card α ≤ Fintype.card β) : Trunc (α ↪ β) := (Fintype.truncEquivFin α).bind fun ea => (Fintype.truncEquivFin β).map fun eb => ea.toEmbedding.trans ((Fin.castLEEmb h).trans eb.symm.toEmbedding) theorem nonempty_of_card_le [Fintype α] [Fintype β] (h : Fintype.card α ≤ Fintype.card β) : Nonempty (α ↪ β) := by classical exact (truncOfCardLE h).nonempty theorem nonempty_iff_card_le [Fintype α] [Fintype β] : Nonempty (α ↪ β) ↔ Fintype.card α ≤ Fintype.card β := ⟨fun ⟨e⟩ => Fintype.card_le_of_embedding e, nonempty_of_card_le⟩ theorem exists_of_card_le_finset [Fintype α] {s : Finset β} (h : Fintype.card α ≤ s.card) : ∃ f : α ↪ β, Set.range f ⊆ s := by rw [← Fintype.card_coe] at h rcases nonempty_of_card_le h with ⟨f⟩ exact ⟨f.trans (Embedding.subtype _), by simp [Set.range_subset_iff]⟩ end Function.Embedding @[simp] theorem Finset.univ_map_embedding {α : Type*} [Fintype α] (e : α ↪ α) : univ.map e = univ := by rw [← e.equiv_of_fintype_self_embedding_to_embedding, univ_map_equiv_to_embedding] namespace Fintype theorem card_lt_of_surjective_not_injective [Fintype α] [Fintype β] (f : α → β) (h : Function.Surjective f) (h' : ¬Function.Injective f) : card β < card α := card_lt_of_injective_not_surjective _ (Function.injective_surjInv h) fun hg => have w : Function.Bijective (Function.surjInv h) := ⟨Function.injective_surjInv h, hg⟩ h' <| h.injective_of_fintype (Equiv.ofBijective _ w).symm end Fintype theorem Fintype.card_subtype_le [Fintype α] (p : α → Prop) [DecidablePred p] : Fintype.card { x // p x } ≤ Fintype.card α := Fintype.card_le_of_embedding (Function.Embedding.subtype _) theorem Fintype.card_subtype_lt [Fintype α] {p : α → Prop} [DecidablePred p] {x : α} (hx : ¬p x) : Fintype.card { x // p x } < Fintype.card α := Fintype.card_lt_of_injective_of_not_mem (b := x) (↑) Subtype.coe_injective <| by rwa [Subtype.range_coe_subtype] theorem Fintype.card_subtype [Fintype α] (p : α → Prop) [DecidablePred p] : Fintype.card { x // p x } = ((Finset.univ : Finset α).filter p).card := by refine Fintype.card_of_subtype _ ?_ simp @[simp] theorem Fintype.card_subtype_compl [Fintype α] (p : α → Prop) [Fintype { x // p x }] [Fintype { x // ¬p x }] : Fintype.card { x // ¬p x } = Fintype.card α - Fintype.card { x // p x } := by classical rw [Fintype.card_of_subtype (Set.toFinset { x | p x }ᶜ), Set.toFinset_compl, Finset.card_compl, Fintype.card_of_subtype] <;> · intro simp only [Set.mem_toFinset, Set.mem_compl_iff, Set.mem_setOf] theorem Fintype.card_subtype_mono (p q : α → Prop) (h : p ≤ q) [Fintype { x // p x }] [Fintype { x // q x }] : Fintype.card { x // p x } ≤ Fintype.card { x // q x } := Fintype.card_le_of_embedding (Subtype.impEmbedding _ _ h) /-- If two subtypes of a fintype have equal cardinality, so do their complements. -/ theorem Fintype.card_compl_eq_card_compl [Finite α] (p q : α → Prop) [Fintype { x // p x }] [Fintype { x // ¬p x }] [Fintype { x // q x }] [Fintype { x // ¬q x }] (h : Fintype.card { x // p x } = Fintype.card { x // q x }) : Fintype.card { x // ¬p x } = Fintype.card { x // ¬q x } := by cases nonempty_fintype α simp only [Fintype.card_subtype_compl, h] theorem Fintype.card_quotient_le [Fintype α] (s : Setoid α) [DecidableRel ((· ≈ ·) : α → α → Prop)] : Fintype.card (Quotient s) ≤ Fintype.card α := Fintype.card_le_of_surjective _ (surjective_quotient_mk' _) theorem Fintype.card_quotient_lt [Fintype α] {s : Setoid α} [DecidableRel ((· ≈ ·) : α → α → Prop)] {x y : α} (h1 : x ≠ y) (h2 : x ≈ y) : Fintype.card (Quotient s) < Fintype.card α := Fintype.card_lt_of_surjective_not_injective _ (surjective_quotient_mk' _) fun w => h1 (w <| Quotient.eq.mpr h2) theorem univ_eq_singleton_of_card_one {α} [Fintype α] (x : α) (h : Fintype.card α = 1) : (univ : Finset α) = {x} := by symm apply eq_of_subset_of_card_le (subset_univ {x}) apply le_of_eq simp [h, Finset.card_univ] namespace Finite variable [Finite α] theorem wellFounded_of_trans_of_irrefl (r : α → α → Prop) [IsTrans α r] [IsIrrefl α r] : WellFounded r := by classical cases nonempty_fintype α have : ∀ x y, r x y → (univ.filter fun z => r z x).card < (univ.filter fun z => r z y).card := fun x y hxy => Finset.card_lt_card <| by simp only [Finset.lt_iff_ssubset.symm, lt_iff_le_not_le, Finset.le_iff_subset, Finset.subset_iff, mem_filter, true_and_iff, mem_univ, hxy] exact ⟨fun z hzx => _root_.trans hzx hxy, not_forall_of_exists_not ⟨x, Classical.not_imp.2 ⟨hxy, irrefl x⟩⟩⟩ exact Subrelation.wf (this _ _) (measure _).wf -- See note [lower instance priority] instance (priority := 100) to_wellFoundedLT [Preorder α] : WellFoundedLT α := ⟨wellFounded_of_trans_of_irrefl _⟩ -- See note [lower instance priority] instance (priority := 100) to_wellFoundedGT [Preorder α] : WellFoundedGT α := ⟨wellFounded_of_trans_of_irrefl _⟩ instance (priority := 10) LinearOrder.isWellOrder_lt [LinearOrder α] : IsWellOrder α (· < ·) := {} instance (priority := 10) LinearOrder.isWellOrder_gt [LinearOrder α] : IsWellOrder α (· > ·) := {} end Finite -- @[nolint fintype_finite] -- Porting note: do we need this? protected theorem Fintype.false [Infinite α] (_h : Fintype α) : False := not_finite α @[simp] theorem isEmpty_fintype {α : Type*} : IsEmpty (Fintype α) ↔ Infinite α := ⟨fun ⟨h⟩ => ⟨fun h' => (@nonempty_fintype α h').elim h⟩, fun ⟨h⟩ => ⟨fun h' => h h'.finite⟩⟩ /-- A non-infinite type is a fintype. -/ noncomputable def fintypeOfNotInfinite {α : Type*} (h : ¬Infinite α) : Fintype α := @Fintype.ofFinite _ (not_infinite_iff_finite.mp h) section open scoped Classical /-- Any type is (classically) either a `Fintype`, or `Infinite`. One can obtain the relevant typeclasses via `cases fintypeOrInfinite α`. -/ noncomputable def fintypeOrInfinite (α : Type*) : Fintype α ⊕' Infinite α := if h : Infinite α then PSum.inr h else PSum.inl (fintypeOfNotInfinite h) end theorem Finset.exists_minimal {α : Type*} [Preorder α] (s : Finset α) (h : s.Nonempty) : ∃ m ∈ s, ∀ x ∈ s, ¬x < m := by obtain ⟨c, hcs : c ∈ s⟩ := h have : WellFounded (@LT.lt { x // x ∈ s } _) := Finite.wellFounded_of_trans_of_irrefl _ obtain ⟨⟨m, hms : m ∈ s⟩, -, H⟩ := this.has_min Set.univ ⟨⟨c, hcs⟩, trivial⟩ exact ⟨m, hms, fun x hx hxm => H ⟨x, hx⟩ trivial hxm⟩ theorem Finset.exists_maximal {α : Type*} [Preorder α] (s : Finset α) (h : s.Nonempty) : ∃ m ∈ s, ∀ x ∈ s, ¬m < x := @Finset.exists_minimal αᵒᵈ _ s h namespace Infinite theorem of_not_fintype (h : Fintype α → False) : Infinite α := isEmpty_fintype.mp ⟨h⟩ /-- If `s : Set α` is a proper subset of `α` and `f : α → s` is injective, then `α` is infinite. -/ theorem of_injective_to_set {s : Set α} (hs : s ≠ Set.univ) {f : α → s} (hf : Injective f) : Infinite α := of_not_fintype fun h => by classical refine lt_irrefl (Fintype.card α) ?_ calc Fintype.card α ≤ Fintype.card s := Fintype.card_le_of_injective f hf _ = s.toFinset.card := s.toFinset_card.symm _ < Fintype.card α := Finset.card_lt_card <| by rwa [Set.toFinset_ssubset_univ, Set.ssubset_univ_iff] /-- If `s : Set α` is a proper subset of `α` and `f : s → α` is surjective, then `α` is infinite. -/ theorem of_surjective_from_set {s : Set α} (hs : s ≠ Set.univ) {f : s → α} (hf : Surjective f) : Infinite α := of_injective_to_set hs (injective_surjInv hf) theorem exists_not_mem_finset [Infinite α] (s : Finset α) : ∃ x, x ∉ s := not_forall.1 fun h => Fintype.false ⟨s, h⟩ -- see Note [lower instance priority] instance (priority := 100) (α : Type*) [H : Infinite α] : Nontrivial α := ⟨let ⟨x, _hx⟩ := exists_not_mem_finset (∅ : Finset α) let ⟨y, hy⟩ := exists_not_mem_finset ({x} : Finset α) ⟨y, x, by simpa only [mem_singleton] using hy⟩⟩ protected theorem nonempty (α : Type*) [Infinite α] : Nonempty α := by infer_instance theorem of_injective {α β} [Infinite β] (f : β → α) (hf : Injective f) : Infinite α := ⟨fun _I => (Finite.of_injective f hf).false⟩ theorem of_surjective {α β} [Infinite β] (f : α → β) (hf : Surjective f) : Infinite α := ⟨fun _I => (Finite.of_surjective f hf).false⟩ instance {β : α → Type*} [Infinite α] [∀ a, Nonempty (β a)] : Infinite ((a : α) × β a) := Infinite.of_surjective Sigma.fst Sigma.fst_surjective theorem sigma_of_right {β : α → Type*} {a : α} [Infinite (β a)] : Infinite ((a : α) × β a) := Infinite.of_injective (f := fun x ↦ ⟨a,x⟩) fun _ _ ↦ by simp instance {β : α → Type*} [Nonempty α] [∀ a, Infinite (β a)] : Infinite ((a : α) × β a) := Infinite.sigma_of_right (a := Classical.arbitrary α) end Infinite instance : Infinite ℕ := Infinite.of_not_fintype <| by intro h exact (Finset.range _).card_le_univ.not_lt ((Nat.lt_succ_self _).trans_eq (card_range _).symm) instance Int.infinite : Infinite ℤ := Infinite.of_injective Int.ofNat fun _ _ => Int.ofNat.inj instance [Nonempty α] : Infinite (Multiset α) := let ⟨x⟩ := ‹Nonempty α› Infinite.of_injective (fun n => Multiset.replicate n x) (Multiset.replicate_left_injective _) instance [Nonempty α] : Infinite (List α) := Infinite.of_surjective ((↑) : List α → Multiset α) (surjective_quot_mk _) instance String.infinite : Infinite String := Infinite.of_injective (String.mk) <| by intro _ _ h cases h with | refl => rfl instance Infinite.set [Infinite α] : Infinite (Set α) := Infinite.of_injective singleton Set.singleton_injective instance [Infinite α] : Infinite (Finset α) := Infinite.of_injective singleton Finset.singleton_injective instance [Infinite α] : Infinite (Option α) := Infinite.of_injective some (Option.some_injective α) instance Sum.infinite_of_left [Infinite α] : Infinite (α ⊕ β) := Infinite.of_injective Sum.inl Sum.inl_injective instance Sum.infinite_of_right [Infinite β] : Infinite (α ⊕ β) := Infinite.of_injective Sum.inr Sum.inr_injective instance Prod.infinite_of_right [Nonempty α] [Infinite β] : Infinite (α × β) := Infinite.of_surjective Prod.snd Prod.snd_surjective instance Prod.infinite_of_left [Infinite α] [Nonempty β] : Infinite (α × β) := Infinite.of_surjective Prod.fst Prod.fst_surjective instance instInfiniteProdSubtypeCommute [Mul α] [Infinite α] : Infinite { p : α × α // Commute p.1 p.2 } := Infinite.of_injective (fun a => ⟨⟨a, a⟩, rfl⟩) (by intro; simp) namespace Infinite private noncomputable def natEmbeddingAux (α : Type*) [Infinite α] : ℕ → α | n => letI := Classical.decEq α Classical.choose (exists_not_mem_finset ((Multiset.range n).pmap (fun m (hm : m < n) => natEmbeddingAux _ m) fun _ => Multiset.mem_range.1).toFinset) private theorem natEmbeddingAux_injective (α : Type*) [Infinite α] : Function.Injective (natEmbeddingAux α) := by rintro m n h letI := Classical.decEq α wlog hmlen : m ≤ n generalizing m n · exact (this h.symm <| le_of_not_le hmlen).symm by_contra hmn have hmn : m < n := lt_of_le_of_ne hmlen hmn refine (Classical.choose_spec (exists_not_mem_finset ((Multiset.range n).pmap (fun m (_ : m < n) ↦ natEmbeddingAux α m) (fun _ ↦ Multiset.mem_range.1)).toFinset)) ?_ refine Multiset.mem_toFinset.2 (Multiset.mem_pmap.2 ⟨m, Multiset.mem_range.2 hmn, ?_⟩) rw [h, natEmbeddingAux] /-- Embedding of `ℕ` into an infinite type. -/ noncomputable def natEmbedding (α : Type*) [Infinite α] : ℕ ↪ α := ⟨_, natEmbeddingAux_injective α⟩ /-- See `Infinite.exists_superset_card_eq` for a version that, for an `s : Finset α`, provides a superset `t : Finset α`, `s ⊆ t` such that `t.card` is fixed. -/ theorem exists_subset_card_eq (α : Type*) [Infinite α] (n : ℕ) : ∃ s : Finset α, s.card = n := ⟨(range n).map (natEmbedding α), by rw [card_map, card_range]⟩ /-- See `Infinite.exists_subset_card_eq` for a version that provides an arbitrary `s : Finset α` for any cardinality. -/ theorem exists_superset_card_eq [Infinite α] (s : Finset α) (n : ℕ) (hn : s.card ≤ n) : ∃ t : Finset α, s ⊆ t ∧ t.card = n := by induction' n with n IH generalizing s · exact ⟨s, subset_refl _, Nat.eq_zero_of_le_zero hn⟩ · rcases hn.eq_or_lt with hn' | hn' · exact ⟨s, subset_refl _, hn'⟩ obtain ⟨t, hs, ht⟩ := IH _ (Nat.le_of_lt_succ hn') obtain ⟨x, hx⟩ := exists_not_mem_finset t refine ⟨Finset.cons x t hx, hs.trans (Finset.subset_cons _), ?_⟩ simp [hx, ht] end Infinite /-- If every finset in a type has bounded cardinality, that type is finite. -/ noncomputable def fintypeOfFinsetCardLe {ι : Type*} (n : ℕ) (w : ∀ s : Finset ι, s.card ≤ n) : Fintype ι := by apply fintypeOfNotInfinite intro i obtain ⟨s, c⟩ := Infinite.exists_subset_card_eq ι (n + 1) specialize w s rw [c] at w exact Nat.not_succ_le_self n w theorem not_injective_infinite_finite {α β} [Infinite α] [Finite β] (f : α → β) : ¬Injective f := fun hf => (Finite.of_injective f hf).false /-- The pigeonhole principle for infinitely many pigeons in finitely many pigeonholes. If there are infinitely many pigeons in finitely many pigeonholes, then there are at least two pigeons in the same pigeonhole. See also: `Fintype.exists_ne_map_eq_of_card_lt`, `Finite.exists_infinite_fiber`. -/ theorem Finite.exists_ne_map_eq_of_infinite {α β} [Infinite α] [Finite β] (f : α → β) : ∃ x y : α, x ≠ y ∧ f x = f y := by simpa [Injective, and_comm] using not_injective_infinite_finite f instance Function.Embedding.is_empty {α β} [Infinite α] [Finite β] : IsEmpty (α ↪ β) := ⟨fun f => not_injective_infinite_finite f f.2⟩ /-- The strong pigeonhole principle for infinitely many pigeons in finitely many pigeonholes. If there are infinitely many pigeons in finitely many pigeonholes, then there is a pigeonhole with infinitely many pigeons. See also: `Finite.exists_ne_map_eq_of_infinite` -/ theorem Finite.exists_infinite_fiber [Infinite α] [Finite β] (f : α → β) : ∃ y : β, Infinite (f ⁻¹' {y}) := by classical by_contra! hf cases nonempty_fintype β haveI := fun y => fintypeOfNotInfinite <| hf y let key : Fintype α := { elems := univ.biUnion fun y : β => (f ⁻¹' {y}).toFinset complete := by simp } exact key.false theorem not_surjective_finite_infinite {α β} [Finite α] [Infinite β] (f : α → β) : ¬Surjective f := fun hf => (Infinite.of_surjective f hf).not_finite ‹_› section Ranges /-- For any `c : List ℕ` whose sum is at most `Fintype.card α`, we can find `o : List (List α)` whose members have no duplicate, whose lengths given by `c`, and which are pairwise disjoint -/ theorem List.exists_pw_disjoint_with_card {α : Type*} [Fintype α] {c : List ℕ} (hc : c.sum ≤ Fintype.card α) : ∃ o : List (List α), o.map length = c ∧ (∀ s ∈ o, s.Nodup) ∧ Pairwise List.Disjoint o := by let klift (n : ℕ) (hn : n < Fintype.card α) : Fin (Fintype.card α) := (⟨n, hn⟩ : Fin (Fintype.card α)) let klift' (l : List ℕ) (hl : ∀ a ∈ l, a < Fintype.card α) : List (Fin (Fintype.card α)) := List.pmap klift l hl have hc'_lt : ∀ l ∈ c.ranges, ∀ n ∈ l, n < Fintype.card α := by intro l hl n hn apply lt_of_lt_of_le _ hc rw [← mem_mem_ranges_iff_lt_sum] exact ⟨l, hl, hn⟩ let l := (ranges c).pmap klift' hc'_lt have hl : ∀ (a : List ℕ) (ha : a ∈ c.ranges), (klift' a (hc'_lt a ha)).map Fin.valEmbedding = a := by intro a ha conv_rhs => rw [← List.map_id a] rw [List.map_pmap] simp only [Fin.valEmbedding_apply, Fin.val_mk, List.pmap_eq_map, List.map_id', List.map_id] use l.map (List.map (Fintype.equivFin α).symm) constructor · -- length rw [← ranges_length c] simp only [l, klift', map_map, map_pmap, Function.comp_apply, length_map, length_pmap, pmap_eq_map] constructor · -- nodup intro s rw [mem_map] rintro ⟨t, ht, rfl⟩ apply Nodup.map (Equiv.injective _) obtain ⟨u, hu, rfl⟩ := mem_pmap.mp ht apply Nodup.of_map rw [hl u hu] exact ranges_nodup hu · -- pairwise disjoint refine Pairwise.map _ (fun s t ↦ disjoint_map (Equiv.injective _)) ?_ -- List.Pairwise List.disjoint l apply Pairwise.pmap (List.ranges_disjoint c) intro u hu v hv huv apply disjoint_pmap · intro a a' ha ha' h simpa only [klift, Fin.mk_eq_mk] using h exact huv end Ranges section Trunc /-- A `Fintype` with positive cardinality constructively contains an element. -/ def truncOfCardPos {α} [Fintype α] (h : 0 < Fintype.card α) : Trunc α := letI := Fintype.card_pos_iff.mp h truncOfNonemptyFintype α end Trunc /-- A custom induction principle for fintypes. The base case is a subsingleton type, and the induction step is for non-trivial types, and one can assume the hypothesis for smaller types (via `Fintype.card`). The major premise is `Fintype α`, so to use this with the `induction` tactic you have to give a name to that instance and use that name. -/ @[elab_as_elim] theorem Fintype.induction_subsingleton_or_nontrivial {P : ∀ (α) [Fintype α], Prop} (α : Type*) [Fintype α] (hbase : ∀ (α) [Fintype α] [Subsingleton α], P α) (hstep : ∀ (α) [Fintype α] [Nontrivial α], (∀ (β) [Fintype β], Fintype.card β < Fintype.card α → P β) → P α) : P α := by obtain ⟨n, hn⟩ : ∃ n, Fintype.card α = n := ⟨Fintype.card α, rfl⟩ induction' n using Nat.strong_induction_on with n ih generalizing α cases' subsingleton_or_nontrivial α with hsing hnontriv · apply hbase · apply hstep intro β _ hlt rw [hn] at hlt exact ih (Fintype.card β) hlt _ rfl
Data\Fintype\CardEmbedding.lean
/- Copyright (c) 2021 Eric Rodriguez. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Rodriguez -/ import Mathlib.Data.Fintype.BigOperators import Mathlib.Logic.Equiv.Embedding /-! # Number of embeddings This file establishes the cardinality of `α ↪ β` in full generality. -/ local notation "|" x "|" => Finset.card x local notation "‖" x "‖" => Fintype.card x open Function open Nat namespace Fintype theorem card_embedding_eq_of_unique {α β : Type*} [Unique α] [Fintype β] [Fintype (α ↪ β)] : ‖α ↪ β‖ = ‖β‖ := card_congr Equiv.uniqueEmbeddingEquivResult -- Establishes the cardinality of the type of all injections between two finite types. -- Porting note: `induction'` is broken so instead we make an ugly refine and `dsimp` a lot. @[simp] theorem card_embedding_eq {α β : Type*} [Fintype α] [Fintype β] [emb : Fintype (α ↪ β)] : ‖α ↪ β‖ = ‖β‖.descFactorial ‖α‖ := by rw [Subsingleton.elim emb Embedding.fintype] refine Fintype.induction_empty_option (P := fun t ↦ ‖t ↪ β‖ = ‖β‖.descFactorial ‖t‖) (fun α₁ α₂ h₂ e ih ↦ ?_) (?_) (fun γ h ih ↦ ?_) α <;> dsimp only <;> clear! α · letI := Fintype.ofEquiv _ e.symm rw [← card_congr (Equiv.embeddingCongr e (Equiv.refl β)), ih, card_congr e] · rw [card_pempty, Nat.descFactorial_zero, card_eq_one_iff] exact ⟨Embedding.ofIsEmpty, fun x ↦ DFunLike.ext _ _ isEmptyElim⟩ · classical dsimp only at ih rw [card_option, Nat.descFactorial_succ, card_congr (Embedding.optionEmbeddingEquiv γ β), card_sigma, ← ih] simp only [Fintype.card_compl_set, Fintype.card_range, Finset.sum_const, Finset.card_univ, Nat.nsmul_eq_mul, mul_comm] /-- The cardinality of embeddings from an infinite type to a finite type is zero. This is a re-statement of the pigeonhole principle. -/ theorem card_embedding_eq_of_infinite {α β : Type*} [Infinite α] [Finite β] [Fintype (α ↪ β)] : ‖α ↪ β‖ = 0 := card_eq_zero end Fintype
Data\Fintype\Fin.lean
/- Copyright (c) 2021 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import Mathlib.Order.Interval.Finset.Fin /-! # The structure of `Fintype (Fin n)` This file contains some basic results about the `Fintype` instance for `Fin`, especially properties of `Finset.univ : Finset (Fin n)`. -/ open Mathlib open Finset open Fintype namespace Fin variable {α β : Type*} {n : ℕ} theorem map_valEmbedding_univ : (Finset.univ : Finset (Fin n)).map Fin.valEmbedding = Iio n := by ext simp [orderIsoSubtype.symm.surjective.exists, OrderIso.symm] @[simp] theorem Ioi_zero_eq_map : Ioi (0 : Fin n.succ) = univ.map (Fin.succEmb _) := coe_injective <| by ext; simp [pos_iff_ne_zero] @[simp] theorem Iio_last_eq_map : Iio (Fin.last n) = Finset.univ.map Fin.castSuccEmb := coe_injective <| by ext; simp [lt_def] @[simp] theorem Ioi_succ (i : Fin n) : Ioi i.succ = (Ioi i).map (Fin.succEmb _) := by ext i simp only [mem_filter, mem_Ioi, mem_map, mem_univ, true_and_iff, Function.Embedding.coeFn_mk, exists_true_left] constructor · refine cases ?_ ?_ i · rintro ⟨⟨⟩⟩ · intro i hi exact ⟨i, succ_lt_succ_iff.mp hi, rfl⟩ · rintro ⟨i, hi, rfl⟩ simpa @[simp] theorem Iio_castSucc (i : Fin n) : Iio (castSucc i) = (Iio i).map Fin.castSuccEmb := by apply Finset.map_injective Fin.valEmbedding rw [Finset.map_map, Fin.map_valEmbedding_Iio] exact (Fin.map_valEmbedding_Iio i).symm theorem card_filter_univ_succ' (p : Fin (n + 1) → Prop) [DecidablePred p] : (univ.filter p).card = ite (p 0) 1 0 + (univ.filter (p ∘ Fin.succ)).card := by rw [Fin.univ_succ, filter_cons, card_disjUnion, filter_map, card_map] split_ifs <;> simp theorem card_filter_univ_succ (p : Fin (n + 1) → Prop) [DecidablePred p] : (univ.filter p).card = if p 0 then (univ.filter (p ∘ Fin.succ)).card + 1 else (univ.filter (p ∘ Fin.succ)).card := (card_filter_univ_succ' p).trans (by split_ifs <;> simp [add_comm 1]) theorem card_filter_univ_eq_vector_get_eq_count [DecidableEq α] (a : α) (v : Vector α n) : (univ.filter fun i => v.get i = a).card = v.toList.count a := by induction' v with n x xs hxs · simp · simp_rw [card_filter_univ_succ', Vector.get_cons_zero, Vector.toList_cons, Function.comp, Vector.get_cons_succ, hxs, List.count_cons, add_comm (ite (x = a) 1 0), beq_iff_eq] end Fin
Data\Fintype\Lattice.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.Fintype.Card import Mathlib.Data.Finset.Lattice /-! # Lemmas relating fintypes and order/lattice structure. -/ open Function open Nat universe u v variable {ι α β : Type*} namespace Finset variable [Fintype α] {s : Finset α} /-- A special case of `Finset.sup_eq_iSup` that omits the useless `x ∈ univ` binder. -/ theorem sup_univ_eq_iSup [CompleteLattice β] (f : α → β) : Finset.univ.sup f = iSup f := (sup_eq_iSup _ f).trans <| congr_arg _ <| funext fun _ => iSup_pos (mem_univ _) /-- A special case of `Finset.inf_eq_iInf` that omits the useless `x ∈ univ` binder. -/ theorem inf_univ_eq_iInf [CompleteLattice β] (f : α → β) : Finset.univ.inf f = iInf f := @sup_univ_eq_iSup _ βᵒᵈ _ _ (f : α → βᵒᵈ) @[simp] theorem fold_inf_univ [SemilatticeInf α] [OrderBot α] (a : α) : -- Porting note: added `haveI` haveI : Std.Commutative (α := α) (· ⊓ ·) := inferInstance (Finset.univ.fold (· ⊓ ·) a fun x => x) = ⊥ := eq_bot_iff.2 <| ((Finset.fold_op_rel_iff_and <| @le_inf_iff α _).1 le_rfl).2 ⊥ <| Finset.mem_univ _ @[simp] theorem fold_sup_univ [SemilatticeSup α] [OrderTop α] (a : α) : -- Porting note: added `haveI` haveI : Std.Commutative (α := α) (· ⊔ ·) := inferInstance (Finset.univ.fold (· ⊔ ·) a fun x => x) = ⊤ := @fold_inf_univ αᵒᵈ _ _ _ _ lemma mem_inf [DecidableEq α] {s : Finset ι} {f : ι → Finset α} {a : α} : a ∈ s.inf f ↔ ∀ i ∈ s, a ∈ f i := by induction' s using Finset.cons_induction <;> simp [*] end Finset open Finset Function theorem Finite.exists_max [Finite α] [Nonempty α] [LinearOrder β] (f : α → β) : ∃ x₀ : α, ∀ x, f x ≤ f x₀ := by cases nonempty_fintype α simpa using exists_max_image univ f univ_nonempty theorem Finite.exists_min [Finite α] [Nonempty α] [LinearOrder β] (f : α → β) : ∃ x₀ : α, ∀ x, f x₀ ≤ f x := by cases nonempty_fintype α simpa using exists_min_image univ f univ_nonempty
Data\Fintype\List.lean
/- Copyright (c) 2021 Yakov Pechersky. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yakov Pechersky -/ import Mathlib.Data.Fintype.Basic import Mathlib.Data.Finset.Powerset /-! # Fintype instance for nodup lists The subtype of `{l : List α // l.nodup}` over a `[Fintype α]` admits a `Fintype` instance. ## Implementation details To construct the `Fintype` instance, a function lifting a `Multiset α` to the `Finset (List α)` that can construct it is provided. This function is applied to the `Finset.powerset` of `Finset.univ`. In general, a `DecidableEq` instance is not necessary to define this function, but a proof of `(List.permutations l).nodup` is required to avoid it, which is a TODO. -/ variable {α : Type*} [DecidableEq α] open List namespace Multiset /-- The `Finset` of `l : List α` that, given `m : Multiset α`, have the property `⟦l⟧ = m`. -/ def lists : Multiset α → Finset (List α) := fun s => Quotient.liftOn s (fun l => l.permutations.toFinset) fun l l' (h : l ~ l') => by ext sl simp only [mem_permutations, List.mem_toFinset] exact ⟨fun hs => hs.trans h, fun hs => hs.trans h.symm⟩ @[simp] theorem lists_coe (l : List α) : lists (l : Multiset α) = l.permutations.toFinset := rfl @[simp] theorem mem_lists_iff (s : Multiset α) (l : List α) : l ∈ lists s ↔ s = ⟦l⟧ := by induction s using Quotient.inductionOn simpa using perm_comm end Multiset instance fintypeNodupList [Fintype α] : Fintype { l : List α // l.Nodup } := Fintype.subtype ((Finset.univ : Finset α).powerset.biUnion fun s => s.val.lists) fun l => by suffices (∃ a : Finset α, a.val = ↑l) ↔ l.Nodup by simpa constructor · rintro ⟨s, hs⟩ simpa [← Multiset.coe_nodup, ← hs] using s.nodup · intro hl refine ⟨⟨↑l, hl⟩, ?_⟩ simp
Data\Fintype\Option.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.Fintype.Card import Mathlib.Data.Finset.Option /-! # fintype instances for option -/ assert_not_exists MonoidWithZero assert_not_exists MulAction open Function open Nat universe u v variable {α β γ : Type*} open Finset Function instance {α : Type*} [Fintype α] : Fintype (Option α) := ⟨Finset.insertNone univ, fun a => by simp⟩ theorem univ_option (α : Type*) [Fintype α] : (univ : Finset (Option α)) = insertNone univ := rfl @[simp] theorem Fintype.card_option {α : Type*} [Fintype α] : Fintype.card (Option α) = Fintype.card α + 1 := (Finset.card_cons (by simp)).trans <| congr_arg₂ _ (card_map _) rfl /-- If `Option α` is a `Fintype` then so is `α` -/ def fintypeOfOption {α : Type*} [Fintype (Option α)] : Fintype α := ⟨Finset.eraseNone (Fintype.elems (α := Option α)), fun x => mem_eraseNone.mpr (Fintype.complete (some x))⟩ /-- A type is a `Fintype` if its successor (using `Option`) is a `Fintype`. -/ def fintypeOfOptionEquiv [Fintype α] (f : α ≃ Option β) : Fintype β := haveI := Fintype.ofEquiv _ f fintypeOfOption namespace Fintype /-- A recursor principle for finite types, analogous to `Nat.rec`. It effectively says that every `Fintype` is either `Empty` or `Option α`, up to an `Equiv`. -/ def truncRecEmptyOption {P : Type u → Sort v} (of_equiv : ∀ {α β}, α ≃ β → P α → P β) (h_empty : P PEmpty) (h_option : ∀ {α} [Fintype α] [DecidableEq α], P α → P (Option α)) (α : Type u) [Fintype α] [DecidableEq α] : Trunc (P α) := by suffices ∀ n : ℕ, Trunc (P (ULift <| Fin n)) by apply Trunc.bind (this (Fintype.card α)) intro h apply Trunc.map _ (Fintype.truncEquivFin α) intro e exact of_equiv (Equiv.ulift.trans e.symm) h apply ind where -- Porting note: do a manual recursion, instead of `induction` tactic, -- to ensure the result is computable /-- Internal induction hypothesis -/ ind : ∀ n : ℕ, Trunc (P (ULift <| Fin n)) | Nat.zero => by have : card PEmpty = card (ULift (Fin 0)) := by simp only [card_fin, card_pempty, card_ulift] apply Trunc.bind (truncEquivOfCardEq this) intro e apply Trunc.mk exact of_equiv e h_empty | Nat.succ n => by have : card (Option (ULift (Fin n))) = card (ULift (Fin n.succ)) := by simp only [card_fin, card_option, card_ulift] apply Trunc.bind (truncEquivOfCardEq this) intro e apply Trunc.map _ (ind n) intro ih exact of_equiv e (h_option ih) -- Porting note: due to instance inference issues in `SetTheory.Cardinal.Basic` -- I had to explicitly name `h_fintype` in order to access it manually. -- was `[Fintype α]` /-- An induction principle for finite types, analogous to `Nat.rec`. It effectively says that every `Fintype` is either `Empty` or `Option α`, up to an `Equiv`. -/ @[elab_as_elim] theorem induction_empty_option {P : ∀ (α : Type u) [Fintype α], Prop} (of_equiv : ∀ (α β) [Fintype β] (e : α ≃ β), @P α (@Fintype.ofEquiv α β ‹_› e.symm) → @P β ‹_›) (h_empty : P PEmpty) (h_option : ∀ (α) [Fintype α], P α → P (Option α)) (α : Type u) [h_fintype : Fintype α] : P α := by obtain ⟨p⟩ := let f_empty := fun i => by convert h_empty let h_option : ∀ {α : Type u} [Fintype α] [DecidableEq α], (∀ (h : Fintype α), P α) → ∀ (h : Fintype (Option α)), P (Option α) := by rintro α hα - Pα hα' convert h_option α (Pα _) @truncRecEmptyOption (fun α => ∀ h, @P α h) (@fun α β e hα hβ => @of_equiv α β hβ e (hα _)) f_empty h_option α _ (Classical.decEq α) exact p _ -- · end Fintype /-- An induction principle for finite types, analogous to `Nat.rec`. It effectively says that every `Fintype` is either `Empty` or `Option α`, up to an `Equiv`. -/ theorem Finite.induction_empty_option {P : Type u → Prop} (of_equiv : ∀ {α β}, α ≃ β → P α → P β) (h_empty : P PEmpty) (h_option : ∀ {α} [Fintype α], P α → P (Option α)) (α : Type u) [Finite α] : P α := by cases nonempty_fintype α refine Fintype.induction_empty_option ?_ ?_ ?_ α exacts [fun α β _ => of_equiv, h_empty, @h_option]
Data\Fintype\Order.lean
/- Copyright (c) 2021 Peter Nelson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Peter Nelson, Yaël Dillies -/ import Mathlib.Data.Finset.Order import Mathlib.Order.Atoms import Mathlib.Data.Set.Finite /-! # Order structures on finite types This file provides order instances on fintypes. ## Computable instances On a `Fintype`, we can construct * an `OrderBot` from `SemilatticeInf`. * an `OrderTop` from `SemilatticeSup`. * a `BoundedOrder` from `Lattice`. Those are marked as `def` to avoid defeqness issues. ## Completion instances Those instances are noncomputable because the definitions of `sSup` and `sInf` use `Set.toFinset` and set membership is undecidable in general. On a `Fintype`, we can promote: * a `Lattice` to a `CompleteLattice`. * a `DistribLattice` to a `CompleteDistribLattice`. * a `LinearOrder` to a `CompleteLinearOrder`. * a `BooleanAlgebra` to a `CompleteAtomicBooleanAlgebra`. Those are marked as `def` to avoid typeclass loops. ## Concrete instances We provide a few instances for concrete types: * `Fin.completeLinearOrder` * `Bool.completeLinearOrder` * `Bool.completeBooleanAlgebra` -/ open Finset namespace Fintype variable {ι α : Type*} [Fintype ι] [Fintype α] section Nonempty variable (α) [Nonempty α] -- See note [reducible non-instances] /-- Constructs the `⊥` of a finite nonempty `SemilatticeInf`. -/ abbrev toOrderBot [SemilatticeInf α] : OrderBot α where bot := univ.inf' univ_nonempty id bot_le a := inf'_le _ <| mem_univ a -- See note [reducible non-instances] /-- Constructs the `⊤` of a finite nonempty `SemilatticeSup` -/ abbrev toOrderTop [SemilatticeSup α] : OrderTop α where top := univ.sup' univ_nonempty id -- Porting note: needed to make `id` explicit le_top a := le_sup' id <| mem_univ a -- See note [reducible non-instances] /-- Constructs the `⊤` and `⊥` of a finite nonempty `Lattice`. -/ abbrev toBoundedOrder [Lattice α] : BoundedOrder α := { toOrderBot α, toOrderTop α with } end Nonempty section BoundedOrder variable (α) open scoped Classical -- See note [reducible non-instances] /-- A finite bounded lattice is complete. -/ noncomputable abbrev toCompleteLattice [Lattice α] [BoundedOrder α] : CompleteLattice α where __ := ‹Lattice α› __ := ‹BoundedOrder α› sSup := fun s => s.toFinset.sup id sInf := fun s => s.toFinset.inf id le_sSup := fun _ _ ha => Finset.le_sup (f := id) (Set.mem_toFinset.mpr ha) sSup_le := fun s _ ha => Finset.sup_le fun b hb => ha _ <| Set.mem_toFinset.mp hb sInf_le := fun _ _ ha => Finset.inf_le (Set.mem_toFinset.mpr ha) le_sInf := fun s _ ha => Finset.le_inf fun b hb => ha _ <| Set.mem_toFinset.mp hb -- See note [reducible non-instances] /-- A finite bounded distributive lattice is completely distributive. -/ noncomputable abbrev toCompleteDistribLatticeMinimalAxioms [DistribLattice α] [BoundedOrder α] : CompleteDistribLattice.MinimalAxioms α where __ := toCompleteLattice α iInf_sup_le_sup_sInf := fun a s => by convert (Finset.inf_sup_distrib_left s.toFinset id a).ge using 1 rw [Finset.inf_eq_iInf] simp_rw [Set.mem_toFinset] rfl inf_sSup_le_iSup_inf := fun a s => by convert (Finset.sup_inf_distrib_left s.toFinset id a).le using 1 rw [Finset.sup_eq_iSup] simp_rw [Set.mem_toFinset] rfl -- See note [reducible non-instances] /-- A finite bounded distributive lattice is completely distributive. -/ noncomputable abbrev toCompleteDistribLattice [DistribLattice α] [BoundedOrder α] : CompleteDistribLattice α := .ofMinimalAxioms (toCompleteDistribLatticeMinimalAxioms _) -- See note [reducible non-instances] /-- A finite bounded linear order is complete. -/ noncomputable abbrev toCompleteLinearOrder [LinearOrder α] [BoundedOrder α] : CompleteLinearOrder α := { toCompleteLattice α, ‹LinearOrder α›, LinearOrder.toBiheytingAlgebra with } -- See note [reducible non-instances] /-- A finite boolean algebra is complete. -/ noncomputable abbrev toCompleteBooleanAlgebra [BooleanAlgebra α] : CompleteBooleanAlgebra α where __ := ‹BooleanAlgebra α› __ := Fintype.toCompleteDistribLattice α -- See note [reducible non-instances] /-- A finite boolean algebra is complete and atomic. -/ noncomputable abbrev toCompleteAtomicBooleanAlgebra [BooleanAlgebra α] : CompleteAtomicBooleanAlgebra α := (toCompleteBooleanAlgebra α).toCompleteAtomicBooleanAlgebra end BoundedOrder section Nonempty variable (α) [Nonempty α] -- See note [reducible non-instances] /-- A nonempty finite lattice is complete. If the lattice is already a `BoundedOrder`, then use `Fintype.toCompleteLattice` instead, as this gives definitional equality for `⊥` and `⊤`. -/ noncomputable abbrev toCompleteLatticeOfNonempty [Lattice α] : CompleteLattice α := @toCompleteLattice _ _ _ <| @toBoundedOrder α _ ⟨Classical.arbitrary α⟩ _ -- See note [reducible non-instances] /-- A nonempty finite linear order is complete. If the linear order is already a `BoundedOrder`, then use `Fintype.toCompleteLinearOrder` instead, as this gives definitional equality for `⊥` and `⊤`. -/ noncomputable abbrev toCompleteLinearOrderOfNonempty [LinearOrder α] : CompleteLinearOrder α := by let _ := toBoundedOrder α exact { toCompleteLatticeOfNonempty α, ‹LinearOrder α›, LinearOrder.toBiheytingAlgebra with } end Nonempty end Fintype /-! ### Concrete instances -/ noncomputable instance Fin.completeLinearOrder {n : ℕ} [NeZero n] : CompleteLinearOrder (Fin n) := Fintype.toCompleteLinearOrder _ noncomputable instance Bool.completeLinearOrder : CompleteLinearOrder Bool := Fintype.toCompleteLinearOrder _ noncomputable instance Bool.completeBooleanAlgebra : CompleteBooleanAlgebra Bool := Fintype.toCompleteBooleanAlgebra _ noncomputable instance Bool.completeAtomicBooleanAlgebra : CompleteAtomicBooleanAlgebra Bool := Fintype.toCompleteAtomicBooleanAlgebra _ /-! ### Directed Orders -/ variable {α : Type*} {r : α → α → Prop} [IsTrans α r] {β γ : Type*} [Nonempty γ] {f : γ → α} [Finite β] theorem Directed.finite_set_le (D : Directed r f) {s : Set γ} (hs : s.Finite) : ∃ z, ∀ i ∈ s, r (f i) (f z) := by convert D.finset_le hs.toFinset; rw [Set.Finite.mem_toFinset] theorem Directed.finite_le (D : Directed r f) (g : β → γ) : ∃ z, ∀ i, r (f (g i)) (f z) := by classical obtain ⟨z, hz⟩ := D.finite_set_le (Set.finite_range g) exact ⟨z, fun i => hz (g i) ⟨i, rfl⟩⟩ variable [Nonempty α] [Preorder α] theorem Finite.exists_le [IsDirected α (· ≤ ·)] (f : β → α) : ∃ M, ∀ i, f i ≤ M := directed_id.finite_le _ theorem Finite.exists_ge [IsDirected α (· ≥ ·)] (f : β → α) : ∃ M, ∀ i, M ≤ f i := directed_id.finite_le (r := (· ≥ ·)) _ theorem Set.Finite.exists_le [IsDirected α (· ≤ ·)] {s : Set α} (hs : s.Finite) : ∃ M, ∀ i ∈ s, i ≤ M := directed_id.finite_set_le hs theorem Set.Finite.exists_ge [IsDirected α (· ≥ ·)] {s : Set α} (hs : s.Finite) : ∃ M, ∀ i ∈ s, M ≤ i := directed_id.finite_set_le (r := (· ≥ ·)) hs theorem Finite.bddAbove_range [IsDirected α (· ≤ ·)] (f : β → α) : BddAbove (Set.range f) := by obtain ⟨M, hM⟩ := Finite.exists_le f refine ⟨M, fun a ha => ?_⟩ obtain ⟨b, rfl⟩ := ha exact hM b theorem Finite.bddBelow_range [IsDirected α (· ≥ ·)] (f : β → α) : BddBelow (Set.range f) := by obtain ⟨M, hM⟩ := Finite.exists_ge f refine ⟨M, fun a ha => ?_⟩ obtain ⟨b, rfl⟩ := ha exact hM b @[deprecated (since := "2024-01-16")] alias Directed.fintype_le := Directed.finite_le @[deprecated (since := "2024-01-16")] alias Fintype.exists_le := Finite.exists_le @[deprecated (since := "2024-01-16")] alias Fintype.exists_ge := Finite.exists_ge @[deprecated (since := "2024-01-16")] alias Fintype.bddAbove_range := Finite.bddAbove_range @[deprecated (since := "2024-01-16")] alias Fintype.bddBelow_range := Finite.bddBelow_range
Data\Fintype\Parity.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.Fintype.Card /-! # The cardinality of `Fin 2` is even. -/ variable {α : Type*} namespace Fintype instance IsSquare.decidablePred [Mul α] [Fintype α] [DecidableEq α] : DecidablePred (IsSquare : α → Prop) := fun _ => Fintype.decidableExistsFintype /-- The cardinality of `Fin 2` is even, `Fact` version. This `Fact` is needed as an instance by `Matrix.SpecialLinearGroup.instNeg`. -/ instance card_fin_two : Fact (Even (Fintype.card (Fin 2))) := ⟨⟨1, rfl⟩⟩ end Fintype
Data\Fintype\Perm.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.Fintype.Card import Mathlib.GroupTheory.Perm.Basic import Mathlib.Tactic.Ring /-! # `Fintype` instances for `Equiv` and `Perm` Main declarations: * `permsOfFinset s`: The finset of permutations of the finset `s`. -/ open Function open Nat universe u v variable {α β γ : Type*} open Finset Function List Equiv Equiv.Perm variable [DecidableEq α] [DecidableEq β] /-- Given a list, produce a list of all permutations of its elements. -/ def permsOfList : List α → List (Perm α) | [] => [1] | a :: l => permsOfList l ++ l.bind fun b => (permsOfList l).map fun f => Equiv.swap a b * f theorem length_permsOfList : ∀ l : List α, length (permsOfList l) = l.length ! | [] => rfl | a :: l => by rw [length_cons, Nat.factorial_succ] simp only [permsOfList, length_append, length_permsOfList, length_bind, comp, length_map, map_const', sum_replicate, smul_eq_mul, succ_mul] ring theorem mem_permsOfList_of_mem {l : List α} {f : Perm α} (h : ∀ x, f x ≠ x → x ∈ l) : f ∈ permsOfList l := by induction l generalizing f with | nil => -- Porting note: applied `not_mem_nil` because it is no longer true definitionally. simp only [not_mem_nil] at h exact List.mem_singleton.2 (Equiv.ext fun x => Decidable.by_contradiction <| h x) | cons a l IH => by_cases hfa : f a = a · refine mem_append_left _ (IH fun x hx => mem_of_ne_of_mem ?_ (h x hx)) rintro rfl exact hx hfa have hfa' : f (f a) ≠ f a := mt (fun h => f.injective h) hfa have : ∀ x : α, (Equiv.swap a (f a) * f) x ≠ x → x ∈ l := by intro x hx have hxa : x ≠ a := by rintro rfl apply hx simp only [mul_apply, swap_apply_right] refine List.mem_of_ne_of_mem hxa (h x fun h => ?_) simp only [mul_apply, swap_apply_def, mul_apply, Ne, apply_eq_iff_eq] at hx split_ifs at hx with h_1 exacts [hxa (h.symm.trans h_1), hx h] suffices f ∈ permsOfList l ∨ ∃ b ∈ l, ∃ g ∈ permsOfList l, Equiv.swap a b * g = f by simpa only [permsOfList, exists_prop, List.mem_map, mem_append, List.mem_bind] refine or_iff_not_imp_left.2 fun _hfl => ⟨f a, ?_, Equiv.swap a (f a) * f, IH this, ?_⟩ · exact mem_of_ne_of_mem hfa (h _ hfa') · rw [← mul_assoc, mul_def (swap a (f a)) (swap a (f a)), swap_swap, ← Perm.one_def, one_mul] theorem mem_of_mem_permsOfList : -- Porting note: was `∀ {x}` but need to capture the `x` ∀ {l : List α} {f : Perm α}, f ∈ permsOfList l → (x : α ) → f x ≠ x → x ∈ l | [], f, h, heq_iff_eq => by have : f = 1 := by simpa [permsOfList] using h rw [this]; simp | a :: l, f, h, x => (mem_append.1 h).elim (fun h hx => mem_cons_of_mem _ (mem_of_mem_permsOfList h x hx)) fun h hx => let ⟨y, hy, hy'⟩ := List.mem_bind.1 h let ⟨g, hg₁, hg₂⟩ := List.mem_map.1 hy' -- Porting note: Seems like the implicit variable `x` of type `α` is needed. if hxa : x = a then by simp [hxa] else if hxy : x = y then mem_cons_of_mem _ <| by rwa [hxy] else mem_cons_of_mem a <| mem_of_mem_permsOfList hg₁ _ <| by rw [eq_inv_mul_iff_mul_eq.2 hg₂, mul_apply, swap_inv, swap_apply_def] split_ifs <;> [exact Ne.symm hxy; exact Ne.symm hxa; exact hx] theorem mem_permsOfList_iff {l : List α} {f : Perm α} : f ∈ permsOfList l ↔ ∀ {x}, f x ≠ x → x ∈ l := ⟨mem_of_mem_permsOfList, mem_permsOfList_of_mem⟩ theorem nodup_permsOfList : ∀ {l : List α}, l.Nodup → (permsOfList l).Nodup | [], _ => by simp [permsOfList] | a :: l, hl => by have hl' : l.Nodup := hl.of_cons have hln' : (permsOfList l).Nodup := nodup_permsOfList hl' have hmeml : ∀ {f : Perm α}, f ∈ permsOfList l → f a = a := fun {f} hf => not_not.1 (mt (mem_of_mem_permsOfList hf _) (nodup_cons.1 hl).1) rw [permsOfList, List.nodup_append, List.nodup_bind, pairwise_iff_getElem] refine ⟨?_, ⟨⟨?_,?_ ⟩, ?_⟩⟩ · exact hln' · exact fun _ _ => hln'.map fun _ _ => mul_left_cancel · intros i j hi hj hij x hx₁ hx₂ let ⟨f, hf⟩ := List.mem_map.1 hx₁ let ⟨g, hg⟩ := List.mem_map.1 hx₂ have hix : x a = l[i] := by rw [← hf.2, mul_apply, hmeml hf.1, swap_apply_left] have hiy : x a = l[j] := by rw [← hg.2, mul_apply, hmeml hg.1, swap_apply_left] have hieqj : i = j := hl'.getElem_inj_iff.1 (hix.symm.trans hiy) exact absurd hieqj (_root_.ne_of_lt hij) · intros f hf₁ hf₂ let ⟨x, hx, hx'⟩ := List.mem_bind.1 hf₂ let ⟨g, hg⟩ := List.mem_map.1 hx' have hgxa : g⁻¹ x = a := f.injective <| by rw [hmeml hf₁, ← hg.2]; simp have hxa : x ≠ a := fun h => (List.nodup_cons.1 hl).1 (h ▸ hx) exact (List.nodup_cons.1 hl).1 <| hgxa ▸ mem_of_mem_permsOfList hg.1 _ (by rwa [apply_inv_self, hgxa]) /-- Given a finset, produce the finset of all permutations of its elements. -/ def permsOfFinset (s : Finset α) : Finset (Perm α) := Quotient.hrecOn s.1 (fun l hl => ⟨permsOfList l, nodup_permsOfList hl⟩) (fun a b hab => hfunext (congr_arg _ (Quotient.sound hab)) fun ha hb _ => heq_of_eq <| Finset.ext <| by simp [mem_permsOfList_iff, hab.mem_iff]) s.2 theorem mem_perms_of_finset_iff : ∀ {s : Finset α} {f : Perm α}, f ∈ permsOfFinset s ↔ ∀ {x}, f x ≠ x → x ∈ s := by rintro ⟨⟨l⟩, hs⟩ f; exact mem_permsOfList_iff theorem card_perms_of_finset : ∀ s : Finset α, (permsOfFinset s).card = s.card ! := by rintro ⟨⟨l⟩, hs⟩; exact length_permsOfList l /-- The collection of permutations of a fintype is a fintype. -/ def fintypePerm [Fintype α] : Fintype (Perm α) := ⟨permsOfFinset (@Finset.univ α _), by simp [mem_perms_of_finset_iff]⟩ instance equivFintype [Fintype α] [Fintype β] : Fintype (α ≃ β) := if h : Fintype.card β = Fintype.card α then Trunc.recOnSubsingleton (Fintype.truncEquivFin α) fun eα => Trunc.recOnSubsingleton (Fintype.truncEquivFin β) fun eβ => @Fintype.ofEquiv _ (Perm α) fintypePerm (equivCongr (Equiv.refl α) (eα.trans (Eq.recOn h eβ.symm)) : α ≃ α ≃ (α ≃ β)) else ⟨∅, fun x => False.elim (h (Fintype.card_eq.2 ⟨x.symm⟩))⟩ theorem Fintype.card_perm [Fintype α] : Fintype.card (Perm α) = (Fintype.card α)! := Subsingleton.elim (@fintypePerm α _ _) (@equivFintype α α _ _ _ _) ▸ card_perms_of_finset _ theorem Fintype.card_equiv [Fintype α] [Fintype β] (e : α ≃ β) : Fintype.card (α ≃ β) = (Fintype.card α)! := Fintype.card_congr (equivCongr (Equiv.refl α) e) ▸ Fintype.card_perm
Data\Fintype\Pi.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.Finset.Card import Mathlib.Data.Finset.Pi import Mathlib.Data.Fintype.Basic /-! # Fintype instances for pi types -/ open Finset Function variable {α β : Type*} namespace Fintype variable [DecidableEq α] [Fintype α] {γ δ : α → Type*} {s : ∀ a, Finset (γ a)} /-- Given for all `a : α` a finset `t a` of `δ a`, then one can define the finset `Fintype.piFinset t` of all functions taking values in `t a` for all `a`. This is the analogue of `Finset.pi` where the base finset is `univ` (but formally they are not the same, as there is an additional condition `i ∈ Finset.univ` in the `Finset.pi` definition). -/ def piFinset (t : ∀ a, Finset (δ a)) : Finset (∀ a, δ a) := (Finset.univ.pi t).map ⟨fun f a => f a (mem_univ a), fun _ _ => by simp (config := {contextual := true}) [Function.funext_iff]⟩ @[simp] theorem mem_piFinset {t : ∀ a, Finset (δ a)} {f : ∀ a, δ a} : f ∈ piFinset t ↔ ∀ a, f a ∈ t a := by constructor · simp only [piFinset, mem_map, and_imp, forall_prop_of_true, exists_prop, mem_univ, exists_imp, mem_pi] rintro g hg hgf a rw [← hgf] exact hg a · simp only [piFinset, mem_map, forall_prop_of_true, exists_prop, mem_univ, mem_pi] exact fun hf => ⟨fun a _ => f a, hf, rfl⟩ @[simp] theorem coe_piFinset (t : ∀ a, Finset (δ a)) : (piFinset t : Set (∀ a, δ a)) = Set.pi Set.univ fun a => t a := Set.ext fun x => by rw [Set.mem_univ_pi] exact Fintype.mem_piFinset theorem piFinset_subset (t₁ t₂ : ∀ a, Finset (δ a)) (h : ∀ a, t₁ a ⊆ t₂ a) : piFinset t₁ ⊆ piFinset t₂ := fun _ hg => mem_piFinset.2 fun a => h a <| mem_piFinset.1 hg a @[simp] theorem piFinset_empty [Nonempty α] : piFinset (fun _ => ∅ : ∀ i, Finset (δ i)) = ∅ := eq_empty_of_forall_not_mem fun _ => by simp @[simp, aesop safe apply (rule_sets := [finsetNonempty])] lemma piFinset_nonempty : (piFinset s).Nonempty ↔ ∀ a, (s a).Nonempty := by simp [Finset.Nonempty, Classical.skolem] lemma _root_.Finset.Nonempty.piFinset_const {ι : Type*} [Fintype ι] [DecidableEq ι] {s : Finset β} (hs : s.Nonempty) : (piFinset fun _ : ι ↦ s).Nonempty := piFinset_nonempty.2 fun _ ↦ hs @[simp] lemma piFinset_of_isEmpty [IsEmpty α] (s : ∀ a, Finset (γ a)) : piFinset s = univ := eq_univ_of_forall fun _ ↦ by simp @[simp] theorem piFinset_singleton (f : ∀ i, δ i) : piFinset (fun i => {f i} : ∀ i, Finset (δ i)) = {f} := ext fun _ => by simp only [Function.funext_iff, Fintype.mem_piFinset, mem_singleton] theorem piFinset_subsingleton {f : ∀ i, Finset (δ i)} (hf : ∀ i, (f i : Set (δ i)).Subsingleton) : (Fintype.piFinset f : Set (∀ i, δ i)).Subsingleton := fun _ ha _ hb => funext fun _ => hf _ (mem_piFinset.1 ha _) (mem_piFinset.1 hb _) theorem piFinset_disjoint_of_disjoint (t₁ t₂ : ∀ a, Finset (δ a)) {a : α} (h : Disjoint (t₁ a) (t₂ a)) : Disjoint (piFinset t₁) (piFinset t₂) := disjoint_iff_ne.2 fun f₁ hf₁ f₂ hf₂ eq₁₂ => disjoint_iff_ne.1 h (f₁ a) (mem_piFinset.1 hf₁ a) (f₂ a) (mem_piFinset.1 hf₂ a) (congr_fun eq₁₂ a) lemma piFinset_image [∀ a, DecidableEq (δ a)] (f : ∀ a, γ a → δ a) (s : ∀ a, Finset (γ a)) : piFinset (fun a ↦ (s a).image (f a)) = (piFinset s).image fun b a ↦ f _ (b a) := by ext; simp only [mem_piFinset, mem_image, Classical.skolem, forall_and, Function.funext_iff] lemma eval_image_piFinset_subset (t : ∀ a, Finset (δ a)) (a : α) [DecidableEq (δ a)] : ((piFinset t).image fun f ↦ f a) ⊆ t a := image_subset_iff.2 fun _x hx ↦ mem_piFinset.1 hx _ lemma eval_image_piFinset (t : ∀ a, Finset (δ a)) (a : α) [DecidableEq (δ a)] (ht : ∀ b, a ≠ b → (t b).Nonempty) : ((piFinset t).image fun f ↦ f a) = t a := by refine (eval_image_piFinset_subset _ _).antisymm fun x h ↦ mem_image.2 ?_ choose f hf using ht exact ⟨fun b ↦ if h : a = b then h ▸ x else f _ h, by aesop, by simp⟩ lemma eval_image_piFinset_const {β} [DecidableEq β] (t : Finset β) (a : α) : ((piFinset fun _i : α ↦ t).image fun f ↦ f a) = t := by obtain rfl | ht := t.eq_empty_or_nonempty · haveI : Nonempty α := ⟨a⟩ simp · exact eval_image_piFinset (fun _ ↦ t) a fun _ _ ↦ ht variable [∀ a, DecidableEq (δ a)] lemma filter_piFinset_of_not_mem (t : ∀ a, Finset (δ a)) (a : α) (x : δ a) (hx : x ∉ t a) : (piFinset t).filter (· a = x) = ∅ := by simp only [filter_eq_empty_iff, mem_piFinset]; rintro f hf rfl; exact hx (hf _) -- TODO: This proof looks like a good example of something that `aesop` can't do but should lemma piFinset_update_eq_filter_piFinset_mem (s : ∀ i, Finset (δ i)) (i : α) {t : Finset (δ i)} (hts : t ⊆ s i) : piFinset (Function.update s i t) = (piFinset s).filter (fun f ↦ f i ∈ t) := by ext f simp only [mem_piFinset, mem_filter] refine ⟨fun h ↦ ?_, fun h j ↦ ?_⟩ · have := by simpa using h i refine ⟨fun j ↦ ?_, this⟩ obtain rfl | hji := eq_or_ne j i · exact hts this · simpa [hji] using h j · obtain rfl | hji := eq_or_ne j i · simpa using h.2 · simpa [hji] using h.1 j lemma piFinset_update_singleton_eq_filter_piFinset_eq (s : ∀ i, Finset (δ i)) (i : α) {a : δ i} (ha : a ∈ s i) : piFinset (Function.update s i {a}) = (piFinset s).filter (fun f ↦ f i = a) := by simp [piFinset_update_eq_filter_piFinset_mem, ha] end Fintype /-! ### pi -/ /-- A dependent product of fintypes, indexed by a fintype, is a fintype. -/ instance Pi.fintype {α : Type*} {β : α → Type*} [DecidableEq α] [Fintype α] [∀ a, Fintype (β a)] : Fintype (∀ a, β a) := ⟨Fintype.piFinset fun _ => univ, by simp⟩ @[simp] theorem Fintype.piFinset_univ {α : Type*} {β : α → Type*} [DecidableEq α] [Fintype α] [∀ a, Fintype (β a)] : (Fintype.piFinset fun a : α => (Finset.univ : Finset (β a))) = (Finset.univ : Finset (∀ a, β a)) := rfl -- Porting note: this instance used to be computable in Lean3 and used `decidable_eq`, but -- it makes things a lot harder to work with here. in some ways that was because in Lean3 -- we could make this instance irreducible when needed and in the worst case use `congr/convert`, -- but those don't work with subsingletons in lean4 as-is so we cannot do this here. noncomputable instance _root_.Function.Embedding.fintype {α β} [Fintype α] [Fintype β] : Fintype (α ↪ β) := by classical exact Fintype.ofEquiv _ (Equiv.subtypeInjectiveEquivEmbedding α β) instance RelHom.instFintype {α β} [Fintype α] [Fintype β] [DecidableEq α] {r : α → α → Prop} {s : β → β → Prop} [DecidableRel r] [DecidableRel s] : Fintype (r →r s) := Fintype.ofEquiv {f : α → β // ∀ {x y}, r x y → s (f x) (f y)} <| Equiv.mk (fun f ↦ ⟨f.1, f.2⟩) (fun f ↦ ⟨f.1, f.2⟩) (fun _ ↦ rfl) (fun _ ↦ rfl) noncomputable instance RelEmbedding.instFintype {α β} [Fintype α] [Fintype β] {r : α → α → Prop} {s : β → β → Prop} : Fintype (r ↪r s) := Fintype.ofInjective _ RelEmbedding.toEmbedding_injective @[simp] theorem Finset.univ_pi_univ {α : Type*} {β : α → Type*} [DecidableEq α] [Fintype α] [∀ a, Fintype (β a)] : (Finset.univ.pi fun a : α => (Finset.univ : Finset (β a))) = Finset.univ := by ext; simp /-! ### Diagonal -/ namespace Finset variable {ι : Type*} [DecidableEq (ι → α)] {s : Finset α} {f : ι → α} lemma piFinset_filter_const [DecidableEq ι] [Fintype ι] : (Fintype.piFinset fun _ ↦ s).filter (∃ a ∈ s, const ι a = ·) = s.piDiag ι := by aesop lemma piDiag_subset_piFinset [DecidableEq ι] [Fintype ι] : s.piDiag ι ⊆ Fintype.piFinset fun _ ↦ s := by simp [← piFinset_filter_const] end Finset
Data\Fintype\Powerset.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.Fintype.Card import Mathlib.Data.Finset.Powerset /-! # fintype instance for `Set α`, when `α` is a fintype -/ variable {α : Type*} open Finset instance Finset.fintype [Fintype α] : Fintype (Finset α) := ⟨univ.powerset, fun _ => Finset.mem_powerset.2 (Finset.subset_univ _)⟩ @[simp] theorem Fintype.card_finset [Fintype α] : Fintype.card (Finset α) = 2 ^ Fintype.card α := Finset.card_powerset Finset.univ namespace Finset variable [Fintype α] {s : Finset α} {k : ℕ} @[simp] lemma powerset_univ : (univ : Finset α).powerset = univ := coe_injective <| by simp [-coe_eq_univ] lemma filter_subset_univ [DecidableEq α] (s : Finset α) : filter (fun t ↦ t ⊆ s) univ = powerset s := by ext; simp @[simp] lemma powerset_eq_univ : s.powerset = univ ↔ s = univ := by rw [← Finset.powerset_univ, powerset_inj] lemma mem_powersetCard_univ : s ∈ powersetCard k (univ : Finset α) ↔ card s = k := mem_powersetCard.trans <| and_iff_right <| subset_univ _ variable (α) @[simp] lemma univ_filter_card_eq (k : ℕ) : (univ : Finset (Finset α)).filter (fun s ↦ s.card = k) = univ.powersetCard k := by ext; simp end Finset @[simp] theorem Fintype.card_finset_len [Fintype α] (k : ℕ) : Fintype.card { s : Finset α // s.card = k } = Nat.choose (Fintype.card α) k := by simp [Fintype.subtype_card, Finset.card_univ] instance Set.fintype [Fintype α] : Fintype (Set α) := ⟨(@Finset.univ (Finset α) _).map coeEmb.1, fun s => by classical refine mem_map.2 ⟨Finset.univ.filter (· ∈ s), Finset.mem_univ _, (coe_filter _ _).trans ?_⟩ simp⟩ -- Not to be confused with `Set.Finite`, the predicate instance Set.finite' [Finite α] : Finite (Set α) := by cases nonempty_fintype α infer_instance @[simp] theorem Fintype.card_set [Fintype α] : Fintype.card (Set α) = 2 ^ Fintype.card α := (Finset.card_map _).trans (Finset.card_powerset _)
Data\Fintype\Prod.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.Fintype.Card import Mathlib.Data.Finset.Prod /-! # fintype instance for the product of two fintypes. -/ open Function open Nat universe u v variable {α β γ : Type*} open Finset Function namespace Set variable {s t : Set α} theorem toFinset_prod (s : Set α) (t : Set β) [Fintype s] [Fintype t] [Fintype (s ×ˢ t)] : (s ×ˢ t).toFinset = s.toFinset ×ˢ t.toFinset := by ext simp theorem toFinset_off_diag {s : Set α} [DecidableEq α] [Fintype s] [Fintype s.offDiag] : s.offDiag.toFinset = s.toFinset.offDiag := Finset.ext <| by simp end Set instance instFintypeProd (α β : Type*) [Fintype α] [Fintype β] : Fintype (α × β) := ⟨univ ×ˢ univ, fun ⟨a, b⟩ => by simp⟩ namespace Finset variable [Fintype α] [Fintype β] {s : Finset α} {t : Finset β} @[simp] lemma univ_product_univ : univ ×ˢ univ = (univ : Finset (α × β)) := rfl @[simp] lemma product_eq_univ [Nonempty α] [Nonempty β] : s ×ˢ t = univ ↔ s = univ ∧ t = univ := by simp [eq_univ_iff_forall, forall_and] end Finset @[simp] theorem Fintype.card_prod (α β : Type*) [Fintype α] [Fintype β] : Fintype.card (α × β) = Fintype.card α * Fintype.card β := card_product _ _ section open scoped Classical @[simp] theorem infinite_prod : Infinite (α × β) ↔ Infinite α ∧ Nonempty β ∨ Nonempty α ∧ Infinite β := by refine ⟨fun H => ?_, fun H => H.elim (and_imp.2 <| @Prod.infinite_of_left α β) (and_imp.2 <| @Prod.infinite_of_right α β)⟩ rw [and_comm]; contrapose! H; intro H' rcases Infinite.nonempty (α × β) with ⟨a, b⟩ haveI := fintypeOfNotInfinite (H.1 ⟨b⟩); haveI := fintypeOfNotInfinite (H.2 ⟨a⟩) exact H'.false instance Pi.infinite_of_left {ι : Sort*} {π : ι → Type*} [∀ i, Nontrivial <| π i] [Infinite ι] : Infinite (∀ i : ι, π i) := by choose m n hm using fun i => exists_pair_ne (π i) refine Infinite.of_injective (fun i => update m i (n i)) fun x y h => of_not_not fun hne => ?_ simp_rw [update_eq_iff, update_noteq hne] at h exact (hm x h.1.symm).elim /-- If at least one `π i` is infinite and the rest nonempty, the pi type of all `π` is infinite. -/ theorem Pi.infinite_of_exists_right {ι : Sort*} {π : ι → Sort*} (i : ι) [Infinite <| π i] [∀ i, Nonempty <| π i] : Infinite (∀ i : ι, π i) := let ⟨m⟩ := @Pi.instNonempty ι π _ Infinite.of_injective _ (update_injective m i) /-- See `Pi.infinite_of_exists_right` for the case that only one `π i` is infinite. -/ instance Pi.infinite_of_right {ι : Sort*} {π : ι → Type*} [∀ i, Infinite <| π i] [Nonempty ι] : Infinite (∀ i : ι, π i) := Pi.infinite_of_exists_right (Classical.arbitrary ι) /-- Non-dependent version of `Pi.infinite_of_left`. -/ instance Function.infinite_of_left {ι : Sort*} {π : Type*} [Nontrivial π] [Infinite ι] : Infinite (ι → π) := Pi.infinite_of_left /-- Non-dependent version of `Pi.infinite_of_exists_right` and `Pi.infinite_of_right`. -/ instance Function.infinite_of_right {ι : Sort*} {π : Type*} [Infinite π] [Nonempty ι] : Infinite (ι → π) := Pi.infinite_of_right end
Data\Fintype\Quotient.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.Fintype.Basic /-! # Quotients of families indexed by a finite type This file provides `Quotient.finChoice`, a mechanism to go from a finite family of quotients to a quotient of finite families. ## Main definitions * `Quotient.finChoice` -/ /-- An auxiliary function for `Quotient.finChoice`. Given a collection of setoids indexed by a type `ι`, a (finite) list `l` of indices, and a function that for each `i ∈ l` gives a term of the corresponding quotient type, then there is a corresponding term in the quotient of the product of the setoids indexed by `l`. -/ def Quotient.finChoiceAux {ι : Type*} [DecidableEq ι] {α : ι → Type*} [S : ∀ i, Setoid (α i)] : ∀ l : List ι, (∀ i ∈ l, Quotient (S i)) → @Quotient (∀ i ∈ l, α i) (by infer_instance) | [], _ => ⟦fun i h => nomatch List.not_mem_nil _ h⟧ | i :: l, f => by refine Quotient.liftOn₂ (f i (List.mem_cons_self _ _)) (Quotient.finChoiceAux l fun j h => f j (List.mem_cons_of_mem _ h)) ?_ ?_ · exact fun a l => ⟦fun j h => if e : j = i then by rw [e]; exact a else l _ ((List.mem_cons.1 h).resolve_left e)⟧ refine fun a₁ l₁ a₂ l₂ h₁ h₂ => Quotient.sound fun j h => ?_ by_cases e : j = i · simp [e]; subst j exact h₁ · simpa [e] using h₂ _ _ theorem Quotient.finChoiceAux_eq {ι : Type*} [DecidableEq ι] {α : ι → Type*} [S : ∀ i, Setoid (α i)] : ∀ (l : List ι) (f : ∀ i ∈ l, α i), (Quotient.finChoiceAux l fun i h => ⟦f i h⟧) = ⟦f⟧ | [], f => Quotient.sound fun i h => nomatch List.not_mem_nil _ h | i :: l, f => by simp only [finChoiceAux, Quotient.finChoiceAux_eq l, eq_mpr_eq_cast, lift_mk] refine Quotient.sound fun j h => ?_ by_cases e : j = i <;> simp [e] <;> try exact Setoid.refl _ subst j; exact Setoid.refl _ /-- Given a collection of setoids indexed by a fintype `ι` and a function that for each `i : ι` gives a term of the corresponding quotient type, then there is corresponding term in the quotient of the product of the setoids. -/ def Quotient.finChoice {ι : Type*} [DecidableEq ι] [Fintype ι] {α : ι → Type*} [S : ∀ i, Setoid (α i)] (f : ∀ i, Quotient (S i)) : @Quotient (∀ i, α i) (by infer_instance) := Quotient.liftOn (@Quotient.recOn _ _ (fun l : Multiset ι => @Quotient (∀ i ∈ l, α i) (by infer_instance)) Finset.univ.1 (fun l => Quotient.finChoiceAux l fun i _ => f i) (fun a b h => by have := fun a => Quotient.finChoiceAux_eq a fun i _ => Quotient.out (f i) simp? [Quotient.out_eq] at this says simp only [out_eq] at this simp only [Multiset.quot_mk_to_coe, this] let g := fun a : Multiset ι => (⟦fun (i : ι) (_ : i ∈ a) => Quotient.out (f i)⟧ : Quotient (by infer_instance)) apply eq_of_heq trans (g a) · exact eq_rec_heq (φ := fun l : Multiset ι => @Quotient (∀ i ∈ l, α i) (by infer_instance)) (Quotient.sound h) (g a) · change HEq (g a) (g b); congr 1; exact Quotient.sound h)) (fun f => ⟦fun i => f i (Finset.mem_univ _)⟧) (fun a b h => Quotient.sound fun i => by apply h) theorem Quotient.finChoice_eq {ι : Type*} [DecidableEq ι] [Fintype ι] {α : ι → Type*} [∀ i, Setoid (α i)] (f : ∀ i, α i) : (Quotient.finChoice fun i => ⟦f i⟧) = ⟦f⟧ := by dsimp only [Quotient.finChoice] conv_lhs => enter [1] tactic => change _ = ⟦fun i _ => f i⟧ exact Quotient.inductionOn (@Finset.univ ι _).1 fun l => Quotient.finChoiceAux_eq _ _ rfl /-- Given a function that for each `i : ι` gives a term of the corresponding truncation type, then there is corresponding term in the truncation of the product. -/ def Trunc.finChoice {ι : Type*} [DecidableEq ι] [Fintype ι] {α : ι → Type*} (f : ∀ i, Trunc (α i)) : Trunc (∀ i, α i) := Quotient.map' id (fun _ _ _ => trivial) (Quotient.finChoice f (S := fun _ => trueSetoid)) theorem Trunc.finChoice_eq {ι : Type*} [DecidableEq ι] [Fintype ι] {α : ι → Type*} (f : ∀ i, α i) : (Trunc.finChoice fun i => Trunc.mk (f i)) = Trunc.mk f := Subsingleton.elim _ _
Data\Fintype\Shrink.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 Mathlib.Data.Countable.Small import Mathlib.Data.Fintype.Card /-! # Fintype instance for `Shrink` -/ universe u v variable {α : Type u} [Fintype α] noncomputable instance Shrink.instFintype : Fintype (Shrink.{v} α) := .ofEquiv _ (equivShrink _) instance Shrink.instFinite {α : Type u} [Finite α] : Finite (Shrink.{v} α) := .of_equiv _ (equivShrink _) @[simp] lemma Fintype.card_shrink [Fintype (Shrink.{v} α)] : card (Shrink.{v} α) = card α := card_congr (equivShrink _).symm
Data\Fintype\Sigma.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.Fintype.Basic import Mathlib.Data.Finset.Sigma /-! # fintype instances for sigma types -/ open Function open Nat universe u v variable {ι α β γ : Type*} {κ : ι → Type*} [Π i, Fintype (κ i)] open Finset Function lemma Set.biUnion_finsetSigma_univ (s : Finset ι) (f : Sigma κ → Set α) : ⋃ ij ∈ s.sigma fun _ ↦ Finset.univ, f ij = ⋃ i ∈ s, ⋃ j, f ⟨i, j⟩ := by aesop lemma Set.biUnion_finsetSigma_univ' (s : Finset ι) (f : Π i, κ i → Set α) : ⋃ i ∈ s, ⋃ j, f i j = ⋃ ij ∈ s.sigma fun _ ↦ Finset.univ, f ij.1 ij.2 := by aesop lemma Set.biInter_finsetSigma_univ (s : Finset ι) (f : Sigma κ → Set α) : ⋂ ij ∈ s.sigma fun _ ↦ Finset.univ, f ij = ⋂ i ∈ s, ⋂ j, f ⟨i, j⟩ := by aesop lemma Set.biInter_finsetSigma_univ' (s : Finset ι) (f : Π i, κ i → Set α) : ⋂ i ∈ s, ⋂ j, f i j = ⋂ ij ∈ s.sigma fun _ ↦ Finset.univ, f ij.1 ij.2 := by aesop variable [Fintype ι] instance Sigma.instFintype : Fintype (Σ i, κ i) := ⟨univ.sigma fun _ ↦ univ, by simp⟩ instance PSigma.instFintype : Fintype (Σ' i, κ i) := .ofEquiv _ (Equiv.psigmaEquivSigma _).symm @[simp] lemma Finset.univ_sigma_univ : univ.sigma (fun _ ↦ univ) = (univ : Finset (Σ i, κ i)) := rfl
Data\Fintype\Sort.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.Finset.Sort import Mathlib.Data.Fintype.Basic /-! # Sorting a finite type This file provides two equivalences for linearly ordered fintypes: * `monoEquivOfFin`: Order isomorphism between `α` and `Fin (card α)`. * `finSumEquivOfFinset`: Equivalence between `α` and `Fin m ⊕ Fin n` where `m` and `n` are respectively the cardinalities of some `Finset α` and its complement. -/ open Finset /-- Given a linearly ordered fintype `α` of cardinal `k`, the order isomorphism `monoEquivOfFin α h` is the increasing bijection between `Fin k` and `α`. Here, `h` is a proof that the cardinality of `α` is `k`. We use this instead of an isomorphism `Fin (card α) ≃o α` to avoid casting issues in further uses of this function. -/ def monoEquivOfFin (α : Type*) [Fintype α] [LinearOrder α] {k : ℕ} (h : Fintype.card α = k) : Fin k ≃o α := (univ.orderIsoOfFin h).trans <| (OrderIso.setCongr _ _ coe_univ).trans OrderIso.Set.univ variable {α : Type*} [DecidableEq α] [Fintype α] [LinearOrder α] {m n : ℕ} {s : Finset α} /-- If `α` is a linearly ordered fintype, `s : Finset α` has cardinality `m` and its complement has cardinality `n`, then `Fin m ⊕ Fin n ≃ α`. The equivalence sends elements of `Fin m` to elements of `s` and elements of `Fin n` to elements of `sᶜ` while preserving order on each "half" of `Fin m ⊕ Fin n` (using `Set.orderIsoOfFin`). -/ def finSumEquivOfFinset (hm : s.card = m) (hn : sᶜ.card = n) : Fin m ⊕ Fin n ≃ α := calc Fin m ⊕ Fin n ≃ (s : Set α) ⊕ (sᶜ : Set α) := Equiv.sumCongr (s.orderIsoOfFin hm).toEquiv <| (sᶜ.orderIsoOfFin hn).toEquiv.trans <| Equiv.Set.ofEq s.coe_compl _ ≃ α := Equiv.Set.sumCompl _ @[simp] theorem finSumEquivOfFinset_inl (hm : s.card = m) (hn : sᶜ.card = n) (i : Fin m) : finSumEquivOfFinset hm hn (Sum.inl i) = s.orderEmbOfFin hm i := rfl @[simp] theorem finSumEquivOfFinset_inr (hm : s.card = m) (hn : sᶜ.card = n) (i : Fin n) : finSumEquivOfFinset hm hn (Sum.inr i) = sᶜ.orderEmbOfFin hn i := rfl
Data\Fintype\Sum.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.Fintype.Card import Mathlib.Data.Finset.Sum import Mathlib.Logic.Embedding.Set /-! ## Instances We provide the `Fintype` instance for the sum of two fintypes. -/ universe u v variable {α β : Type*} open Finset instance (α : Type u) (β : Type v) [Fintype α] [Fintype β] : Fintype (α ⊕ β) where elems := univ.disjSum univ complete := by rintro (_ | _) <;> simp @[simp] theorem Finset.univ_disjSum_univ {α β : Type*} [Fintype α] [Fintype β] : univ.disjSum univ = (univ : Finset (α ⊕ β)) := rfl @[simp] theorem Fintype.card_sum [Fintype α] [Fintype β] : Fintype.card (α ⊕ β) = Fintype.card α + Fintype.card β := card_disjSum _ _ /-- If the subtype of all-but-one elements is a `Fintype` then the type itself is a `Fintype`. -/ def fintypeOfFintypeNe (a : α) (h : Fintype { b // b ≠ a }) : Fintype α := Fintype.ofBijective (Sum.elim ((↑) : { b // b = a } → α) ((↑) : { b // b ≠ a } → α)) <| by classical exact (Equiv.sumCompl (· = a)).bijective theorem image_subtype_ne_univ_eq_image_erase [Fintype α] [DecidableEq β] (k : β) (b : α → β) : image (fun i : { a // b a ≠ k } => b ↑i) univ = (image b univ).erase k := by apply subset_antisymm · rw [image_subset_iff] intro i _ apply mem_erase_of_ne_of_mem i.2 (mem_image_of_mem _ (mem_univ _)) · intro i hi rw [mem_image] rcases mem_image.1 (erase_subset _ _ hi) with ⟨a, _, ha⟩ subst ha exact ⟨⟨a, ne_of_mem_erase hi⟩, mem_univ _, rfl⟩ theorem image_subtype_univ_ssubset_image_univ [Fintype α] [DecidableEq β] (k : β) (b : α → β) (hk : k ∈ Finset.image b univ) (p : β → Prop) [DecidablePred p] (hp : ¬p k) : image (fun i : { a // p (b a) } => b ↑i) univ ⊂ image b univ := by constructor · intro x hx rcases mem_image.1 hx with ⟨y, _, hy⟩ exact hy ▸ mem_image_of_mem b (mem_univ (y : α)) · intro h rw [mem_image] at hk rcases hk with ⟨k', _, hk'⟩ subst hk' have := h (mem_image_of_mem b (mem_univ k')) rw [mem_image] at this rcases this with ⟨j, _, hj'⟩ exact hp (hj' ▸ j.2) /-- Any injection from a finset `s` in a fintype `α` to a finset `t` of the same cardinality as `α` can be extended to a bijection between `α` and `t`. -/ theorem Finset.exists_equiv_extend_of_card_eq [Fintype α] [DecidableEq β] {t : Finset β} (hαt : Fintype.card α = t.card) {s : Finset α} {f : α → β} (hfst : Finset.image f s ⊆ t) (hfs : Set.InjOn f s) : ∃ g : α ≃ t, ∀ i ∈ s, (g i : β) = f i := by classical induction' s using Finset.induction with a s has H generalizing f · obtain ⟨e⟩ : Nonempty (α ≃ ↥t) := by rwa [← Fintype.card_eq, Fintype.card_coe] use e simp have hfst' : Finset.image f s ⊆ t := (Finset.image_mono _ (s.subset_insert a)).trans hfst have hfs' : Set.InjOn f s := hfs.mono (s.subset_insert a) obtain ⟨g', hg'⟩ := H hfst' hfs' have hfat : f a ∈ t := hfst (mem_image_of_mem _ (s.mem_insert_self a)) use g'.trans (Equiv.swap (⟨f a, hfat⟩ : t) (g' a)) simp_rw [mem_insert] rintro i (rfl | hi) · simp rw [Equiv.trans_apply, Equiv.swap_apply_of_ne_of_ne, hg' _ hi] · exact ne_of_apply_ne Subtype.val (ne_of_eq_of_ne (hg' _ hi) <| hfs.ne (subset_insert _ _ hi) (mem_insert_self _ _) <| ne_of_mem_of_not_mem hi has) · exact g'.injective.ne (ne_of_mem_of_not_mem hi has) /-- Any injection from a set `s` in a fintype `α` to a finset `t` of the same cardinality as `α` can be extended to a bijection between `α` and `t`. -/ theorem Set.MapsTo.exists_equiv_extend_of_card_eq [Fintype α] {t : Finset β} (hαt : Fintype.card α = t.card) {s : Set α} {f : α → β} (hfst : s.MapsTo f t) (hfs : Set.InjOn f s) : ∃ g : α ≃ t, ∀ i ∈ s, (g i : β) = f i := by classical let s' : Finset α := s.toFinset have hfst' : s'.image f ⊆ t := by simpa [s', ← Finset.coe_subset] using hfst have hfs' : Set.InjOn f s' := by simpa [s'] using hfs obtain ⟨g, hg⟩ := Finset.exists_equiv_extend_of_card_eq hαt hfst' hfs' refine ⟨g, fun i hi => ?_⟩ apply hg simpa [s'] using hi theorem Fintype.card_subtype_or (p q : α → Prop) [Fintype { x // p x }] [Fintype { x // q x }] [Fintype { x // p x ∨ q x }] : Fintype.card { x // p x ∨ q x } ≤ Fintype.card { x // p x } + Fintype.card { x // q x } := by classical convert Fintype.card_le_of_embedding (subtypeOrLeftEmbedding p q) rw [Fintype.card_sum] theorem Fintype.card_subtype_or_disjoint (p q : α → Prop) (h : Disjoint p q) [Fintype { x // p x }] [Fintype { x // q x }] [Fintype { x // p x ∨ q x }] : Fintype.card { x // p x ∨ q x } = Fintype.card { x // p x } + Fintype.card { x // q x } := by classical convert Fintype.card_congr (subtypeOrEquiv p q h) simp section open scoped Classical @[simp] theorem infinite_sum : Infinite (α ⊕ β) ↔ Infinite α ∨ Infinite β := by refine ⟨fun H => ?_, fun H => H.elim (@Sum.infinite_of_left α β) (@Sum.infinite_of_right α β)⟩ contrapose! H; haveI := fintypeOfNotInfinite H.1; haveI := fintypeOfNotInfinite H.2 exact Infinite.false end
Data\Fintype\Units.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.Fintype.Prod import Mathlib.Data.Fintype.Sum import Mathlib.SetTheory.Cardinal.Finite /-! # fintype instances relating to units -/ variable {α : Type*} instance UnitsInt.fintype : Fintype ℤˣ := ⟨{1, -1}, fun x ↦ by cases Int.units_eq_one_or x <;> simp [*]⟩ @[simp] theorem UnitsInt.univ : (Finset.univ : Finset ℤˣ) = {1, -1} := rfl @[simp] theorem Fintype.card_units_int : Fintype.card ℤˣ = 2 := rfl instance [Monoid α] [Fintype α] [DecidableEq α] : Fintype αˣ := Fintype.ofEquiv _ (unitsEquivProdSubtype α).symm instance [Monoid α] [Finite α] : Finite αˣ := Finite.of_injective _ Units.ext theorem Fintype.card_eq_card_units_add_one [GroupWithZero α] [Fintype α] [DecidableEq α] : Fintype.card α = Fintype.card αˣ + 1 := by rw [eq_comm, Fintype.card_congr unitsEquivNeZero] have := Fintype.card_congr (Equiv.sumCompl (· = (0 : α))) rwa [Fintype.card_sum, add_comm, Fintype.card_subtype_eq] at this theorem Nat.card_eq_card_units_add_one [GroupWithZero α] [Finite α] : Nat.card α = Nat.card αˣ + 1 := by have : Fintype α := Fintype.ofFinite α classical rw [Nat.card_eq_fintype_card, Nat.card_eq_fintype_card, Fintype.card_eq_card_units_add_one] theorem Fintype.card_units [GroupWithZero α] [Fintype α] [DecidableEq α] : Fintype.card αˣ = Fintype.card α - 1 := by rw [@Fintype.card_eq_card_units_add_one α, Nat.add_sub_cancel]
Data\Fintype\Vector.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.Fintype.Pi import Mathlib.Data.Sym.Basic /-! # `Vector α n` and `Sym α n` are fintypes when `α` is. -/ open Mathlib (Vector) variable {α : Type*} instance Vector.fintype [Fintype α] {n : ℕ} : Fintype (Vector α n) := Fintype.ofEquiv _ (Equiv.vectorEquivFin _ _).symm instance [DecidableEq α] [Fintype α] {n : ℕ} : Fintype (Sym.Sym' α n) := by refine @Quotient.fintype _ _ _ ?_ -- Porting note: had to build the instance manually intros x y apply List.decidablePerm instance [DecidableEq α] [Fintype α] {n : ℕ} : Fintype (Sym α n) := Fintype.ofEquiv _ Sym.symEquivSym'.symm
Data\FP\Basic.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.Semiquot import Mathlib.Data.Nat.Size import Mathlib.Tactic.Ring.RingNF /-! # Implementation of floating-point numbers (experimental). -/ -- Porting note (#11215): TODO add docs and remove `@[nolint docBlame]` @[nolint docBlame] def Int.shift2 (a b : ℕ) : ℤ → ℕ × ℕ | Int.ofNat e => (a <<< e, b) | Int.negSucc e => (a, b <<< e.succ) namespace FP @[nolint docBlame] inductive RMode | NE -- round to nearest even deriving Inhabited @[nolint docBlame] class FloatCfg where (prec emax : ℕ) precPos : 0 < prec precMax : prec ≤ emax attribute [nolint docBlame] FloatCfg.prec FloatCfg.emax FloatCfg.precPos FloatCfg.precMax variable [C : FloatCfg] @[nolint docBlame] def prec := C.prec @[nolint docBlame] def emax := C.emax @[nolint docBlame] def emin : ℤ := 1 - C.emax @[nolint docBlame] def ValidFinite (e : ℤ) (m : ℕ) : Prop := emin ≤ e + prec - 1 ∧ e + prec - 1 ≤ emax ∧ e = max (e + m.size - prec) emin instance decValidFinite (e m) : Decidable (ValidFinite e m) := by (unfold ValidFinite; infer_instance) @[nolint docBlame] inductive Float | inf : Bool → Float | nan : Float | finite : Bool → ∀ e m, ValidFinite e m → Float @[nolint docBlame] def Float.isFinite : Float → Bool | Float.finite _ _ _ _ => true | _ => false @[nolint docBlame] def toRat : ∀ f : Float, f.isFinite → ℚ | Float.finite s e m _, _ => let (n, d) := Int.shift2 m 1 e let r := mkRat n d if s then -r else r theorem Float.Zero.valid : ValidFinite emin 0 := ⟨by rw [add_sub_assoc] apply le_add_of_nonneg_right apply sub_nonneg_of_le apply Int.ofNat_le_ofNat_of_le exact C.precPos, suffices prec ≤ 2 * emax by rw [← Int.ofNat_le] at this rw [← sub_nonneg] at * simp only [emin, emax] at * ring_nf rw [mul_comm] assumption le_trans C.precMax (Nat.le_mul_of_pos_left _ two_pos), by (rw [max_eq_right]; simp [sub_eq_add_neg])⟩ @[nolint docBlame] def Float.zero (s : Bool) : Float := Float.finite s emin 0 Float.Zero.valid instance : Inhabited Float := ⟨Float.zero true⟩ @[nolint docBlame] protected def Float.sign' : Float → Semiquot Bool | Float.inf s => pure s | Float.nan => ⊤ | Float.finite s _ _ _ => pure s @[nolint docBlame] protected def Float.sign : Float → Bool | Float.inf s => s | Float.nan => false | Float.finite s _ _ _ => s @[nolint docBlame] protected def Float.isZero : Float → Bool | Float.finite _ _ 0 _ => true | _ => false @[nolint docBlame] protected def Float.neg : Float → Float | Float.inf s => Float.inf (not s) | Float.nan => Float.nan | Float.finite s e m f => Float.finite (not s) e m f @[nolint docBlame] def divNatLtTwoPow (n d : ℕ) : ℤ → Bool | Int.ofNat e => n < d <<< e | Int.negSucc e => n <<< e.succ < d -- TODO(Mario): Prove these and drop 'unsafe' @[nolint docBlame] unsafe def ofPosRatDn (n : ℕ+) (d : ℕ+) : Float × Bool := by let e₁ : ℤ := n.1.size - d.1.size - prec cases' Int.shift2 d.1 n.1 (e₁ + prec) with d₁ n₁ let e₂ := if n₁ < d₁ then e₁ - 1 else e₁ let e₃ := max e₂ emin cases' Int.shift2 d.1 n.1 (e₃ + prec) with d₂ n₂ let r := mkRat n₂ d₂ let m := r.floor refine (Float.finite Bool.false e₃ (Int.toNat m) ?_, r.den = 1) exact lcProof -- Porting note: remove this line when you dropped 'lcProof' set_option linter.unusedVariables false in @[nolint docBlame] unsafe def nextUpPos (e m) (v : ValidFinite e m) : Float := let m' := m.succ if ss : m'.size = m.size then Float.finite false e m' (by unfold ValidFinite at *; rw [ss]; exact v) else if h : e = emax then Float.inf false else Float.finite false e.succ (Nat.div2 m') lcProof set_option linter.deprecated false in -- Porting note: remove this line when you dropped 'lcProof' set_option linter.unusedVariables false in @[nolint docBlame] unsafe def nextDnPos (e m) (v : ValidFinite e m) : Float := match m with | 0 => nextUpPos _ _ Float.Zero.valid | Nat.succ m' => -- Porting note: was `m'.size = m.size` if ss : m'.size = m'.succ.size then Float.finite false e m' (by unfold ValidFinite at *; rw [ss]; exact v) else if h : e = emin then Float.finite false emin m' lcProof else Float.finite false e.pred (2 * m' + 1) lcProof @[nolint docBlame] unsafe def nextUp : Float → Float | Float.finite Bool.false e m f => nextUpPos e m f | Float.finite Bool.true e m f => Float.neg <| nextDnPos e m f | f => f @[nolint docBlame] unsafe def nextDn : Float → Float | Float.finite Bool.false e m f => nextDnPos e m f | Float.finite Bool.true e m f => Float.neg <| nextUpPos e m f | f => f @[nolint docBlame] unsafe def ofRatUp : ℚ → Float | ⟨0, _, _, _⟩ => Float.zero false | ⟨Nat.succ n, d, h, _⟩ => let (f, exact) := ofPosRatDn n.succPNat ⟨d, Nat.pos_of_ne_zero h⟩ if exact then f else nextUp f | ⟨Int.negSucc n, d, h, _⟩ => Float.neg (ofPosRatDn n.succPNat ⟨d, Nat.pos_of_ne_zero h⟩).1 @[nolint docBlame] unsafe def ofRatDn (r : ℚ) : Float := Float.neg <| ofRatUp (-r) @[nolint docBlame] unsafe def ofRat : RMode → ℚ → Float | RMode.NE, r => let low := ofRatDn r let high := ofRatUp r if hf : high.isFinite then if r = toRat _ hf then high else if lf : low.isFinite then if r - toRat _ lf > toRat _ hf - r then high else if r - toRat _ lf < toRat _ hf - r then low else match low, lf with | Float.finite _ _ m _, _ => if 2 ∣ m then low else high else Float.inf true else Float.inf false namespace Float instance : Neg Float := ⟨Float.neg⟩ @[nolint docBlame] unsafe def add (mode : RMode) : Float → Float → Float | nan, _ => nan | _, nan => nan | inf Bool.true, inf Bool.false=> nan | inf Bool.false, inf Bool.true => nan | inf s₁, _ => inf s₁ | _, inf s₂ => inf s₂ | finite s₁ e₁ m₁ v₁, finite s₂ e₂ m₂ v₂ => let f₁ := finite s₁ e₁ m₁ v₁ let f₂ := finite s₂ e₂ m₂ v₂ ofRat mode (toRat f₁ rfl + toRat f₂ rfl) unsafe instance : Add Float := ⟨Float.add RMode.NE⟩ @[nolint docBlame] unsafe def sub (mode : RMode) (f1 f2 : Float) : Float := add mode f1 (-f2) unsafe instance : Sub Float := ⟨Float.sub RMode.NE⟩ @[nolint docBlame] unsafe def mul (mode : RMode) : Float → Float → Float | nan, _ => nan | _, nan => nan | inf s₁, f₂ => if f₂.isZero then nan else inf (xor s₁ f₂.sign) | f₁, inf s₂ => if f₁.isZero then nan else inf (xor f₁.sign s₂) | finite s₁ e₁ m₁ v₁, finite s₂ e₂ m₂ v₂ => let f₁ := finite s₁ e₁ m₁ v₁ let f₂ := finite s₂ e₂ m₂ v₂ ofRat mode (toRat f₁ rfl * toRat f₂ rfl) @[nolint docBlame] unsafe def div (mode : RMode) : Float → Float → Float | nan, _ => nan | _, nan => nan | inf _, inf _ => nan | inf s₁, f₂ => inf (xor s₁ f₂.sign) | f₁, inf s₂ => zero (xor f₁.sign s₂) | finite s₁ e₁ m₁ v₁, finite s₂ e₂ m₂ v₂ => let f₁ := finite s₁ e₁ m₁ v₁ let f₂ := finite s₂ e₂ m₂ v₂ if f₂.isZero then inf (xor s₁ s₂) else ofRat mode (toRat f₁ rfl / toRat f₂ rfl) end Float end FP
Data\FunLike\Basic.lean
/- Copyright (c) 2021 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import Mathlib.Logic.Function.Basic import Mathlib.Util.CompileInductive /-! # Typeclass for a type `F` with an injective map to `A → B` This typeclass is primarily for use by homomorphisms like `MonoidHom` and `LinearMap`. There is the "D"ependent version `DFunLike` and the non-dependent version `FunLike`. ## Basic usage of `DFunLike` and `FunLike` A typical type of morphisms should be declared as: ``` structure MyHom (A B : Type*) [MyClass A] [MyClass B] := (toFun : A → B) (map_op' : ∀ (x y : A), toFun (MyClass.op x y) = MyClass.op (toFun x) (toFun y)) namespace MyHom variable (A B : Type*) [MyClass A] [MyClass B] instance : FunLike (MyHom A B) A B where coe := MyHom.toFun coe_injective' := fun f g h => by cases f; cases g; congr @[ext] theorem ext {f g : MyHom A B} (h : ∀ x, f x = g x) : f = g := DFunLike.ext f g h /-- Copy of a `MyHom` with a new `toFun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : MyHom A B) (f' : A → B) (h : f' = ⇑f) : MyHom A B where toFun := f' map_op' := h.symm ▸ f.map_op' end MyHom ``` This file will then provide a `CoeFun` instance and various extensionality and simp lemmas. ## Morphism classes extending `DFunLike` and `FunLike` The `FunLike` design provides further benefits if you put in a bit more work. The first step is to extend `FunLike` to create a class of those types satisfying the axioms of your new type of morphisms. Continuing the example above: ``` /-- `MyHomClass F A B` states that `F` is a type of `MyClass.op`-preserving morphisms. You should extend this class when you extend `MyHom`. -/ class MyHomClass (F : Type*) (A B : outParam Type*) [MyClass A] [MyClass B] [FunLike F A B] : Prop := (map_op : ∀ (f : F) (x y : A), f (MyClass.op x y) = MyClass.op (f x) (f y)) @[simp] lemma map_op {F A B : Type*} [MyClass A] [MyClass B] [FunLike F A B] [MyHomClass F A B] (f : F) (x y : A) : f (MyClass.op x y) = MyClass.op (f x) (f y) := MyHomClass.map_op _ _ _ -- You can add the below instance next to `MyHomClass.instFunLike`: instance : MyHomClass (MyHom A B) A B where map_op := MyHom.map_op' -- [Insert `ext` and `copy` here] ``` Note that `A B` are marked as `outParam` even though they are not purely required to be so due to the `FunLike` parameter already filling them in. This is required to see through type synonyms, which is important in the category theory library. Also, it appears having them as `outParam` is slightly faster. The second step is to add instances of your new `MyHomClass` for all types extending `MyHom`. Typically, you can just declare a new class analogous to `MyHomClass`: ``` structure CoolerHom (A B : Type*) [CoolClass A] [CoolClass B] extends MyHom A B := (map_cool' : toFun CoolClass.cool = CoolClass.cool) class CoolerHomClass (F : Type*) (A B : outParam Type*) [CoolClass A] [CoolClass B] [FunLike F A B] extends MyHomClass F A B := (map_cool : ∀ (f : F), f CoolClass.cool = CoolClass.cool) @[simp] lemma map_cool {F A B : Type*} [CoolClass A] [CoolClass B] [FunLike F A B] [CoolerHomClass F A B] (f : F) : f CoolClass.cool = CoolClass.cool := CoolerHomClass.map_cool _ variable {A B : Type*} [CoolClass A] [CoolClass B] instance : FunLike (CoolerHom A B) A B where coe f := f.toFun coe_injective' := fun f g h ↦ by cases f; cases g; congr; apply DFunLike.coe_injective; congr instance : CoolerHomClass (CoolerHom A B) A B where map_op f := f.map_op' map_cool f := f.map_cool' -- [Insert `ext` and `copy` here] ``` Then any declaration taking a specific type of morphisms as parameter can instead take the class you just defined: ``` -- Compare with: lemma do_something (f : MyHom A B) : sorry := sorry lemma do_something {F : Type*} [FunLike F A B] [MyHomClass F A B] (f : F) : sorry := sorry ``` This means anything set up for `MyHom`s will automatically work for `CoolerHomClass`es, and defining `CoolerHomClass` only takes a constant amount of effort, instead of linearly increasing the work per `MyHom`-related declaration. ## Design rationale The current form of FunLike was set up in pull request #8386: https://github.com/leanprover-community/mathlib4/pull/8386 We made `FunLike` *unbundled*: child classes don't extend `FunLike`, they take a `[FunLike F A B]` parameter instead. This suits the instance synthesis algorithm better: it's easy to verify a type does **not** have a `FunLike` instance by checking the discrimination tree once instead of searching the entire `extends` hierarchy. -/ -- This instance should have low priority, to ensure we follow the chain -- `DFunLike → CoeFun` -- Porting note: this is an elaboration detail from Lean 3, we are going to disable it -- until it is clearer what the Lean 4 elaborator needs. -- attribute [instance, priority 10] coe_fn_trans /-- The class `DFunLike F α β` expresses that terms of type `F` have an injective coercion to (dependent) functions from `α` to `β`. For non-dependent functions you can also use the abbreviation `FunLike`. This typeclass is used in the definition of the homomorphism typeclasses, such as `ZeroHomClass`, `MulHomClass`, `MonoidHomClass`, .... -/ @[notation_class * toFun Simps.findCoercionArgs] class DFunLike (F : Sort*) (α : outParam (Sort*)) (β : outParam <| α → Sort*) where /-- The coercion from `F` to a function. -/ coe : F → ∀ a : α, β a /-- The coercion to functions must be injective. -/ coe_injective' : Function.Injective coe -- https://github.com/leanprover/lean4/issues/2096 compile_def% DFunLike.coe /-- The class `FunLike F α β` (`Fun`ction-`Like`) expresses that terms of type `F` have an injective coercion to functions from `α` to `β`. `FunLike` is the non-dependent version of `DFunLike`. This typeclass is used in the definition of the homomorphism typeclasses, such as `ZeroHomClass`, `MulHomClass`, `MonoidHomClass`, .... -/ abbrev FunLike F α β := DFunLike F α fun _ => β section Dependent /-! ### `DFunLike F α β` where `β` depends on `a : α` -/ variable (F α : Sort*) (β : α → Sort*) namespace DFunLike variable {F α β} [i : DFunLike F α β] instance (priority := 100) hasCoeToFun : CoeFun F (fun _ ↦ ∀ a : α, β a) where coe := @DFunLike.coe _ _ β _ -- need to make explicit to beta reduce for non-dependent functions run_cmd Lean.Elab.Command.liftTermElabM do Lean.Meta.registerCoercion ``DFunLike.coe (some { numArgs := 5, coercee := 4, type := .coeFun }) -- @[simp] -- Porting note: this loops in lean 4 theorem coe_eq_coe_fn : (DFunLike.coe (F := F)) = (fun f => ↑f) := rfl theorem coe_injective : Function.Injective (fun f : F ↦ (f : ∀ a : α, β a)) := DFunLike.coe_injective' @[simp] theorem coe_fn_eq {f g : F} : (f : ∀ a : α, β a) = (g : ∀ a : α, β a) ↔ f = g := ⟨fun h ↦ DFunLike.coe_injective' h, fun h ↦ by cases h; rfl⟩ theorem ext' {f g : F} (h : (f : ∀ a : α, β a) = (g : ∀ a : α, β a)) : f = g := DFunLike.coe_injective' h theorem ext'_iff {f g : F} : f = g ↔ (f : ∀ a : α, β a) = (g : ∀ a : α, β a) := coe_fn_eq.symm theorem ext (f g : F) (h : ∀ x : α, f x = g x) : f = g := DFunLike.coe_injective' (funext h) theorem ext_iff {f g : F} : f = g ↔ ∀ x, f x = g x := coe_fn_eq.symm.trans Function.funext_iff protected theorem congr_fun {f g : F} (h₁ : f = g) (x : α) : f x = g x := congr_fun (congr_arg _ h₁) x theorem ne_iff {f g : F} : f ≠ g ↔ ∃ a, f a ≠ g a := ext_iff.not.trans not_forall theorem exists_ne {f g : F} (h : f ≠ g) : ∃ x, f x ≠ g x := ne_iff.mp h /-- This is not an instance to avoid slowing down every single `Subsingleton` typeclass search. -/ lemma subsingleton_cod [∀ a, Subsingleton (β a)] : Subsingleton F := ⟨fun _ _ ↦ coe_injective <| Subsingleton.elim _ _⟩ end DFunLike end Dependent section NonDependent /-! ### `FunLike F α β` where `β` does not depend on `a : α` -/ variable {F α β : Sort*} [i : FunLike F α β] namespace DFunLike protected theorem congr {f g : F} {x y : α} (h₁ : f = g) (h₂ : x = y) : f x = g y := congr (congr_arg _ h₁) h₂ protected theorem congr_arg (f : F) {x y : α} (h₂ : x = y) : f x = f y := congr_arg _ h₂ end DFunLike end NonDependent
Data\FunLike\Embedding.lean
/- Copyright (c) 2021 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import Mathlib.Data.FunLike.Basic /-! # Typeclass for a type `F` with an injective map to `A ↪ B` This typeclass is primarily for use by embeddings such as `RelEmbedding`. ## Basic usage of `EmbeddingLike` A typical type of embeddings should be declared as: ``` structure MyEmbedding (A B : Type*) [MyClass A] [MyClass B] := (toFun : A → B) (injective' : Function.Injective toFun) (map_op' : ∀ (x y : A), toFun (MyClass.op x y) = MyClass.op (toFun x) (toFun y)) namespace MyEmbedding variable (A B : Type*) [MyClass A] [MyClass B] instance : FunLike (MyEmbedding A B) A B where coe := MyEmbedding.toFun coe_injective' := fun f g h ↦ by cases f; cases g; congr -- This instance is optional if you follow the "Embedding class" design below: instance : EmbeddingLike (MyEmbedding A B) A B where injective' := MyEmbedding.injective' @[ext] theorem ext {f g : MyEmbedding A B} (h : ∀ x, f x = g x) : f = g := DFunLike.ext f g h /-- Copy of a `MyEmbedding` with a new `toFun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : MyEmbedding A B) (f' : A → B) (h : f' = ⇑f) : MyEmbedding A B := { toFun := f' injective' := h.symm ▸ f.injective' map_op' := h.symm ▸ f.map_op' } end MyEmbedding ``` This file will then provide a `CoeFun` instance and various extensionality and simp lemmas. ## Embedding classes extending `EmbeddingLike` The `EmbeddingLike` design provides further benefits if you put in a bit more work. The first step is to extend `EmbeddingLike` to create a class of those types satisfying the axioms of your new type of morphisms. Continuing the example above: ``` /-- `MyEmbeddingClass F A B` states that `F` is a type of `MyClass.op`-preserving embeddings. You should extend this class when you extend `MyEmbedding`. -/ class MyEmbeddingClass (F : Type*) (A B : outParam Type*) [MyClass A] [MyClass B] [FunLike F A B] extends EmbeddingLike F A B := (map_op : ∀ (f : F) (x y : A), f (MyClass.op x y) = MyClass.op (f x) (f y)) @[simp] lemma map_op {F A B : Type*} [MyClass A] [MyClass B] [FunLike F A B] [MyEmbeddingClass F A B] (f : F) (x y : A) : f (MyClass.op x y) = MyClass.op (f x) (f y) := MyEmbeddingClass.map_op _ _ _ namespace MyEmbedding variable {A B : Type*} [MyClass A] [MyClass B] -- You can replace `MyEmbedding.EmbeddingLike` with the below instance: instance : MyEmbeddingClass (MyEmbedding A B) A B where injective' := MyEmbedding.injective' map_op := MyEmbedding.map_op' end MyEmbedding ``` The second step is to add instances of your new `MyEmbeddingClass` for all types extending `MyEmbedding`. Typically, you can just declare a new class analogous to `MyEmbeddingClass`: ``` structure CoolerEmbedding (A B : Type*) [CoolClass A] [CoolClass B] extends MyEmbedding A B := (map_cool' : toFun CoolClass.cool = CoolClass.cool) class CoolerEmbeddingClass (F : Type*) (A B : outParam Type*) [CoolClass A] [CoolClass B] [FunLike F A B] extends MyEmbeddingClass F A B := (map_cool : ∀ (f : F), f CoolClass.cool = CoolClass.cool) @[simp] lemma map_cool {F A B : Type*} [CoolClass A] [CoolClass B] [FunLike F A B] [CoolerEmbeddingClass F A B] (f : F) : f CoolClass.cool = CoolClass.cool := CoolerEmbeddingClass.map_cool _ variable {A B : Type*} [CoolClass A] [CoolClass B] instance : FunLike (CoolerEmbedding A B) A B where coe f := f.toFun coe_injective' f g h := by cases f; cases g; congr; apply DFunLike.coe_injective; congr instance : CoolerEmbeddingClass (CoolerEmbedding A B) A B where injective' f := f.injective' map_op f := f.map_op' map_cool f := f.map_cool' -- [Insert `ext` and `copy` here] ``` Then any declaration taking a specific type of morphisms as parameter can instead take the class you just defined: ``` -- Compare with: lemma do_something (f : MyEmbedding A B) : sorry := sorry lemma do_something {F : Type*} [FunLike F A B] [MyEmbeddingClass F A B] (f : F) : sorry := sorry ``` This means anything set up for `MyEmbedding`s will automatically work for `CoolerEmbeddingClass`es, and defining `CoolerEmbeddingClass` only takes a constant amount of effort, instead of linearly increasing the work per `MyEmbedding`-related declaration. -/ /-- The class `EmbeddingLike F α β` expresses that terms of type `F` have an injective coercion to injective functions `α ↪ β`. -/ class EmbeddingLike (F : Sort*) (α β : outParam (Sort*)) [FunLike F α β] : Prop where /-- The coercion to functions must produce injective functions. -/ injective' : ∀ f : F, Function.Injective (DFunLike.coe f) namespace EmbeddingLike variable {F α β γ : Sort*} [FunLike F α β] [i : EmbeddingLike F α β] protected theorem injective (f : F) : Function.Injective f := injective' f @[simp] theorem apply_eq_iff_eq (f : F) {x y : α} : f x = f y ↔ x = y := (EmbeddingLike.injective f).eq_iff @[simp] theorem comp_injective {F : Sort*} [FunLike F β γ] [EmbeddingLike F β γ] (f : α → β) (e : F) : Function.Injective (e ∘ f) ↔ Function.Injective f := (EmbeddingLike.injective e).of_comp_iff f end EmbeddingLike
Data\FunLike\Equiv.lean
/- Copyright (c) 2021 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import Mathlib.Data.FunLike.Embedding /-! # Typeclass for a type `F` with an injective map to `A ≃ B` This typeclass is primarily for use by isomorphisms like `MonoidEquiv` and `LinearEquiv`. ## Basic usage of `EquivLike` A typical type of isomorphisms should be declared as: ``` structure MyIso (A B : Type*) [MyClass A] [MyClass B] extends Equiv A B := (map_op' : ∀ (x y : A), toFun (MyClass.op x y) = MyClass.op (toFun x) (toFun y)) namespace MyIso variable (A B : Type*) [MyClass A] [MyClass B] instance instEquivLike : EquivLike (MyIso A B) A B where coe f := f.toFun inv f := f.invFun left_inv f := f.left_inv right_inv f := f.right_inv coe_injective' f g h₁ h₂ := by cases f; cases g; congr; exact EquivLike.coe_injective' _ _ h₁ h₂ @[ext] theorem ext {f g : MyIso A B} (h : ∀ x, f x = g x) : f = g := DFunLike.ext f g h /-- Copy of a `MyIso` with a new `toFun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : MyIso A B) (f' : A → B) (f_inv : B → A) (h₁ : f' = f) (h₂ : f_inv = f.invFun) : MyIso A B where toFun := f' invFun := f_inv left_inv := h₁.symm ▸ h₂.symm ▸ f.left_inv right_inv := h₁.symm ▸ h₂.symm ▸ f.right_inv map_op' := h₁.symm ▸ f.map_op' end MyIso ``` This file will then provide a `CoeFun` instance and various extensionality and simp lemmas. ## Isomorphism classes extending `EquivLike` The `EquivLike` design provides further benefits if you put in a bit more work. The first step is to extend `EquivLike` to create a class of those types satisfying the axioms of your new type of isomorphisms. Continuing the example above: ``` /-- `MyIsoClass F A B` states that `F` is a type of `MyClass.op`-preserving morphisms. You should extend this class when you extend `MyIso`. -/ class MyIsoClass (F : Type*) (A B : outParam Type*) [MyClass A] [MyClass B] [EquivLike F A B] extends MyHomClass F A B namespace MyIso variable {A B : Type*} [MyClass A] [MyClass B] -- This goes after `MyIsoClass.instEquivLike`: instance : MyIsoClass (MyIso A B) A B where map_op := MyIso.map_op' -- [Insert `ext` and `copy` here] end MyIso ``` The second step is to add instances of your new `MyIsoClass` for all types extending `MyIso`. Typically, you can just declare a new class analogous to `MyIsoClass`: ``` structure CoolerIso (A B : Type*) [CoolClass A] [CoolClass B] extends MyIso A B := (map_cool' : toFun CoolClass.cool = CoolClass.cool) class CoolerIsoClass (F : Type*) (A B : outParam Type*) [CoolClass A] [CoolClass B] [EquivLike F A B] extends MyIsoClass F A B := (map_cool : ∀ (f : F), f CoolClass.cool = CoolClass.cool) @[simp] lemma map_cool {F A B : Type*} [CoolClass A] [CoolClass B] [EquivLike F A B] [CoolerIsoClass F A B] (f : F) : f CoolClass.cool = CoolClass.cool := CoolerIsoClass.map_cool _ namespace CoolerIso variable {A B : Type*} [CoolClass A] [CoolClass B] instance : EquivLike (CoolerIso A B) A B where coe f := f.toFun inv f := f.invFun left_inv f := f.left_inv right_inv f := f.right_inv coe_injective' f g h₁ h₂ := by cases f; cases g; congr; exact EquivLike.coe_injective' _ _ h₁ h₂ instance : CoolerIsoClass (CoolerIso A B) A B where map_op f := f.map_op' map_cool f := f.map_cool' -- [Insert `ext` and `copy` here] end CoolerIso ``` Then any declaration taking a specific type of morphisms as parameter can instead take the class you just defined: ``` -- Compare with: lemma do_something (f : MyIso A B) : sorry := sorry lemma do_something {F : Type*} [EquivLike F A B] [MyIsoClass F A B] (f : F) : sorry := sorry ``` This means anything set up for `MyIso`s will automatically work for `CoolerIsoClass`es, and defining `CoolerIsoClass` only takes a constant amount of effort, instead of linearly increasing the work per `MyIso`-related declaration. -/ /-- The class `EquivLike E α β` expresses that terms of type `E` have an injective coercion to bijections between `α` and `β`. Note that this does not directly extend `FunLike`, nor take `FunLike` as a parameter, so we can state `coe_injective'` in a nicer way. This typeclass is used in the definition of the isomorphism (or equivalence) typeclasses, such as `ZeroEquivClass`, `MulEquivClass`, `MonoidEquivClass`, .... -/ class EquivLike (E : Sort*) (α β : outParam (Sort*)) where /-- The coercion to a function in the forward direction. -/ coe : E → α → β /-- The coercion to a function in the backwards direction. -/ inv : E → β → α /-- The coercions are left inverses. -/ left_inv : ∀ e, Function.LeftInverse (inv e) (coe e) /-- The coercions are right inverses. -/ right_inv : ∀ e, Function.RightInverse (inv e) (coe e) /-- The two coercions to functions are jointly injective. -/ coe_injective' : ∀ e g, coe e = coe g → inv e = inv g → e = g -- This is mathematically equivalent to either of the coercions to functions being injective, but -- the `inv` hypothesis makes this easier to prove with `congr'` namespace EquivLike variable {E F α β γ : Sort*} [EquivLike E α β] [EquivLike F β γ] theorem inv_injective : Function.Injective (EquivLike.inv : E → β → α) := fun e g h ↦ coe_injective' e g ((right_inv e).eq_rightInverse (h.symm ▸ left_inv g)) h instance (priority := 100) toFunLike : FunLike E α β where coe := (coe : E → α → β) coe_injective' e g h := coe_injective' e g h ((left_inv e).eq_rightInverse (h.symm ▸ right_inv g)) instance (priority := 100) toEmbeddingLike : EmbeddingLike E α β where injective' e := (left_inv e).injective protected theorem injective (e : E) : Function.Injective e := EmbeddingLike.injective e protected theorem surjective (e : E) : Function.Surjective e := (right_inv e).surjective protected theorem bijective (e : E) : Function.Bijective (e : α → β) := ⟨EquivLike.injective e, EquivLike.surjective e⟩ theorem apply_eq_iff_eq (f : E) {x y : α} : f x = f y ↔ x = y := EmbeddingLike.apply_eq_iff_eq f @[simp] theorem injective_comp (e : E) (f : β → γ) : Function.Injective (f ∘ e) ↔ Function.Injective f := Function.Injective.of_comp_iff' f (EquivLike.bijective e) @[simp] theorem surjective_comp (e : E) (f : β → γ) : Function.Surjective (f ∘ e) ↔ Function.Surjective f := (EquivLike.surjective e).of_comp_iff f @[simp] theorem bijective_comp (e : E) (f : β → γ) : Function.Bijective (f ∘ e) ↔ Function.Bijective f := (EquivLike.bijective e).of_comp_iff f /-- This lemma is only supposed to be used in the generic context, when working with instances of classes extending `EquivLike`. For concrete isomorphism types such as `Equiv`, you should use `Equiv.symm_apply_apply` or its equivalent. TODO: define a generic form of `Equiv.symm`. -/ @[simp] theorem inv_apply_apply (e : E) (a : α) : EquivLike.inv e (e a) = a := left_inv _ _ /-- This lemma is only supposed to be used in the generic context, when working with instances of classes extending `EquivLike`. For concrete isomorphism types such as `Equiv`, you should use `Equiv.apply_symm_apply` or its equivalent. TODO: define a generic form of `Equiv.symm`. -/ @[simp] theorem apply_inv_apply (e : E) (b : β) : e (EquivLike.inv e b) = b := right_inv _ _ theorem comp_injective (f : α → β) (e : F) : Function.Injective (e ∘ f) ↔ Function.Injective f := EmbeddingLike.comp_injective f e @[simp] theorem comp_surjective (f : α → β) (e : F) : Function.Surjective (e ∘ f) ↔ Function.Surjective f := Function.Surjective.of_comp_iff' (EquivLike.bijective e) f @[simp] theorem comp_bijective (f : α → β) (e : F) : Function.Bijective (e ∘ f) ↔ Function.Bijective f := (EquivLike.bijective e).of_comp_iff' f /-- This is not an instance to avoid slowing down every single `Subsingleton` typeclass search. -/ lemma subsingleton_dom [Subsingleton β] : Subsingleton F := ⟨fun f g ↦ DFunLike.ext f g fun _ ↦ (right_inv f).injective <| Subsingleton.elim _ _⟩ end EquivLike
Data\FunLike\Fintype.lean
/- Copyright (c) 2022 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import Mathlib.Data.Finite.Basic import Mathlib.Data.Fintype.Basic import Mathlib.Data.FunLike.Basic /-! # Finiteness of `DFunLike` types We show a type `F` with a `DFunLike F α β` is finite if both `α` and `β` are finite. This corresponds to the following two pairs of declarations: * `DFunLike.fintype` is a definition stating all `DFunLike`s are finite if their domain and codomain are. * `DFunLike.finite` is a lemma stating all `DFunLike`s are finite if their domain and codomain are. * `FunLike.fintype` is a non-dependent version of `DFunLike.fintype` and * `FunLike.finite` is a non-dependent version of `DFunLike.finite`, because dependent instances are harder to infer. You can use these to produce instances for specific `DFunLike` types. (Although there might be options for `Fintype` instances with better definitional behaviour.) They can't be instances themselves since they can cause loops. -/ -- Porting note: `Type` is a reserved word, switched to `Type'` section Type' variable (F G : Type*) {α γ : Type*} {β : α → Type*} [DFunLike F α β] [FunLike G α γ] /-- All `DFunLike`s are finite if their domain and codomain are. This is not an instance because specific `DFunLike` types might have a better-suited definition. See also `DFunLike.finite`. -/ noncomputable def DFunLike.fintype [DecidableEq α] [Fintype α] [∀ i, Fintype (β i)] : Fintype F := Fintype.ofInjective _ DFunLike.coe_injective /-- All `FunLike`s are finite if their domain and codomain are. Non-dependent version of `DFunLike.fintype` that might be easier to infer. This is not an instance because specific `FunLike` types might have a better-suited definition. -/ noncomputable def FunLike.fintype [DecidableEq α] [Fintype α] [Fintype γ] : Fintype G := DFunLike.fintype G end Type' -- Porting note: `Sort` is a reserved word, switched to `Sort'` section Sort' variable (F G : Sort*) {α γ : Sort*} {β : α → Sort*} [DFunLike F α β] [FunLike G α γ] /-- All `DFunLike`s are finite if their domain and codomain are. Can't be an instance because it can cause infinite loops. -/ theorem DFunLike.finite [Finite α] [∀ i, Finite (β i)] : Finite F := Finite.of_injective _ DFunLike.coe_injective /-- All `FunLike`s are finite if their domain and codomain are. Non-dependent version of `DFunLike.finite` that might be easier to infer. Can't be an instance because it can cause infinite loops. -/ theorem FunLike.finite [Finite α] [Finite γ] : Finite G := DFunLike.finite G end Sort' -- See note [lower instance priority] instance (priority := 100) FunLike.toDecidableEq {F α β : Type*} [DecidableEq β] [Fintype α] [FunLike F α β] : DecidableEq F := fun a b ↦ decidable_of_iff ((a : α → β) = b) DFunLike.coe_injective.eq_iff
Data\Int\AbsoluteValue.lean
/- Copyright (c) 2021 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import Mathlib.Algebra.GroupWithZero.Action.Units import Mathlib.Algebra.Module.Defs import Mathlib.Algebra.Order.AbsoluteValue import Mathlib.Data.Int.Cast.Lemmas /-! # Absolute values and the integers This file contains some results on absolute values applied to integers. ## Main results * `AbsoluteValue.map_units_int`: an absolute value sends all units of `ℤ` to `1` * `Int.natAbsHom`: `Int.natAbs` bundled as a `MonoidWithZeroHom` -/ variable {R S : Type*} [Ring R] [LinearOrderedCommRing S] @[simp] theorem AbsoluteValue.map_units_int (abv : AbsoluteValue ℤ S) (x : ℤˣ) : abv x = 1 := by rcases Int.units_eq_one_or x with (rfl | rfl) <;> simp @[simp] theorem AbsoluteValue.map_units_intCast [Nontrivial R] (abv : AbsoluteValue R S) (x : ℤˣ) : abv ((x : ℤ) : R) = 1 := by rcases Int.units_eq_one_or x with (rfl | rfl) <;> simp @[deprecated (since := "2024-04-17")] alias AbsoluteValue.map_units_int_cast := AbsoluteValue.map_units_intCast @[simp] theorem AbsoluteValue.map_units_int_smul (abv : AbsoluteValue R S) (x : ℤˣ) (y : R) : abv (x • y) = abv y := by rcases Int.units_eq_one_or x with (rfl | rfl) <;> simp /-- `Int.natAbs` as a bundled monoid with zero hom. -/ @[simps] def Int.natAbsHom : ℤ →*₀ ℕ where toFun := Int.natAbs map_mul' := Int.natAbs_mul map_one' := Int.natAbs_one map_zero' := Int.natAbs_zero
Data\Int\Align.lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad -/ /-! # Align statements for results about the integers -/
Data\Int\Associated.lean
/- Copyright (c) 2022 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import Mathlib.Algebra.Associated.Basic import Mathlib.Algebra.Ring.Int /-! # Associated elements and the integers This file contains some results on equality up to units in the integers. ## Main results * `Int.natAbs_eq_iff_associated`: the absolute value is equal iff integers are associated -/ theorem Int.natAbs_eq_iff_associated {a b : ℤ} : a.natAbs = b.natAbs ↔ Associated a b := by refine Int.natAbs_eq_natAbs_iff.trans ?_ constructor · rintro (rfl | rfl) · rfl · exact ⟨-1, by simp⟩ · rintro ⟨u, rfl⟩ obtain rfl | rfl := Int.units_eq_one_or u · exact Or.inl (by simp) · exact Or.inr (by simp)
Data\Int\Bitwise.lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad -/ import Mathlib.Algebra.Ring.Int import Mathlib.Data.Nat.Bitwise import Mathlib.Data.Nat.Size /-! # Bitwise operations on integers Possibly only of archaeological significance. ## Recursors * `Int.bitCasesOn`: Parity disjunction. Something is true/defined on `ℤ` if it's true/defined for even and for odd values. -/ namespace Int /-- `div2 n = n/2`-/ def div2 : ℤ → ℤ | (n : ℕ) => n.div2 | -[n +1] => negSucc n.div2 /-- `bodd n` returns `true` if `n` is odd-/ def bodd : ℤ → Bool | (n : ℕ) => n.bodd | -[n +1] => not (n.bodd) /-- `bit b` appends the digit `b` to the binary representation of its integer input. -/ def bit (b : Bool) : ℤ → ℤ := cond b (2 * · + 1) (2 * ·) /-- `testBit m n` returns whether the `(n+1)ˢᵗ` least significant bit is `1` or `0`-/ def testBit : ℤ → ℕ → Bool | (m : ℕ), n => Nat.testBit m n | -[m +1], n => !(Nat.testBit m n) /-- `Int.natBitwise` is an auxiliary definition for `Int.bitwise`. -/ def natBitwise (f : Bool → Bool → Bool) (m n : ℕ) : ℤ := cond (f false false) -[ Nat.bitwise (fun x y => not (f x y)) m n +1] (Nat.bitwise f m n) /-- `Int.bitwise` applies the function `f` to pairs of bits in the same position in the binary representations of its inputs. -/ def bitwise (f : Bool → Bool → Bool) : ℤ → ℤ → ℤ | (m : ℕ), (n : ℕ) => natBitwise f m n | (m : ℕ), -[n +1] => natBitwise (fun x y => f x (not y)) m n | -[m +1], (n : ℕ) => natBitwise (fun x y => f (not x) y) m n | -[m +1], -[n +1] => natBitwise (fun x y => f (not x) (not y)) m n /-- `lnot` flips all the bits in the binary representation of its input -/ def lnot : ℤ → ℤ | (m : ℕ) => -[m +1] | -[m +1] => m /-- `lor` takes two integers and returns their bitwise `or`-/ def lor : ℤ → ℤ → ℤ | (m : ℕ), (n : ℕ) => m ||| n | (m : ℕ), -[n +1] => -[Nat.ldiff n m +1] | -[m +1], (n : ℕ) => -[Nat.ldiff m n +1] | -[m +1], -[n +1] => -[m &&& n +1] /-- `land` takes two integers and returns their bitwise `and`-/ def land : ℤ → ℤ → ℤ | (m : ℕ), (n : ℕ) => m &&& n | (m : ℕ), -[n +1] => Nat.ldiff m n | -[m +1], (n : ℕ) => Nat.ldiff n m | -[m +1], -[n +1] => -[m ||| n +1] -- Porting note: I don't know why `Nat.ldiff` got the prime, but I'm matching this change here /-- `ldiff a b` performs bitwise set difference. For each corresponding pair of bits taken as booleans, say `aᵢ` and `bᵢ`, it applies the boolean operation `aᵢ ∧ bᵢ` to obtain the `iᵗʰ` bit of the result. -/ def ldiff : ℤ → ℤ → ℤ | (m : ℕ), (n : ℕ) => Nat.ldiff m n | (m : ℕ), -[n +1] => m &&& n | -[m +1], (n : ℕ) => -[m ||| n +1] | -[m +1], -[n +1] => Nat.ldiff n m -- Porting note: I don't know why `Nat.xor'` got the prime, but I'm matching this change here /-- `xor` computes the bitwise `xor` of two natural numbers-/ protected def xor : ℤ → ℤ → ℤ | (m : ℕ), (n : ℕ) => (m ^^^ n) | (m : ℕ), -[n +1] => -[(m ^^^ n) +1] | -[m +1], (n : ℕ) => -[(m ^^^ n) +1] | -[m +1], -[n +1] => (m ^^^ n) /-- `m <<< n` produces an integer whose binary representation is obtained by left-shifting the binary representation of `m` by `n` places -/ instance : ShiftLeft ℤ where shiftLeft | (m : ℕ), (n : ℕ) => Nat.shiftLeft' false m n | (m : ℕ), -[n +1] => m >>> (Nat.succ n) | -[m +1], (n : ℕ) => -[Nat.shiftLeft' true m n +1] | -[m +1], -[n +1] => -[m >>> (Nat.succ n) +1] /-- `m >>> n` produces an integer whose binary representation is obtained by right-shifting the binary representation of `m` by `n` places -/ instance : ShiftRight ℤ where shiftRight m n := m <<< (-n) /-! ### bitwise ops -/ @[simp] theorem bodd_zero : bodd 0 = false := rfl @[simp] theorem bodd_one : bodd 1 = true := rfl theorem bodd_two : bodd 2 = false := rfl @[simp, norm_cast] theorem bodd_coe (n : ℕ) : Int.bodd n = Nat.bodd n := rfl @[simp] theorem bodd_subNatNat (m n : ℕ) : bodd (subNatNat m n) = xor m.bodd n.bodd := by apply subNatNat_elim m n fun m n i => bodd i = xor m.bodd n.bodd <;> intros i j <;> simp only [Int.bodd, Int.bodd_coe, Nat.bodd_add] <;> cases Nat.bodd i <;> simp @[simp] theorem bodd_negOfNat (n : ℕ) : bodd (negOfNat n) = n.bodd := by cases n <;> simp (config := {decide := true}) rfl @[simp] theorem bodd_neg (n : ℤ) : bodd (-n) = bodd n := by cases n with | ofNat => rw [← negOfNat_eq, bodd_negOfNat] simp | negSucc n => rw [neg_negSucc, bodd_coe, Nat.bodd_succ] change (!Nat.bodd n) = !(bodd n) rw [bodd_coe] -- Porting note: Heavily refactored proof, used to work all with `simp`: -- `cases n <;> simp [Neg.neg, Int.natCast_eq_ofNat, Int.neg, bodd, -of_nat_eq_coe]` @[simp] theorem bodd_add (m n : ℤ) : bodd (m + n) = xor (bodd m) (bodd n) := by cases' m with m m <;> cases' n with n n <;> simp only [ofNat_eq_coe, ofNat_add_negSucc, negSucc_add_ofNat, negSucc_add_negSucc, bodd_subNatNat] <;> simp only [negSucc_coe, bodd_neg, bodd_coe, ← Nat.bodd_add, Bool.xor_comm, ← Nat.cast_add] rw [← Nat.succ_add, add_assoc] -- Porting note: Heavily refactored proof, used to work all with `simp`: -- `by cases m with m m; cases n with n n; unfold has_add.add;` -- `simp [int.add, -of_nat_eq_coe, bool.xor_comm]` @[simp] theorem bodd_mul (m n : ℤ) : bodd (m * n) = (bodd m && bodd n) := by cases' m with m m <;> cases' n with n n <;> simp only [ofNat_eq_coe, ofNat_mul_negSucc, negSucc_mul_ofNat, ofNat_mul_ofNat, negSucc_mul_negSucc] <;> simp only [negSucc_coe, bodd_neg, bodd_coe, ← Nat.bodd_mul] -- Porting note: Heavily refactored proof, used to be: -- `by cases m with m m; cases n with n n;` -- `simp [← int.mul_def, int.mul, -of_nat_eq_coe, bool.xor_comm]` theorem bodd_add_div2 : ∀ n, cond (bodd n) 1 0 + 2 * div2 n = n | (n : ℕ) => by rw [show (cond (bodd n) 1 0 : ℤ) = (cond (bodd n) 1 0 : ℕ) by cases bodd n <;> rfl] exact congr_arg ofNat n.bodd_add_div2 | -[n+1] => by refine Eq.trans ?_ (congr_arg negSucc n.bodd_add_div2) dsimp [bodd]; cases Nat.bodd n <;> dsimp [cond, not, div2, Int.mul] · change -[2 * Nat.div2 n+1] = _ rw [zero_add] · rw [zero_add, add_comm] rfl theorem div2_val : ∀ n, div2 n = n / 2 | (n : ℕ) => congr_arg ofNat n.div2_val | -[n+1] => congr_arg negSucc n.div2_val theorem bit_val (b n) : bit b n = 2 * n + cond b 1 0 := by cases b · apply (add_zero _).symm · rfl theorem bit_decomp (n : ℤ) : bit (bodd n) (div2 n) = n := (bit_val _ _).trans <| (add_comm _ _).trans <| bodd_add_div2 _ /-- Defines a function from `ℤ` conditionally, if it is defined for odd and even integers separately using `bit`. -/ def bitCasesOn.{u} {C : ℤ → Sort u} (n) (h : ∀ b n, C (bit b n)) : C n := by rw [← bit_decomp n] apply h @[simp] theorem bit_zero : bit false 0 = 0 := rfl @[simp] theorem bit_coe_nat (b) (n : ℕ) : bit b n = Nat.bit b n := by rw [bit_val, Nat.bit_val] cases b <;> rfl @[simp] theorem bit_negSucc (b) (n : ℕ) : bit b -[n+1] = -[Nat.bit (not b) n+1] := by rw [bit_val, Nat.bit_val] cases b <;> rfl @[simp] theorem bodd_bit (b n) : bodd (bit b n) = b := by rw [bit_val] cases b <;> cases bodd n <;> simp [(show bodd 2 = false by rfl)] @[simp] theorem testBit_bit_zero (b) : ∀ n, testBit (bit b n) 0 = b | (n : ℕ) => by rw [bit_coe_nat]; apply Nat.testBit_bit_zero | -[n+1] => by rw [bit_negSucc]; dsimp [testBit]; rw [Nat.testBit_bit_zero]; clear testBit_bit_zero cases b <;> rfl @[simp] theorem testBit_bit_succ (m b) : ∀ n, testBit (bit b n) (Nat.succ m) = testBit n m | (n : ℕ) => by rw [bit_coe_nat]; apply Nat.testBit_bit_succ | -[n+1] => by dsimp only [testBit] simp only [bit_negSucc] cases b <;> simp only [Bool.not_false, Bool.not_true, Nat.testBit_bit_succ] -- Porting note (#11215): TODO -- private unsafe def bitwise_tac : tactic Unit := -- sorry -- Porting note: Was `bitwise_tac` in mathlib theorem bitwise_or : bitwise or = lor := by funext m n cases' m with m m <;> cases' n with n n <;> try {rfl} <;> simp only [bitwise, natBitwise, Bool.not_false, Bool.or_true, cond_true, lor, Nat.ldiff, negSucc.injEq, Bool.true_or, Nat.land] · rw [Nat.bitwise_swap, Function.swap] congr funext x y cases x <;> cases y <;> rfl · congr funext x y cases x <;> cases y <;> rfl · congr funext x y cases x <;> cases y <;> rfl -- Porting note: Was `bitwise_tac` in mathlib theorem bitwise_and : bitwise and = land := by funext m n cases' m with m m <;> cases' n with n n <;> try {rfl} <;> simp only [bitwise, natBitwise, Bool.not_false, Bool.or_true, cond_false, cond_true, lor, Nat.ldiff, Bool.and_true, negSucc.injEq, Bool.and_false, Nat.land] · rw [Nat.bitwise_swap, Function.swap] congr funext x y cases x <;> cases y <;> rfl · congr funext x y cases x <;> cases y <;> rfl -- Porting note: Was `bitwise_tac` in mathlib theorem bitwise_diff : (bitwise fun a b => a && not b) = ldiff := by funext m n cases' m with m m <;> cases' n with n n <;> try {rfl} <;> simp only [bitwise, natBitwise, Bool.not_false, Bool.or_true, cond_false, cond_true, lor, Nat.ldiff, Bool.and_true, negSucc.injEq, Bool.and_false, Nat.land, Bool.not_true, ldiff, Nat.lor] · congr funext x y cases x <;> cases y <;> rfl · congr funext x y cases x <;> cases y <;> rfl · rw [Nat.bitwise_swap, Function.swap] congr funext x y cases x <;> cases y <;> rfl -- Porting note: Was `bitwise_tac` in mathlib theorem bitwise_xor : bitwise xor = Int.xor := by funext m n cases' m with m m <;> cases' n with n n <;> try {rfl} <;> simp only [bitwise, natBitwise, Bool.not_false, Bool.or_true, Bool.bne_eq_xor, cond_false, cond_true, lor, Nat.ldiff, Bool.and_true, negSucc.injEq, Bool.false_xor, Bool.true_xor, Bool.and_false, Nat.land, Bool.not_true, ldiff, HOr.hOr, OrOp.or, Nat.lor, Int.xor, HXor.hXor, Xor.xor, Nat.xor] · congr funext x y cases x <;> cases y <;> rfl · congr funext x y cases x <;> cases y <;> rfl · congr funext x y cases x <;> cases y <;> rfl @[simp] theorem bitwise_bit (f : Bool → Bool → Bool) (a m b n) : bitwise f (bit a m) (bit b n) = bit (f a b) (bitwise f m n) := by cases' m with m m <;> cases' n with n n <;> simp [bitwise, ofNat_eq_coe, bit_coe_nat, natBitwise, Bool.not_false, Bool.not_eq_false', bit_negSucc] · by_cases h : f false false <;> simp (config := {decide := true}) [h] · by_cases h : f false true <;> simp (config := {decide := true}) [h] · by_cases h : f true false <;> simp (config := {decide := true}) [h] · by_cases h : f true true <;> simp (config := {decide := true}) [h] @[simp] theorem lor_bit (a m b n) : lor (bit a m) (bit b n) = bit (a || b) (lor m n) := by rw [← bitwise_or, bitwise_bit] @[simp] theorem land_bit (a m b n) : land (bit a m) (bit b n) = bit (a && b) (land m n) := by rw [← bitwise_and, bitwise_bit] @[simp] theorem ldiff_bit (a m b n) : ldiff (bit a m) (bit b n) = bit (a && not b) (ldiff m n) := by rw [← bitwise_diff, bitwise_bit] @[simp] theorem lxor_bit (a m b n) : Int.xor (bit a m) (bit b n) = bit (xor a b) (Int.xor m n) := by rw [← bitwise_xor, bitwise_bit] @[simp] theorem lnot_bit (b) : ∀ n, lnot (bit b n) = bit (not b) (lnot n) | (n : ℕ) => by simp [lnot] | -[n+1] => by simp [lnot] @[simp] theorem testBit_bitwise (f : Bool → Bool → Bool) (m n k) : testBit (bitwise f m n) k = f (testBit m k) (testBit n k) := by cases m <;> cases n <;> simp only [testBit, bitwise, natBitwise] · by_cases h : f false false <;> simp [h] · by_cases h : f false true <;> simp [h] · by_cases h : f true false <;> simp [h] · by_cases h : f true true <;> simp [h] @[simp] theorem testBit_lor (m n k) : testBit (lor m n) k = (testBit m k || testBit n k) := by rw [← bitwise_or, testBit_bitwise] @[simp] theorem testBit_land (m n k) : testBit (land m n) k = (testBit m k && testBit n k) := by rw [← bitwise_and, testBit_bitwise] @[simp] theorem testBit_ldiff (m n k) : testBit (ldiff m n) k = (testBit m k && not (testBit n k)) := by rw [← bitwise_diff, testBit_bitwise] @[simp] theorem testBit_lxor (m n k) : testBit (Int.xor m n) k = xor (testBit m k) (testBit n k) := by rw [← bitwise_xor, testBit_bitwise] @[simp] theorem testBit_lnot : ∀ n k, testBit (lnot n) k = not (testBit n k) | (n : ℕ), k => by simp [lnot, testBit] | -[n+1], k => by simp [lnot, testBit] @[simp] theorem shiftLeft_neg (m n : ℤ) : m <<< (-n) = m >>> n := rfl @[simp] theorem shiftRight_neg (m n : ℤ) : m >>> (-n) = m <<< n := by rw [← shiftLeft_neg, neg_neg] -- Porting note: what's the correct new name? @[simp] theorem shiftLeft_coe_nat (m n : ℕ) : (m : ℤ) <<< (n : ℤ) = ↑(m <<< n) := by unfold_projs; simp -- Porting note: what's the correct new name? @[simp] theorem shiftRight_coe_nat (m n : ℕ) : (m : ℤ) >>> (n : ℤ) = m >>> n := by cases n <;> rfl @[simp] theorem shiftLeft_negSucc (m n : ℕ) : -[m+1] <<< (n : ℤ) = -[Nat.shiftLeft' true m n+1] := rfl @[simp] theorem shiftRight_negSucc (m n : ℕ) : -[m+1] >>> (n : ℤ) = -[m >>> n+1] := by cases n <;> rfl /-- Compare with `Int.shiftRight_add`, which doesn't have the coercions `ℕ → ℤ`. -/ theorem shiftRight_add' : ∀ (m : ℤ) (n k : ℕ), m >>> (n + k : ℤ) = (m >>> (n : ℤ)) >>> (k : ℤ) | (m : ℕ), n, k => by rw [shiftRight_coe_nat, shiftRight_coe_nat, ← Int.ofNat_add, shiftRight_coe_nat, Nat.shiftRight_add] | -[m+1], n, k => by rw [shiftRight_negSucc, shiftRight_negSucc, ← Int.ofNat_add, shiftRight_negSucc, Nat.shiftRight_add] /-! ### bitwise ops -/ attribute [local simp] Int.zero_div theorem shiftLeft_add : ∀ (m : ℤ) (n : ℕ) (k : ℤ), m <<< (n + k) = (m <<< (n : ℤ)) <<< k | (m : ℕ), n, (k : ℕ) => congr_arg ofNat (by simp [Nat.shiftLeft_eq, Nat.pow_add, mul_assoc]) | -[m+1], n, (k : ℕ) => congr_arg negSucc (Nat.shiftLeft'_add _ _ _ _) | (m : ℕ), n, -[k+1] => subNatNat_elim n k.succ (fun n k i => (↑m) <<< i = (Nat.shiftLeft' false m n) >>> k) (fun (i n : ℕ) => by dsimp; simp [← Nat.shiftLeft_sub _ , Nat.add_sub_cancel_left]) fun i n => by dsimp simp_rw [negSucc_eq, shiftLeft_neg, Nat.shiftLeft'_false, Nat.shiftRight_add, ← Nat.shiftLeft_sub _ le_rfl, Nat.sub_self, Nat.shiftLeft_zero, ← shiftRight_coe_nat, ← shiftRight_add', Nat.cast_one] | -[m+1], n, -[k+1] => subNatNat_elim n k.succ (fun n k i => -[m+1] <<< i = -[(Nat.shiftLeft' true m n) >>> k+1]) (fun i n => congr_arg negSucc <| by rw [← Nat.shiftLeft'_sub, Nat.add_sub_cancel_left]; apply Nat.le_add_right) fun i n => congr_arg negSucc <| by rw [add_assoc, Nat.shiftRight_add, ← Nat.shiftLeft'_sub _ _ le_rfl, Nat.sub_self, Nat.shiftLeft'] theorem shiftLeft_sub (m : ℤ) (n : ℕ) (k : ℤ) : m <<< (n - k) = (m <<< (n : ℤ)) >>> k := shiftLeft_add _ _ _ theorem shiftLeft_eq_mul_pow : ∀ (m : ℤ) (n : ℕ), m <<< (n : ℤ) = m * (2 ^ n : ℕ) | (m : ℕ), _ => congr_arg ((↑) : ℕ → ℤ) (by simp [Nat.shiftLeft_eq]) | -[_+1], _ => @congr_arg ℕ ℤ _ _ (fun i => -i) (Nat.shiftLeft'_tt_eq_mul_pow _ _) theorem one_shiftLeft (n : ℕ) : 1 <<< (n : ℤ) = (2 ^ n : ℕ) := congr_arg ((↑) : ℕ → ℤ) (by simp [Nat.shiftLeft_eq]) @[simp] theorem zero_shiftLeft : ∀ n : ℤ, 0 <<< n = 0 | (n : ℕ) => congr_arg ((↑) : ℕ → ℤ) (by simp) | -[_+1] => congr_arg ((↑) : ℕ → ℤ) (by simp) /-- Compare with `Int.zero_shiftRight`, which has `n : ℕ`. -/ @[simp] theorem zero_shiftRight' (n : ℤ) : 0 >>> n = 0 := zero_shiftLeft _ end Int
Data\Int\CardIntervalMod.lean
/- Copyright (c) 2024 Jeremy Tan. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Tan -/ import Mathlib.Data.Int.Interval import Mathlib.Data.Int.ModEq import Mathlib.Data.Nat.Count import Mathlib.Data.Rat.Floor import Mathlib.Order.Interval.Finset.Nat /-! # Counting elements in an interval with given residue The theorems in this file generalise `Nat.card_multiples` in `Mathlib.Data.Nat.Factorization.Basic` to all integer intervals and any fixed residue (not just zero, which reduces to the multiples). Theorems are given for `Ico` and `Ioc` intervals. -/ open Finset Int namespace Int variable (a b : ℤ) {r : ℤ} lemma Ico_filter_modEq_eq (v : ℤ) : (Ico a b).filter (· ≡ v [ZMOD r]) = ((Ico (a - v) (b - v)).filter (r ∣ ·)).map ⟨(· + v), add_left_injective v⟩ := by ext x simp_rw [mem_map, mem_filter, mem_Ico, Function.Embedding.coeFn_mk, ← eq_sub_iff_add_eq, exists_eq_right, modEq_comm, modEq_iff_dvd, sub_lt_sub_iff_right, sub_le_sub_iff_right] lemma Ioc_filter_modEq_eq (v : ℤ) : (Ioc a b).filter (· ≡ v [ZMOD r]) = ((Ioc (a - v) (b - v)).filter (r ∣ ·)).map ⟨(· + v), add_left_injective v⟩ := by ext x simp_rw [mem_map, mem_filter, mem_Ioc, Function.Embedding.coeFn_mk, ← eq_sub_iff_add_eq, exists_eq_right, modEq_comm, modEq_iff_dvd, sub_lt_sub_iff_right, sub_le_sub_iff_right] variable (hr : 0 < r) lemma Ico_filter_dvd_eq : (Ico a b).filter (r ∣ ·) = (Ico ⌈a / (r : ℚ)⌉ ⌈b / (r : ℚ)⌉).map ⟨(· * r), mul_left_injective₀ hr.ne'⟩ := by ext x simp only [mem_map, mem_filter, mem_Ico, ceil_le, lt_ceil, div_le_iff, lt_div_iff, dvd_iff_exists_eq_mul_left, cast_pos.2 hr, ← cast_mul, cast_lt, cast_le] aesop lemma Ioc_filter_dvd_eq : (Ioc a b).filter (r ∣ ·) = (Ioc ⌊a / (r : ℚ)⌋ ⌊b / (r : ℚ)⌋).map ⟨(· * r), mul_left_injective₀ hr.ne'⟩ := by ext x simp only [mem_map, mem_filter, mem_Ioc, floor_lt, le_floor, div_lt_iff, le_div_iff, dvd_iff_exists_eq_mul_left, cast_pos.2 hr, ← cast_mul, cast_lt, cast_le] aesop /-- There are `⌈b / r⌉ - ⌈a / r⌉` multiples of `r` in `[a, b)`, if `a ≤ b`. -/ theorem Ico_filter_dvd_card : ((Ico a b).filter (r ∣ ·)).card = max (⌈b / (r : ℚ)⌉ - ⌈a / (r : ℚ)⌉) 0 := by rw [Ico_filter_dvd_eq _ _ hr, card_map, card_Ico, toNat_eq_max] /-- There are `⌊b / r⌋ - ⌊a / r⌋` multiples of `r` in `(a, b]`, if `a ≤ b`. -/ theorem Ioc_filter_dvd_card : ((Ioc a b).filter (r ∣ ·)).card = max (⌊b / (r : ℚ)⌋ - ⌊a / (r : ℚ)⌋) 0 := by rw [Ioc_filter_dvd_eq _ _ hr, card_map, card_Ioc, toNat_eq_max] /-- There are `⌈(b - v) / r⌉ - ⌈(a - v) / r⌉` numbers congruent to `v` mod `r` in `[a, b)`, if `a ≤ b`. -/ theorem Ico_filter_modEq_card (v : ℤ) : ((Ico a b).filter (· ≡ v [ZMOD r])).card = max (⌈(b - v) / (r : ℚ)⌉ - ⌈(a - v) / (r : ℚ)⌉) 0 := by simp [Ico_filter_modEq_eq, Ico_filter_dvd_eq, toNat_eq_max, hr] /-- There are `⌊(b - v) / r⌋ - ⌊(a - v) / r⌋` numbers congruent to `v` mod `r` in `(a, b]`, if `a ≤ b`. -/ theorem Ioc_filter_modEq_card (v : ℤ) : ((Ioc a b).filter (· ≡ v [ZMOD r])).card = max (⌊(b - v) / (r : ℚ)⌋ - ⌊(a - v) / (r : ℚ)⌋) 0 := by simp [Ioc_filter_modEq_eq, Ioc_filter_dvd_eq, toNat_eq_max, hr] end Int namespace Nat variable (a b : ℕ) {r : ℕ} lemma Ico_filter_modEq_cast {v : ℕ} : ((Ico a b).filter (· ≡ v [MOD r])).map castEmbedding = (Ico (a : ℤ) (b : ℤ)).filter (· ≡ v [ZMOD r]) := by ext x simp only [mem_map, mem_filter, mem_Ico, castEmbedding_apply] constructor · simp_rw [forall_exists_index, ← natCast_modEq_iff]; intro y ⟨h, c⟩; subst c; exact_mod_cast h · intro h; lift x to ℕ using (by linarith); exact ⟨x, by simp_all [natCast_modEq_iff]⟩ lemma Ioc_filter_modEq_cast {v : ℕ} : ((Ioc a b).filter (· ≡ v [MOD r])).map castEmbedding = (Ioc (a : ℤ) (b : ℤ)).filter (· ≡ v [ZMOD r]) := by ext x simp only [mem_map, mem_filter, mem_Ioc, castEmbedding_apply] constructor · simp_rw [forall_exists_index, ← natCast_modEq_iff]; intro y ⟨h, c⟩; subst c; exact_mod_cast h · intro h; lift x to ℕ using (by linarith); exact ⟨x, by simp_all [natCast_modEq_iff]⟩ variable (hr : 0 < r) /-- There are `⌈(b - v) / r⌉ - ⌈(a - v) / r⌉` numbers congruent to `v` mod `r` in `[a, b)`, if `a ≤ b`. `Nat` version of `Int.Ico_filter_modEq_card`. -/ theorem Ico_filter_modEq_card (v : ℕ) : ((Ico a b).filter (· ≡ v [MOD r])).card = max (⌈(b - v) / (r : ℚ)⌉ - ⌈(a - v) / (r : ℚ)⌉) 0 := by simp_rw [← Ico_filter_modEq_cast _ _ ▸ card_map _, Int.Ico_filter_modEq_card _ _ (cast_lt.mpr hr), Int.cast_natCast] /-- There are `⌊(b - v) / r⌋ - ⌊(a - v) / r⌋` numbers congruent to `v` mod `r` in `(a, b]`, if `a ≤ b`. `Nat` version of `Int.Ioc_filter_modEq_card`. -/ theorem Ioc_filter_modEq_card (v : ℕ) : ((Ioc a b).filter (· ≡ v [MOD r])).card = max (⌊(b - v) / (r : ℚ)⌋ - ⌊(a - v) / (r : ℚ)⌋) 0 := by simp_rw [← Ioc_filter_modEq_cast _ _ ▸ card_map _, Int.Ioc_filter_modEq_card _ _ (cast_lt.mpr hr), Int.cast_natCast] /-- There are `⌈(b - v % r) / r⌉` numbers in `[0, b)` congruent to `v` mod `r`. -/ theorem count_modEq_card_eq_ceil (v : ℕ) : b.count (· ≡ v [MOD r]) = ⌈(b - (v % r : ℕ)) / (r : ℚ)⌉ := by have hr' : 0 < (r : ℚ) := by positivity rw [count_eq_card_filter_range, ← Ico_zero_eq_range, Ico_filter_modEq_card _ _ hr, max_eq_left (sub_nonneg.mpr <| by gcongr <;> positivity)] conv_lhs => rw [← div_add_mod v r, cast_add, cast_mul, add_comm] tactic => simp_rw [← sub_sub, sub_div (_ - _), mul_div_cancel_left₀ _ hr'.ne', ceil_sub_nat] rw [sub_sub_sub_cancel_right, cast_zero, zero_sub] rw [sub_eq_self, ceil_eq_zero_iff, Set.mem_Ioc, div_le_iff hr', lt_div_iff hr', neg_one_mul, zero_mul, neg_lt_neg_iff, cast_lt] exact ⟨mod_lt _ hr, by simp⟩ /-- There are `b / r + [v % r < b % r]` numbers in `[0, b)` congruent to `v` mod `r`, where `[·]` is the Iverson bracket. -/ theorem count_modEq_card (v : ℕ) : b.count (· ≡ v [MOD r]) = b / r + if v % r < b % r then 1 else 0 := by have hr' : 0 < (r : ℚ) := by positivity rw [← ofNat_inj, count_modEq_card_eq_ceil _ hr, cast_add] conv_lhs => rw [← div_add_mod b r, cast_add, cast_mul, ← add_sub, _root_.add_div, mul_div_cancel_left₀ _ hr'.ne', add_comm, Int.ceil_add_nat, add_comm] rw [add_right_inj] split_ifs with h · rw [← cast_sub h.le, Int.ceil_eq_iff, div_le_iff hr', lt_div_iff hr', cast_one, Int.cast_one, sub_self, zero_mul, cast_pos, tsub_pos_iff_lt, one_mul, cast_le, tsub_le_iff_right] exact ⟨h, ((mod_lt _ hr).trans_le (by simp)).le⟩ · rw [cast_zero, ceil_eq_zero_iff, Set.mem_Ioc, div_le_iff hr', lt_div_iff hr', zero_mul, tsub_nonpos, ← neg_eq_neg_one_mul, neg_lt_sub_iff_lt_add, ← cast_add, cast_lt, cast_le] exact ⟨(mod_lt _ hr).trans_le (by simp), not_lt.mp h⟩ end Nat
Data\Int\CharZero.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.Group.Support import Mathlib.Data.Int.Cast.Field import Mathlib.Data.Int.Cast.Lemmas /-! # Injectivity of `Int.Cast` into characteristic zero rings and fields. -/ open Nat Set variable {α β : Type*} namespace Int @[simp, norm_cast] theorem cast_div_charZero {k : Type*} [DivisionRing k] [CharZero k] {m n : ℤ} (n_dvd : n ∣ m) : ((m / n : ℤ) : k) = m / n := by rcases eq_or_ne n 0 with (rfl | hn) · simp [Int.ediv_zero] · exact cast_div n_dvd (cast_ne_zero.mpr hn) -- Necessary for confluence with `ofNat_ediv` and `cast_div_charZero`. @[simp, norm_cast] theorem cast_div_ofNat_charZero {k : Type*} [DivisionRing k] [CharZero k] {m n : ℕ} (n_dvd : n ∣ m) : (((m : ℤ) / (n : ℤ) : ℤ) : k) = m / n := by rw [cast_div_charZero (Int.ofNat_dvd.mpr n_dvd), cast_natCast, cast_natCast] end Int theorem RingHom.injective_int {α : Type*} [NonAssocRing α] (f : ℤ →+* α) [CharZero α] : Function.Injective f := Subsingleton.elim (Int.castRingHom _) f ▸ Int.cast_injective namespace Function variable [AddGroupWithOne β] [CharZero β] {n : ℤ} lemma support_intCast (hn : n ≠ 0) : support (n : α → β) = univ := support_const <| Int.cast_ne_zero.2 hn @[deprecated (since := "2024-04-17")] alias support_int_cast := support_intCast lemma mulSupport_intCast (hn : n ≠ 1) : mulSupport (n : α → β) = univ := mulSupport_const <| Int.cast_ne_one.2 hn @[deprecated (since := "2024-04-17")] alias mulSupport_int_cast := mulSupport_intCast end Function
Data\Int\ConditionallyCompleteOrder.lean
/- Copyright (c) 2021 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import Mathlib.Order.ConditionallyCompleteLattice.Basic import Mathlib.Data.Int.LeastGreatest /-! ## `ℤ` forms a conditionally complete linear order The integers form a conditionally complete linear order. -/ open Int noncomputable section open scoped Classical instance instConditionallyCompleteLinearOrder : ConditionallyCompleteLinearOrder ℤ where __ := instLinearOrder __ := LinearOrder.toLattice sSup s := if h : s.Nonempty ∧ BddAbove s then greatestOfBdd (Classical.choose h.2) (Classical.choose_spec h.2) h.1 else 0 sInf s := if h : s.Nonempty ∧ BddBelow s then leastOfBdd (Classical.choose h.2) (Classical.choose_spec h.2) h.1 else 0 le_csSup s n hs hns := by have : s.Nonempty ∧ BddAbove s := ⟨⟨n, hns⟩, hs⟩ -- Porting note: this was `rw [dif_pos this]` simp only [this, and_self, dite_true] exact (greatestOfBdd _ _ _).2.2 n hns csSup_le s n hs hns := by have : s.Nonempty ∧ BddAbove s := ⟨hs, ⟨n, hns⟩⟩ -- Porting note: this was `rw [dif_pos this]` simp only [this, and_self, dite_true] exact hns (greatestOfBdd _ (Classical.choose_spec this.2) _).2.1 csInf_le s n hs hns := by have : s.Nonempty ∧ BddBelow s := ⟨⟨n, hns⟩, hs⟩ -- Porting note: this was `rw [dif_pos this]` simp only [this, and_self, dite_true] exact (leastOfBdd _ _ _).2.2 n hns le_csInf s n hs hns := by have : s.Nonempty ∧ BddBelow s := ⟨hs, ⟨n, hns⟩⟩ -- Porting note: this was `rw [dif_pos this]` simp only [this, and_self, dite_true] exact hns (leastOfBdd _ (Classical.choose_spec this.2) _).2.1 csSup_of_not_bddAbove := fun s hs ↦ by simp [hs] csInf_of_not_bddBelow := fun s hs ↦ by simp [hs] namespace Int -- Porting note: mathlib3 proof uses `convert dif_pos _ using 1` theorem csSup_eq_greatest_of_bdd {s : Set ℤ} [DecidablePred (· ∈ s)] (b : ℤ) (Hb : ∀ z ∈ s, z ≤ b) (Hinh : ∃ z : ℤ, z ∈ s) : sSup s = greatestOfBdd b Hb Hinh := by have : s.Nonempty ∧ BddAbove s := ⟨Hinh, b, Hb⟩ simp only [sSup, this, and_self, dite_true] convert (coe_greatestOfBdd_eq Hb (Classical.choose_spec (⟨b, Hb⟩ : BddAbove s)) Hinh).symm @[simp] theorem csSup_empty : sSup (∅ : Set ℤ) = 0 := dif_neg (by simp) theorem csSup_of_not_bdd_above {s : Set ℤ} (h : ¬BddAbove s) : sSup s = 0 := dif_neg (by simp [h]) -- Porting note: mathlib3 proof uses `convert dif_pos _ using 1` theorem csInf_eq_least_of_bdd {s : Set ℤ} [DecidablePred (· ∈ s)] (b : ℤ) (Hb : ∀ z ∈ s, b ≤ z) (Hinh : ∃ z : ℤ, z ∈ s) : sInf s = leastOfBdd b Hb Hinh := by have : s.Nonempty ∧ BddBelow s := ⟨Hinh, b, Hb⟩ simp only [sInf, this, and_self, dite_true] convert (coe_leastOfBdd_eq Hb (Classical.choose_spec (⟨b, Hb⟩ : BddBelow s)) Hinh).symm @[simp] theorem csInf_empty : sInf (∅ : Set ℤ) = 0 := dif_neg (by simp) theorem csInf_of_not_bdd_below {s : Set ℤ} (h : ¬BddBelow s) : sInf s = 0 := dif_neg (by simp [h]) theorem csSup_mem {s : Set ℤ} (h1 : s.Nonempty) (h2 : BddAbove s) : sSup s ∈ s := by convert (greatestOfBdd _ (Classical.choose_spec h2) h1).2.1 exact dif_pos ⟨h1, h2⟩ theorem csInf_mem {s : Set ℤ} (h1 : s.Nonempty) (h2 : BddBelow s) : sInf s ∈ s := by convert (leastOfBdd _ (Classical.choose_spec h2) h1).2.1 exact dif_pos ⟨h1, h2⟩ end Int end -- this example tests that the `Lattice ℤ` instance is computable; -- i.e., that is is not found via the noncomputable instance in this file. example : Lattice ℤ := inferInstance
Data\Int\Defs.lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad -/ import Mathlib.Data.Int.Notation import Mathlib.Data.Nat.Defs import Mathlib.Algebra.Group.ZeroOne import Mathlib.Logic.Nontrivial.Defs import Mathlib.Tactic.Convert import Mathlib.Tactic.Lift /-! # Basic operations on the integers This file contains some basic lemmas about integers. See note [foundational algebra order theory]. ## TODO Split this file into: * `Data.Int.Init` (or maybe `Data.Int.Batteries`?) for lemmas that could go to Batteries * `Data.Int.Basic` for the lemmas that require mathlib definitions -/ open Nat namespace Int variable {a b c d m n : ℤ} section Order variable {a b c : ℤ} protected lemma le_rfl : a ≤ a := a.le_refl protected lemma lt_or_lt_of_ne : a ≠ b → a < b ∨ b < a := Int.lt_or_gt_of_ne protected lemma lt_or_le (a b : ℤ) : a < b ∨ b ≤ a := by rw [← Int.not_lt]; exact em _ protected lemma le_or_lt (a b : ℤ) : a ≤ b ∨ b < a := (b.lt_or_le a).symm protected lemma lt_asymm : a < b → ¬ b < a := by rw [Int.not_lt]; exact Int.le_of_lt protected lemma le_of_eq (hab : a = b) : a ≤ b := by rw [hab]; exact Int.le_rfl protected lemma ge_of_eq (hab : a = b) : b ≤ a := Int.le_of_eq hab.symm protected lemma le_antisymm_iff : a = b ↔ a ≤ b ∧ b ≤ a := ⟨fun h ↦ ⟨Int.le_of_eq h, Int.ge_of_eq h⟩, fun h ↦ Int.le_antisymm h.1 h.2⟩ protected lemma le_iff_eq_or_lt : a ≤ b ↔ a = b ∨ a < b := by rw [Int.le_antisymm_iff, Int.lt_iff_le_not_le, ← and_or_left]; simp [em] protected lemma le_iff_lt_or_eq : a ≤ b ↔ a < b ∨ a = b := by rw [Int.le_iff_eq_or_lt, or_comm] end Order -- TODO: Tag in Lean attribute [simp] natAbs_pos protected lemma one_pos : 0 < (1 : Int) := Int.zero_lt_one protected lemma one_ne_zero : (1 : ℤ) ≠ 0 := by decide protected lemma one_nonneg : 0 ≤ (1 : ℤ) := Int.le_of_lt Int.zero_lt_one lemma zero_le_ofNat (n : ℕ) : 0 ≤ ofNat n := @le.intro _ _ n (by rw [Int.zero_add]; rfl) protected theorem neg_eq_neg {a b : ℤ} (h : -a = -b) : a = b := Int.neg_inj.1 h -- We want to use these lemmas earlier than the lemmas simp can prove them with @[simp, nolint simpNF] protected lemma neg_pos : 0 < -a ↔ a < 0 := ⟨Int.neg_of_neg_pos, Int.neg_pos_of_neg⟩ @[simp, nolint simpNF] protected lemma neg_nonneg : 0 ≤ -a ↔ a ≤ 0 := ⟨Int.nonpos_of_neg_nonneg, Int.neg_nonneg_of_nonpos⟩ @[simp, nolint simpNF] protected lemma neg_neg_iff_pos : -a < 0 ↔ 0 < a := ⟨Int.pos_of_neg_neg, Int.neg_neg_of_pos⟩ @[simp, nolint simpNF] protected lemma neg_nonpos_iff_nonneg : -a ≤ 0 ↔ 0 ≤ a := ⟨Int.nonneg_of_neg_nonpos, Int.neg_nonpos_of_nonneg⟩ @[simp, nolint simpNF] protected lemma sub_pos : 0 < a - b ↔ b < a := ⟨Int.lt_of_sub_pos, Int.sub_pos_of_lt⟩ @[simp, nolint simpNF] protected lemma sub_nonneg : 0 ≤ a - b ↔ b ≤ a := ⟨Int.le_of_sub_nonneg, Int.sub_nonneg_of_le⟩ instance instNontrivial : Nontrivial ℤ := ⟨⟨0, 1, Int.zero_ne_one⟩⟩ protected theorem ofNat_add_out (m n : ℕ) : ↑m + ↑n = (↑(m + n) : ℤ) := rfl protected theorem ofNat_mul_out (m n : ℕ) : ↑m * ↑n = (↑(m * n) : ℤ) := rfl protected theorem ofNat_add_one_out (n : ℕ) : ↑n + (1 : ℤ) = ↑(succ n) := rfl @[simp] lemma ofNat_injective : Function.Injective ofNat := @Int.ofNat.inj @[simp] lemma ofNat_eq_natCast (n : ℕ) : Int.ofNat n = n := rfl @[deprecated ofNat_eq_natCast (since := "2024-03-24")] protected lemma natCast_eq_ofNat (n : ℕ) : ↑n = Int.ofNat n := rfl @[norm_cast] lemma natCast_inj {m n : ℕ} : (m : ℤ) = (n : ℤ) ↔ m = n := ofNat_inj @[simp, norm_cast] lemma natAbs_cast (n : ℕ) : natAbs ↑n = n := rfl @[norm_cast] protected lemma natCast_sub {n m : ℕ} : n ≤ m → (↑(m - n) : ℤ) = ↑m - ↑n := ofNat_sub -- We want to use this lemma earlier than the lemmas simp can prove it with @[simp, nolint simpNF] lemma natCast_eq_zero {n : ℕ} : (n : ℤ) = 0 ↔ n = 0 := by omega lemma natCast_ne_zero {n : ℕ} : (n : ℤ) ≠ 0 ↔ n ≠ 0 := by omega lemma natCast_ne_zero_iff_pos {n : ℕ} : (n : ℤ) ≠ 0 ↔ 0 < n := by omega -- We want to use this lemma earlier than the lemmas simp can prove it with @[simp, nolint simpNF] lemma natCast_pos {n : ℕ} : (0 : ℤ) < n ↔ 0 < n := by omega lemma natCast_succ_pos (n : ℕ) : 0 < (n.succ : ℤ) := natCast_pos.2 n.succ_pos @[simp] lemma natCast_nonpos_iff {n : ℕ} : (n : ℤ) ≤ 0 ↔ n = 0 := by omega lemma natCast_nonneg (n : ℕ) : 0 ≤ (n : ℤ) := ofNat_le.2 (Nat.zero_le _) @[simp] lemma sign_natCast_add_one (n : ℕ) : sign (n + 1) = 1 := rfl @[simp, norm_cast] lemma cast_id {n : ℤ} : Int.cast n = n := rfl protected lemma two_mul : ∀ n : ℤ, 2 * n = n + n | (n : ℕ) => by norm_cast; exact n.two_mul | -[n+1] => by change (2 : ℕ) * (_ : ℤ) = _ rw [Int.ofNat_mul_negSucc, Nat.two_mul, ofNat_add, Int.neg_add] rfl protected lemma mul_le_mul_iff_of_pos_right (ha : 0 < a) : b * a ≤ c * a ↔ b ≤ c := ⟨(le_of_mul_le_mul_right · ha), (Int.mul_le_mul_of_nonneg_right · (Int.le_of_lt ha))⟩ protected lemma mul_nonneg_iff_of_pos_right (hb : 0 < b) : 0 ≤ a * b ↔ 0 ≤ a := by simpa using (Int.mul_le_mul_iff_of_pos_right hb : 0 * b ≤ a * b ↔ 0 ≤ a) /-! ### succ and pred -/ /-- Immediate successor of an integer: `succ n = n + 1` -/ def succ (a : ℤ) := a + 1 /-- Immediate predecessor of an integer: `pred n = n - 1` -/ def pred (a : ℤ) := a - 1 lemma natCast_succ (n : ℕ) : (Nat.succ n : ℤ) = Int.succ n := rfl lemma pred_succ (a : ℤ) : pred (succ a) = a := Int.add_sub_cancel _ _ lemma succ_pred (a : ℤ) : succ (pred a) = a := Int.sub_add_cancel _ _ lemma neg_succ (a : ℤ) : -succ a = pred (-a) := Int.neg_add lemma succ_neg_succ (a : ℤ) : succ (-succ a) = -a := by rw [neg_succ, succ_pred] lemma neg_pred (a : ℤ) : -pred a = succ (-a) := by rw [← Int.neg_eq_comm.mp (neg_succ (-a)), Int.neg_neg] lemma pred_neg_pred (a : ℤ) : pred (-pred a) = -a := by rw [neg_pred, pred_succ] lemma pred_nat_succ (n : ℕ) : pred (Nat.succ n) = n := pred_succ n lemma neg_nat_succ (n : ℕ) : -(Nat.succ n : ℤ) = pred (-n) := neg_succ n lemma succ_neg_natCast_succ (n : ℕ) : succ (-Nat.succ n) = -n := succ_neg_succ n @[norm_cast] lemma natCast_pred_of_pos {n : ℕ} (h : 0 < n) : ((n - 1 : ℕ) : ℤ) = (n : ℤ) - 1 := by cases n; cases h; simp [ofNat_succ] lemma lt_succ_self (a : ℤ) : a < succ a := by unfold succ; omega lemma pred_self_lt (a : ℤ) : pred a < a := by unfold pred; omega lemma le_add_one_iff : m ≤ n + 1 ↔ m ≤ n ∨ m = n + 1 := by omega lemma sub_one_lt_iff : m - 1 < n ↔ m ≤ n := by omega lemma le_sub_one_iff : m ≤ n - 1 ↔ m < n := by omega section open Lean.Omega.Int /-! The following few lemmas are proved in the core implementation of the `omega` tactic. We expose them here with nice user-facing names. -/ protected lemma add_le_iff_le_sub : a + b ≤ c ↔ a ≤ c - b := add_le_iff_le_sub .. protected lemma le_add_iff_sub_le : a ≤ b + c ↔ a - c ≤ b := le_add_iff_sub_le .. protected lemma add_le_zero_iff_le_neg : a + b ≤ 0 ↔ a ≤ - b := add_le_zero_iff_le_neg .. protected lemma add_le_zero_iff_le_neg' : a + b ≤ 0 ↔ b ≤ -a := add_le_zero_iff_le_neg' .. protected lemma add_nonnneg_iff_neg_le : 0 ≤ a + b ↔ -b ≤ a := add_nonnneg_iff_neg_le .. protected lemma add_nonnneg_iff_neg_le' : 0 ≤ a + b ↔ -a ≤ b := add_nonnneg_iff_neg_le' .. end @[elab_as_elim] protected lemma induction_on {p : ℤ → Prop} (i : ℤ) (hz : p 0) (hp : ∀ i : ℕ, p i → p (i + 1)) (hn : ∀ i : ℕ, p (-i) → p (-i - 1)) : p i := by induction i with | ofNat i => induction i with | zero => exact hz | succ i ih => exact hp _ ih | negSucc i => suffices ∀ n : ℕ, p (-n) from this (i + 1) intro n; induction n with | zero => simp [hz] | succ n ih => convert hn _ ih using 1; simp [ofNat_succ, Int.neg_add, Int.sub_eq_add_neg] section inductionOn' variable {C : ℤ → Sort*} (z b : ℤ) (H0 : C b) (Hs : ∀ k, b ≤ k → C k → C (k + 1)) (Hp : ∀ k ≤ b, C k → C (k - 1)) /-- Inductively define a function on `ℤ` by defining it at `b`, for the `succ` of a number greater than `b`, and the `pred` of a number less than `b`. -/ @[elab_as_elim] protected def inductionOn' : C z := cast (congr_arg C <| show b + (z - b) = z by rw [Int.add_comm, z.sub_add_cancel b]) <| match z - b with | .ofNat n => pos n | .negSucc n => neg n where /-- The positive case of `Int.inductionOn'`. -/ pos : ∀ n : ℕ, C (b + n) | 0 => cast (by erw [Int.add_zero]) H0 | n+1 => cast (by rw [Int.add_assoc]; rfl) <| Hs _ (Int.le_add_of_nonneg_right (ofNat_nonneg _)) (pos n) /-- The negative case of `Int.inductionOn'`. -/ neg : ∀ n : ℕ, C (b + -[n+1]) | 0 => Hp _ Int.le_rfl H0 | n+1 => by refine cast (by rw [Int.add_sub_assoc]; rfl) (Hp _ (Int.le_of_lt ?_) (neg n)) conv => rhs; exact b.add_zero.symm rw [Int.add_lt_add_iff_left]; apply negSucc_lt_zero variable (b) {z b b H0 Hs Hp} lemma inductionOn'_self : b.inductionOn' b H0 Hs Hp = H0 := cast_eq_iff_heq.mpr <| .symm <| by rw [b.sub_self, ← cast_eq_iff_heq]; rfl lemma inductionOn'_add_one (hz : b ≤ z) : (z + 1).inductionOn' b H0 Hs Hp = Hs z hz (z.inductionOn' b H0 Hs Hp) := by apply cast_eq_iff_heq.mpr lift z - b to ℕ using Int.sub_nonneg.mpr hz with zb hzb rw [show z + 1 - b = zb + 1 by omega] have : b + zb = z := by omega subst this convert cast_heq _ _ rw [Int.inductionOn', cast_eq_iff_heq, ← hzb] lemma inductionOn'_sub_one (hz : z ≤ b) : (z - 1).inductionOn' b H0 Hs Hp = Hp z hz (z.inductionOn' b H0 Hs Hp) := by apply cast_eq_iff_heq.mpr obtain ⟨n, hn⟩ := Int.eq_negSucc_of_lt_zero (show z - 1 - b < 0 by omega) rw [hn] obtain _|n := n · change _ = -1 at hn have : z = b := by omega subst this; rw [inductionOn'_self]; exact heq_of_eq rfl · have : z = b + -[n+1] := by rw [Int.negSucc_eq] at hn ⊢; omega subst this convert cast_heq _ _ rw [Int.inductionOn', cast_eq_iff_heq, show b + -[n+1] - b = -[n+1] by omega] end inductionOn' /-- Inductively define a function on `ℤ` by defining it on `ℕ` and extending it from `n` to `-n`. -/ @[elab_as_elim] protected def negInduction {C : ℤ → Sort*} (nat : ∀ n : ℕ, C n) (neg : ∀ n : ℕ, C n → C (-n)) : ∀ n : ℤ, C n | .ofNat n => nat n | .negSucc n => neg _ <| nat <| n + 1 /-- See `Int.inductionOn'` for an induction in both directions. -/ protected lemma le_induction {P : ℤ → Prop} {m : ℤ} (h0 : P m) (h1 : ∀ n : ℤ, m ≤ n → P n → P (n + 1)) (n : ℤ) : m ≤ n → P n := by refine Int.inductionOn' n m ?_ ?_ ?_ · intro exact h0 · intro k hle hi _ exact h1 k hle (hi hle) · intro k hle _ hle' omega /-- See `Int.inductionOn'` for an induction in both directions. -/ protected theorem le_induction_down {P : ℤ → Prop} {m : ℤ} (h0 : P m) (h1 : ∀ n : ℤ, n ≤ m → P n → P (n - 1)) (n : ℤ) : n ≤ m → P n := Int.inductionOn' n m (fun _ ↦ h0) (fun k hle _ hle' ↦ by omega) fun k hle hi _ ↦ h1 k hle (hi hle) section strongRec variable {P : ℤ → Sort*} (lt : ∀ n < m, P n) (ge : ∀ n ≥ m, (∀ k < n, P k) → P n) /-- A strong recursor for `Int` that specifies explicit values for integers below a threshold, and is analogous to `Nat.strongRec` for integers on or above the threshold. -/ @[elab_as_elim] protected def strongRec (n : ℤ) : P n := by refine if hnm : n < m then lt n hnm else ge n (by omega) (n.inductionOn' m lt ?_ ?_) · intro _n _ ih l _ exact if hlm : l < m then lt l hlm else ge l (by omega) fun k _ ↦ ih k (by omega) · exact fun n _ hn l _ ↦ hn l (by omega) variable {lt ge} lemma strongRec_of_lt (hn : n < m) : m.strongRec lt ge n = lt n hn := dif_pos _ lemma strongRec_of_ge : ∀ hn : m ≤ n, m.strongRec lt ge n = ge n hn fun k _ ↦ m.strongRec lt ge k := by refine m.strongRec (fun n hnm hmn ↦ (Int.not_lt.mpr hmn hnm).elim) (fun n _ ih hn ↦ ?_) n rw [Int.strongRec, dif_neg (Int.not_lt.mpr hn)] congr; revert ih refine n.inductionOn' m (fun _ ↦ ?_) (fun k hmk ih' ih ↦ ?_) (fun k hkm ih' _ ↦ ?_) <;> ext l hl · rw [inductionOn'_self, strongRec_of_lt hl] · rw [inductionOn'_add_one hmk]; split_ifs with hlm · rw [strongRec_of_lt hlm] · rw [ih' fun l hl ↦ ih l (Int.lt_trans hl k.lt_succ), ih _ hl] · rw [inductionOn'_sub_one hkm, ih'] exact fun l hlk hml ↦ (Int.not_lt.mpr hkm <| Int.lt_of_le_of_lt hml hlk).elim end strongRec /-! ### nat abs -/ -- TODO: Rename `natAbs_ofNat` to `natAbs_natCast` @[simp] lemma natAbs_ofNat' (n : ℕ) : natAbs (ofNat n) = n := rfl lemma natAbs_add_of_nonneg : ∀ {a b : Int}, 0 ≤ a → 0 ≤ b → natAbs (a + b) = natAbs a + natAbs b | ofNat _, ofNat _, _, _ => rfl lemma natAbs_add_of_nonpos {a b : Int} (ha : a ≤ 0) (hb : b ≤ 0) : natAbs (a + b) = natAbs a + natAbs b := by omega lemma natAbs_surjective : natAbs.Surjective := fun n => ⟨n, natAbs_ofNat n⟩ lemma natAbs_pow (n : ℤ) (k : ℕ) : Int.natAbs (n ^ k) = Int.natAbs n ^ k := by induction' k with k ih · rfl · rw [Int.pow_succ, natAbs_mul, Nat.pow_succ, ih, Nat.mul_comm] lemma pow_right_injective (h : 1 < a.natAbs) : ((a ^ ·) : ℕ → ℤ).Injective := by refine (?_ : (natAbs ∘ (a ^ · : ℕ → ℤ)).Injective).of_comp convert Nat.pow_right_injective h using 2 rw [Function.comp_apply, natAbs_pow] lemma natAbs_sq (x : ℤ) : (x.natAbs : ℤ) ^ 2 = x ^ 2 := by simp [Int.pow_succ, Int.pow_zero, Int.natAbs_mul_self'] alias natAbs_pow_two := natAbs_sq /-! ### `/` -/ @[simp, norm_cast] lemma natCast_div (m n : ℕ) : ((m / n : ℕ) : ℤ) = m / n := rfl lemma natCast_ediv (m n : ℕ) : ((m / n : ℕ) : ℤ) = ediv m n := rfl lemma ediv_of_neg_of_pos {a b : ℤ} (Ha : a < 0) (Hb : 0 < b) : ediv a b = -((-a - 1) / b + 1) := match a, b, eq_negSucc_of_lt_zero Ha, eq_succ_of_zero_lt Hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ => by rw [show (- -[m+1] : ℤ) = (m + 1 : ℤ) by rfl]; rw [Int.add_sub_cancel]; rfl /-! ### mod -/ @[simp, norm_cast] lemma natCast_mod (m n : ℕ) : (↑(m % n) : ℤ) = ↑m % ↑n := rfl lemma add_emod_eq_add_mod_right {m n k : ℤ} (i : ℤ) (H : m % n = k % n) : (m + i) % n = (k + i) % n := by rw [← emod_add_emod, ← emod_add_emod k, H] @[simp] lemma neg_emod_two (i : ℤ) : -i % 2 = i % 2 := by apply Int.emod_eq_emod_iff_emod_sub_eq_zero.mpr convert Int.mul_emod_right 2 (-i) using 2 rw [Int.two_mul, Int.sub_eq_add_neg] /-! ### properties of `/` and `%` -/ lemma emod_two_eq_zero_or_one (n : ℤ) : n % 2 = 0 ∨ n % 2 = 1 := have h : n % 2 < 2 := by omega have h₁ : 0 ≤ n % 2 := Int.emod_nonneg _ (by decide) match n % 2, h, h₁ with | (0 : ℕ), _ ,_ => Or.inl rfl | (1 : ℕ), _ ,_ => Or.inr rfl | (k + 2 : ℕ), h₁, _ => by omega | -[a+1], _, h₁ => by cases h₁ /-! ### dvd -/ attribute [simp] Int.dvd_zero Int.dvd_mul_left Int.dvd_mul_right protected lemma mul_dvd_mul : a ∣ b → c ∣ d → a * c ∣ b * d | ⟨e, he⟩, ⟨f, hf⟩ => ⟨e * f, by simp [he, hf, Int.mul_assoc, Int.mul_left_comm, Nat.mul_comm]⟩ protected lemma mul_dvd_mul_left (a : ℤ) (h : b ∣ c) : a * b ∣ a * c := Int.mul_dvd_mul a.dvd_refl h protected lemma mul_dvd_mul_right (a : ℤ) (h : b ∣ c) : b * a ∣ c * a := Int.mul_dvd_mul h a.dvd_refl lemma dvd_mul_of_div_dvd (h : b ∣ a) (hdiv : a / b ∣ c) : a ∣ b * c := by obtain ⟨e, rfl⟩ := hdiv rw [← Int.mul_assoc, Int.mul_comm _ (a / b), Int.ediv_mul_cancel h] exact Int.dvd_mul_right a e @[simp] lemma div_dvd_iff_dvd_mul (h : b ∣ a) (hb : b ≠ 0) : a / b ∣ c ↔ a ∣ b * c := exists_congr <| fun d ↦ by have := Int.dvd_trans (Int.dvd_mul_left _ _) (Int.mul_dvd_mul_left d h) rw [eq_comm, Int.mul_comm, ← Int.mul_ediv_assoc d h, Int.ediv_eq_iff_eq_mul_right hb this, Int.mul_comm, eq_comm] lemma mul_dvd_of_dvd_div (hcb : c ∣ b) (h : a ∣ b / c) : c * a ∣ b := have ⟨d, hd⟩ := h ⟨d, by simpa [Int.mul_comm, Int.mul_left_comm] using Int.eq_mul_of_ediv_eq_left hcb hd⟩ lemma dvd_div_of_mul_dvd (h : a * b ∣ c) : b ∣ c / a := by obtain rfl | ha := eq_or_ne a 0 · simp · obtain ⟨d, rfl⟩ := h simp [Int.mul_assoc, ha] @[simp] lemma dvd_div_iff_mul_dvd (hbc : c ∣ b) : a ∣ b / c ↔ c * a ∣ b := ⟨mul_dvd_of_dvd_div hbc, dvd_div_of_mul_dvd⟩ lemma ediv_dvd_ediv : ∀ {a b c : ℤ}, a ∣ b → b ∣ c → b / a ∣ c / a | a, _, _, ⟨b, rfl⟩, ⟨c, rfl⟩ => if az : a = 0 then by simp [az] else by rw [Int.mul_ediv_cancel_left _ az, Int.mul_assoc, Int.mul_ediv_cancel_left _ az] apply Int.dvd_mul_right /-- If `n > 0` then `m` is not divisible by `n` iff it is between `n * k` and `n * (k + 1)` for some `k`. -/ lemma exists_lt_and_lt_iff_not_dvd (m : ℤ) (hn : 0 < n) : (∃ k, n * k < m ∧ m < n * (k + 1)) ↔ ¬n ∣ m := by refine ⟨?_, fun h ↦ ?_⟩ · rintro ⟨k, h1k, h2k⟩ ⟨l, rfl⟩ replace h1k := lt_of_mul_lt_mul_left h1k (by omega) replace h2k := lt_of_mul_lt_mul_left h2k (by omega) rw [Int.lt_add_one_iff, ← Int.not_lt] at h2k exact h2k h1k · rw [dvd_iff_emod_eq_zero, ← Ne] at h rw [← emod_add_ediv m n] refine ⟨m / n, Int.lt_add_of_pos_left _ ?_, ?_⟩ · have := emod_nonneg m (Int.ne_of_gt hn) omega · rw [Int.add_comm _ (1 : ℤ), Int.mul_add, Int.mul_one] exact Int.add_lt_add_right (emod_lt_of_pos _ hn) _ @[norm_cast] lemma natCast_dvd_natCast {m n : ℕ} : (↑m : ℤ) ∣ ↑n ↔ m ∣ n where mp := by rintro ⟨a, h⟩ obtain rfl | hm := m.eq_zero_or_pos · simpa using h have ha : 0 ≤ a := Int.not_lt.1 fun ha ↦ by simpa [← h, Int.not_lt.2 (Int.natCast_nonneg _)] using Int.mul_neg_of_pos_of_neg (natCast_pos.2 hm) ha lift a to ℕ using ha norm_cast at h exact ⟨a, h⟩ mpr := by rintro ⟨a, rfl⟩; simp [Int.dvd_mul_right] lemma natCast_dvd {m : ℕ} : (m : ℤ) ∣ n ↔ m ∣ n.natAbs := by obtain hn | hn := natAbs_eq n <;> rw [hn] <;> simp [← natCast_dvd_natCast, Int.dvd_neg] lemma dvd_natCast {n : ℕ} : m ∣ (n : ℤ) ↔ m.natAbs ∣ n := by obtain hn | hn := natAbs_eq m <;> rw [hn] <;> simp [← natCast_dvd_natCast, Int.neg_dvd] lemma natAbs_ediv (a b : ℤ) (H : b ∣ a) : natAbs (a / b) = natAbs a / natAbs b := by rcases Nat.eq_zero_or_pos (natAbs b) with (h | h) · rw [natAbs_eq_zero.1 h] simp [Int.ediv_zero] calc natAbs (a / b) = natAbs (a / b) * 1 := by rw [Nat.mul_one] _ = natAbs (a / b) * (natAbs b / natAbs b) := by rw [Nat.div_self h] _ = natAbs (a / b) * natAbs b / natAbs b := by rw [Nat.mul_div_assoc _ b.natAbs.dvd_refl] _ = natAbs (a / b * b) / natAbs b := by rw [natAbs_mul (a / b) b] _ = natAbs a / natAbs b := by rw [Int.ediv_mul_cancel H] lemma dvd_of_mul_dvd_mul_left (ha : a ≠ 0) (h : a * m ∣ a * n) : m ∣ n := by obtain ⟨b, hb⟩ := h rw [Int.mul_assoc, Int.mul_eq_mul_left_iff ha] at hb exact ⟨_, hb⟩ lemma dvd_of_mul_dvd_mul_right (ha : a ≠ 0) (h : m * a ∣ n * a) : m ∣ n := dvd_of_mul_dvd_mul_left ha (by simpa [Int.mul_comm] using h) lemma eq_mul_div_of_mul_eq_mul_of_dvd_left (hb : b ≠ 0) (hbc : b ∣ c) (h : b * a = c * d) : a = c / b * d := by obtain ⟨k, rfl⟩ := hbc rw [Int.mul_ediv_cancel_left _ hb] rwa [Int.mul_assoc, Int.mul_eq_mul_left_iff hb] at h /-- If an integer with larger absolute value divides an integer, it is zero. -/ lemma eq_zero_of_dvd_of_natAbs_lt_natAbs (hmn : m ∣ n) (hnm : natAbs n < natAbs m) : n = 0 := by rw [← natAbs_dvd, ← dvd_natAbs, natCast_dvd_natCast] at hmn rw [← natAbs_eq_zero] exact Nat.eq_zero_of_dvd_of_lt hmn hnm lemma eq_zero_of_dvd_of_nonneg_of_lt (hm : 0 ≤ m) (hmn : m < n) (hnm : n ∣ m) : m = 0 := eq_zero_of_dvd_of_natAbs_lt_natAbs hnm (natAbs_lt_natAbs_of_nonneg_of_lt hm hmn) /-- If two integers are congruent to a sufficiently large modulus, they are equal. -/ lemma eq_of_mod_eq_of_natAbs_sub_lt_natAbs {a b c : ℤ} (h1 : a % b = c) (h2 : natAbs (a - c) < natAbs b) : a = c := Int.eq_of_sub_eq_zero (eq_zero_of_dvd_of_natAbs_lt_natAbs (dvd_sub_of_emod_eq h1) h2) lemma ofNat_add_negSucc_of_ge {m n : ℕ} (h : n.succ ≤ m) : ofNat m + -[n+1] = ofNat (m - n.succ) := by rw [negSucc_eq, ofNat_eq_natCast, ofNat_eq_natCast, ← natCast_one, ← natCast_add, ← Int.sub_eq_add_neg, ← Int.natCast_sub h] lemma natAbs_le_of_dvd_ne_zero (hmn : m ∣ n) (hn : n ≠ 0) : natAbs m ≤ natAbs n := not_lt.mp (mt (eq_zero_of_dvd_of_natAbs_lt_natAbs hmn) hn) @[deprecated (since := "2024-04-02")] alias coe_nat_dvd := natCast_dvd_natCast @[deprecated (since := "2024-04-02")] alias coe_nat_dvd_right := dvd_natCast @[deprecated (since := "2024-04-02")] alias coe_nat_dvd_left := natCast_dvd /-! #### `/` and ordering -/ lemma natAbs_eq_of_dvd_dvd (hmn : m ∣ n) (hnm : n ∣ m) : natAbs m = natAbs n := Nat.dvd_antisymm (natAbs_dvd_natAbs.2 hmn) (natAbs_dvd_natAbs.2 hnm) lemma ediv_dvd_of_dvd (hmn : m ∣ n) : n / m ∣ n := by obtain rfl | hm := eq_or_ne m 0 · simpa using hmn · obtain ⟨a, ha⟩ := hmn simp [ha, Int.mul_ediv_cancel_left _ hm, Int.dvd_mul_left] lemma le_iff_pos_of_dvd (ha : 0 < a) (hab : a ∣ b) : a ≤ b ↔ 0 < b := ⟨Int.lt_of_lt_of_le ha, (Int.le_of_dvd · hab)⟩ lemma le_add_iff_lt_of_dvd_sub (ha : 0 < a) (hab : a ∣ c - b) : a + b ≤ c ↔ b < c := by rw [Int.add_le_iff_le_sub, ← Int.sub_pos, le_iff_pos_of_dvd ha hab] /-! ### sign -/ lemma sign_natCast_of_ne_zero {n : ℕ} (hn : n ≠ 0) : Int.sign n = 1 := sign_ofNat_of_nonzero hn lemma sign_add_eq_of_sign_eq : ∀ {m n : ℤ}, m.sign = n.sign → (m + n).sign = n.sign := by have : (1 : ℤ) ≠ -1 := by decide rintro ((_ | m) | m) ((_ | n) | n) <;> simp [this, this.symm, Int.negSucc_add_negSucc] rw [Int.sign_eq_one_iff_pos] apply Int.add_pos <;> omega /-! ### toNat -/ @[simp] lemma toNat_natCast (n : ℕ) : toNat ↑n = n := rfl @[simp] lemma toNat_natCast_add_one {n : ℕ} : ((n : ℤ) + 1).toNat = n + 1 := rfl @[simp] lemma toNat_le {n : ℕ} : toNat m ≤ n ↔ m ≤ n := by rw [ofNat_le.symm, toNat_eq_max, Int.max_le]; exact and_iff_left (ofNat_zero_le _) @[simp] lemma lt_toNat {m : ℕ} : m < toNat n ↔ (m : ℤ) < n := by rw [← Int.not_le, ← Nat.not_le, toNat_le] lemma toNat_le_toNat {a b : ℤ} (h : a ≤ b) : toNat a ≤ toNat b := by rw [toNat_le]; exact Int.le_trans h (self_le_toNat b) lemma toNat_lt_toNat {a b : ℤ} (hb : 0 < b) : toNat a < toNat b ↔ a < b where mp h := by cases a; exacts [lt_toNat.1 h, Int.lt_trans (neg_of_sign_eq_neg_one rfl) hb] mpr h := by rw [lt_toNat]; cases a; exacts [h, hb] lemma lt_of_toNat_lt {a b : ℤ} (h : toNat a < toNat b) : a < b := (toNat_lt_toNat <| lt_toNat.1 <| Nat.lt_of_le_of_lt (Nat.zero_le _) h).1 h @[simp] lemma toNat_pred_coe_of_pos {i : ℤ} (h : 0 < i) : ((i.toNat - 1 : ℕ) : ℤ) = i - 1 := by simp [h, Int.le_of_lt h, push_cast] @[simp] lemma toNat_eq_zero : ∀ {n : ℤ}, n.toNat = 0 ↔ n ≤ 0 | (n : ℕ) => by simp | -[n+1] => by simpa [toNat] using Int.le_of_lt (negSucc_lt_zero n) @[simp] theorem toNat_sub_of_le {a b : ℤ} (h : b ≤ a) : (toNat (a - b) : ℤ) = a - b := Int.toNat_of_nonneg (Int.sub_nonneg_of_le h) @[deprecated (since := "2024-04-05")] alias coe_nat_pos := natCast_pos @[deprecated (since := "2024-04-05")] alias coe_nat_succ_pos := natCast_succ_pos lemma toNat_lt' {n : ℕ} (hn : n ≠ 0) : m.toNat < n ↔ m < n := by rw [← toNat_lt_toNat, toNat_natCast]; omega /-- The modulus of an integer by another as a natural. Uses the E-rounding convention. -/ def natMod (m n : ℤ) : ℕ := (m % n).toNat lemma natMod_lt {n : ℕ} (hn : n ≠ 0) : m.natMod n < n := (toNat_lt' hn).2 <| emod_lt_of_pos _ <| by omega attribute [simp] natCast_pow @[deprecated (since := "2024-05-25")] alias coe_nat_pow := natCast_pow -- Porting note: this was added in an ad hoc port for use in `Tactic/NormNum/Basic` @[simp] lemma pow_eq (m : ℤ) (n : ℕ) : m.pow n = m ^ n := rfl @[deprecated (since := "2024-04-02")] alias ofNat_eq_cast := ofNat_eq_natCast @[deprecated (since := "2024-04-02")] alias cast_eq_cast_iff_Nat := natCast_inj @[deprecated (since := "2024-04-02")] alias coe_nat_sub := Int.natCast_sub @[deprecated (since := "2024-04-02")] alias coe_nat_nonneg := natCast_nonneg @[deprecated (since := "2024-04-02")] alias sign_coe_add_one := sign_natCast_add_one @[deprecated (since := "2024-04-02")] alias nat_succ_eq_int_succ := natCast_succ @[deprecated (since := "2024-04-02")] alias succ_neg_nat_succ := succ_neg_natCast_succ @[deprecated (since := "2024-04-02")] alias coe_pred_of_pos := natCast_pred_of_pos @[deprecated (since := "2024-04-02")] alias coe_nat_div := natCast_div @[deprecated (since := "2024-04-02")] alias coe_nat_ediv := natCast_ediv @[deprecated (since := "2024-04-02")] alias sign_coe_nat_of_nonzero := sign_natCast_of_ne_zero @[deprecated (since := "2024-04-02")] alias toNat_coe_nat := toNat_natCast @[deprecated (since := "2024-04-02")] alias toNat_coe_nat_add_one := toNat_natCast_add_one
Data\Int\GCD.lean
/- Copyright (c) 2018 Guy Leroy. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sangwoo Jo (aka Jason), Guy Leroy, Johannes Hölzl, Mario Carneiro -/ import Mathlib.Algebra.Group.Int import Mathlib.Algebra.GroupWithZero.Semiconj import Mathlib.Order.Bounds.Basic import Mathlib.Algebra.Group.Commute.Units import Mathlib.Data.Nat.GCD.Basic /-! # Extended GCD and divisibility over ℤ ## Main definitions * Given `x y : ℕ`, `xgcd x y` computes the pair of integers `(a, b)` such that `gcd x y = x * a + y * b`. `gcdA x y` and `gcdB x y` are defined to be `a` and `b`, respectively. ## Main statements * `gcd_eq_gcd_ab`: Bézout's lemma, given `x y : ℕ`, `gcd x y = x * gcdA x y + y * gcdB x y`. ## Tags Bézout's lemma, Bezout's lemma -/ /-! ### Extended Euclidean algorithm -/ namespace Nat /-- Helper function for the extended GCD algorithm (`Nat.xgcd`). -/ def xgcdAux : ℕ → ℤ → ℤ → ℕ → ℤ → ℤ → ℕ × ℤ × ℤ | 0, _, _, r', s', t' => (r', s', t') | succ k, s, t, r', s', t' => let q := r' / succ k xgcdAux (r' % succ k) (s' - q * s) (t' - q * t) (succ k) s t termination_by k => k decreasing_by exact mod_lt _ <| (succ_pos _).gt @[simp] theorem xgcd_zero_left {s t r' s' t'} : xgcdAux 0 s t r' s' t' = (r', s', t') := by simp [xgcdAux] theorem xgcdAux_rec {r s t r' s' t'} (h : 0 < r) : xgcdAux r s t r' s' t' = xgcdAux (r' % r) (s' - r' / r * s) (t' - r' / r * t) r s t := by obtain ⟨r, rfl⟩ := Nat.exists_eq_succ_of_ne_zero h.ne' simp [xgcdAux] /-- Use the extended GCD algorithm to generate the `a` and `b` values satisfying `gcd x y = x * a + y * b`. -/ def xgcd (x y : ℕ) : ℤ × ℤ := (xgcdAux x 1 0 y 0 1).2 /-- The extended GCD `a` value in the equation `gcd x y = x * a + y * b`. -/ def gcdA (x y : ℕ) : ℤ := (xgcd x y).1 /-- The extended GCD `b` value in the equation `gcd x y = x * a + y * b`. -/ def gcdB (x y : ℕ) : ℤ := (xgcd x y).2 @[simp] theorem gcdA_zero_left {s : ℕ} : gcdA 0 s = 0 := by unfold gcdA rw [xgcd, xgcd_zero_left] @[simp] theorem gcdB_zero_left {s : ℕ} : gcdB 0 s = 1 := by unfold gcdB rw [xgcd, xgcd_zero_left] @[simp] theorem gcdA_zero_right {s : ℕ} (h : s ≠ 0) : gcdA s 0 = 1 := by unfold gcdA xgcd obtain ⟨s, rfl⟩ := Nat.exists_eq_succ_of_ne_zero h rw [xgcdAux] simp @[simp] theorem gcdB_zero_right {s : ℕ} (h : s ≠ 0) : gcdB s 0 = 0 := by unfold gcdB xgcd obtain ⟨s, rfl⟩ := Nat.exists_eq_succ_of_ne_zero h rw [xgcdAux] simp @[simp] theorem xgcdAux_fst (x y) : ∀ s t s' t', (xgcdAux x s t y s' t').1 = gcd x y := gcd.induction x y (by simp) fun x y h IH s t s' t' => by simp only [h, xgcdAux_rec, IH] rw [← gcd_rec] theorem xgcdAux_val (x y) : xgcdAux x 1 0 y 0 1 = (gcd x y, xgcd x y) := by rw [xgcd, ← xgcdAux_fst x y 1 0 0 1] theorem xgcd_val (x y) : xgcd x y = (gcdA x y, gcdB x y) := by unfold gcdA gcdB; cases xgcd x y; rfl section variable (x y : ℕ) private def P : ℕ × ℤ × ℤ → Prop | (r, s, t) => (r : ℤ) = x * s + y * t theorem xgcdAux_P {r r'} : ∀ {s t s' t'}, P x y (r, s, t) → P x y (r', s', t') → P x y (xgcdAux r s t r' s' t') := by induction r, r' using gcd.induction with | H0 => simp | H1 a b h IH => intro s t s' t' p p' rw [xgcdAux_rec h]; refine IH ?_ p; dsimp [P] at * rw [Int.emod_def]; generalize (b / a : ℤ) = k rw [p, p', Int.mul_sub, sub_add_eq_add_sub, Int.mul_sub, Int.add_mul, mul_comm k t, mul_comm k s, ← mul_assoc, ← mul_assoc, add_comm (x * s * k), ← add_sub_assoc, sub_sub] /-- **Bézout's lemma**: given `x y : ℕ`, `gcd x y = x * a + y * b`, where `a = gcd_a x y` and `b = gcd_b x y` are computed by the extended Euclidean algorithm. -/ theorem gcd_eq_gcd_ab : (gcd x y : ℤ) = x * gcdA x y + y * gcdB x y := by have := @xgcdAux_P x y x y 1 0 0 1 (by simp [P]) (by simp [P]) rwa [xgcdAux_val, xgcd_val] at this end theorem exists_mul_emod_eq_gcd {k n : ℕ} (hk : gcd n k < k) : ∃ m, n * m % k = gcd n k := by have hk' := Int.ofNat_ne_zero.2 (ne_of_gt (lt_of_le_of_lt (zero_le (gcd n k)) hk)) have key := congr_arg (fun (m : ℤ) => (m % k).toNat) (gcd_eq_gcd_ab n k) simp only at key rw [Int.add_mul_emod_self_left, ← Int.natCast_mod, Int.toNat_natCast, mod_eq_of_lt hk] at key refine ⟨(n.gcdA k % k).toNat, Eq.trans (Int.ofNat.inj ?_) key.symm⟩ rw [Int.ofNat_eq_coe, Int.natCast_mod, Int.ofNat_mul, Int.toNat_of_nonneg (Int.emod_nonneg _ hk'), Int.ofNat_eq_coe, Int.toNat_of_nonneg (Int.emod_nonneg _ hk'), Int.mul_emod, Int.emod_emod, ← Int.mul_emod] theorem exists_mul_emod_eq_one_of_coprime {k n : ℕ} (hkn : Coprime n k) (hk : 1 < k) : ∃ m, n * m % k = 1 := Exists.recOn (exists_mul_emod_eq_gcd (lt_of_le_of_lt (le_of_eq hkn) hk)) fun m hm ↦ ⟨m, hm.trans hkn⟩ end Nat /-! ### Divisibility over ℤ -/ namespace Int theorem gcd_def (i j : ℤ) : gcd i j = Nat.gcd i.natAbs j.natAbs := rfl @[simp, norm_cast] protected lemma gcd_natCast_natCast (m n : ℕ) : gcd ↑m ↑n = m.gcd n := rfl @[deprecated (since := "2024-05-25")] alias coe_nat_gcd := Int.gcd_natCast_natCast /-- The extended GCD `a` value in the equation `gcd x y = x * a + y * b`. -/ def gcdA : ℤ → ℤ → ℤ | ofNat m, n => m.gcdA n.natAbs | -[m+1], n => -m.succ.gcdA n.natAbs /-- The extended GCD `b` value in the equation `gcd x y = x * a + y * b`. -/ def gcdB : ℤ → ℤ → ℤ | m, ofNat n => m.natAbs.gcdB n | m, -[n+1] => -m.natAbs.gcdB n.succ /-- **Bézout's lemma** -/ theorem gcd_eq_gcd_ab : ∀ x y : ℤ, (gcd x y : ℤ) = x * gcdA x y + y * gcdB x y | (m : ℕ), (n : ℕ) => Nat.gcd_eq_gcd_ab _ _ | (m : ℕ), -[n+1] => show (_ : ℤ) = _ + -(n + 1) * -_ by rw [Int.neg_mul_neg]; apply Nat.gcd_eq_gcd_ab | -[m+1], (n : ℕ) => show (_ : ℤ) = -(m + 1) * -_ + _ by rw [Int.neg_mul_neg]; apply Nat.gcd_eq_gcd_ab | -[m+1], -[n+1] => show (_ : ℤ) = -(m + 1) * -_ + -(n + 1) * -_ by rw [Int.neg_mul_neg, Int.neg_mul_neg] apply Nat.gcd_eq_gcd_ab theorem lcm_def (i j : ℤ) : lcm i j = Nat.lcm (natAbs i) (natAbs j) := rfl protected theorem coe_nat_lcm (m n : ℕ) : Int.lcm ↑m ↑n = Nat.lcm m n := rfl theorem dvd_gcd {i j k : ℤ} (h1 : k ∣ i) (h2 : k ∣ j) : k ∣ gcd i j := natAbs_dvd.1 <| natCast_dvd_natCast.2 <| Nat.dvd_gcd (natAbs_dvd_natAbs.2 h1) (natAbs_dvd_natAbs.2 h2) theorem gcd_mul_lcm (i j : ℤ) : gcd i j * lcm i j = natAbs (i * j) := by rw [Int.gcd, Int.lcm, Nat.gcd_mul_lcm, natAbs_mul] theorem gcd_comm (i j : ℤ) : gcd i j = gcd j i := Nat.gcd_comm _ _ theorem gcd_assoc (i j k : ℤ) : gcd (gcd i j) k = gcd i (gcd j k) := Nat.gcd_assoc _ _ _ @[simp] theorem gcd_self (i : ℤ) : gcd i i = natAbs i := by simp [gcd] @[simp] theorem gcd_zero_left (i : ℤ) : gcd 0 i = natAbs i := by simp [gcd] @[simp] theorem gcd_zero_right (i : ℤ) : gcd i 0 = natAbs i := by simp [gcd] theorem gcd_mul_left (i j k : ℤ) : gcd (i * j) (i * k) = natAbs i * gcd j k := by rw [Int.gcd, Int.gcd, natAbs_mul, natAbs_mul] apply Nat.gcd_mul_left theorem gcd_mul_right (i j k : ℤ) : gcd (i * j) (k * j) = gcd i k * natAbs j := by rw [Int.gcd, Int.gcd, natAbs_mul, natAbs_mul] apply Nat.gcd_mul_right theorem gcd_pos_of_ne_zero_left {i : ℤ} (j : ℤ) (hi : i ≠ 0) : 0 < gcd i j := Nat.gcd_pos_of_pos_left _ <| natAbs_pos.2 hi theorem gcd_pos_of_ne_zero_right (i : ℤ) {j : ℤ} (hj : j ≠ 0) : 0 < gcd i j := Nat.gcd_pos_of_pos_right _ <| natAbs_pos.2 hj theorem gcd_eq_zero_iff {i j : ℤ} : gcd i j = 0 ↔ i = 0 ∧ j = 0 := by rw [gcd, Nat.gcd_eq_zero_iff, natAbs_eq_zero, natAbs_eq_zero] theorem gcd_pos_iff {i j : ℤ} : 0 < gcd i j ↔ i ≠ 0 ∨ j ≠ 0 := Nat.pos_iff_ne_zero.trans <| gcd_eq_zero_iff.not.trans not_and_or theorem gcd_div {i j k : ℤ} (H1 : k ∣ i) (H2 : k ∣ j) : gcd (i / k) (j / k) = gcd i j / natAbs k := by rw [gcd, natAbs_ediv i k H1, natAbs_ediv j k H2] exact Nat.gcd_div (natAbs_dvd_natAbs.mpr H1) (natAbs_dvd_natAbs.mpr H2) theorem gcd_div_gcd_div_gcd {i j : ℤ} (H : 0 < gcd i j) : gcd (i / gcd i j) (j / gcd i j) = 1 := by rw [gcd_div gcd_dvd_left gcd_dvd_right, natAbs_ofNat, Nat.div_self H] theorem gcd_dvd_gcd_of_dvd_left {i k : ℤ} (j : ℤ) (H : i ∣ k) : gcd i j ∣ gcd k j := Int.natCast_dvd_natCast.1 <| dvd_gcd (gcd_dvd_left.trans H) gcd_dvd_right theorem gcd_dvd_gcd_of_dvd_right {i k : ℤ} (j : ℤ) (H : i ∣ k) : gcd j i ∣ gcd j k := Int.natCast_dvd_natCast.1 <| dvd_gcd gcd_dvd_left (gcd_dvd_right.trans H) theorem gcd_dvd_gcd_mul_left (i j k : ℤ) : gcd i j ∣ gcd (k * i) j := gcd_dvd_gcd_of_dvd_left _ (dvd_mul_left _ _) theorem gcd_dvd_gcd_mul_right (i j k : ℤ) : gcd i j ∣ gcd (i * k) j := gcd_dvd_gcd_of_dvd_left _ (dvd_mul_right _ _) theorem gcd_dvd_gcd_mul_left_right (i j k : ℤ) : gcd i j ∣ gcd i (k * j) := gcd_dvd_gcd_of_dvd_right _ (dvd_mul_left _ _) theorem gcd_dvd_gcd_mul_right_right (i j k : ℤ) : gcd i j ∣ gcd i (j * k) := gcd_dvd_gcd_of_dvd_right _ (dvd_mul_right _ _) /-- If `gcd a (m * n) = 1`, then `gcd a m = 1`. -/ theorem gcd_eq_one_of_gcd_mul_right_eq_one_left {a : ℤ} {m n : ℕ} (h : a.gcd (m * n) = 1) : a.gcd m = 1 := Nat.dvd_one.mp <| h ▸ gcd_dvd_gcd_mul_right_right a m n /-- If `gcd a (m * n) = 1`, then `gcd a n = 1`. -/ theorem gcd_eq_one_of_gcd_mul_right_eq_one_right {a : ℤ} {m n : ℕ} (h : a.gcd (m * n) = 1) : a.gcd n = 1 := Nat.dvd_one.mp <| h ▸ gcd_dvd_gcd_mul_left_right a n m theorem gcd_eq_left {i j : ℤ} (H : i ∣ j) : gcd i j = natAbs i := Nat.dvd_antisymm (Nat.gcd_dvd_left _ _) (Nat.dvd_gcd dvd_rfl (natAbs_dvd_natAbs.mpr H)) theorem gcd_eq_right {i j : ℤ} (H : j ∣ i) : gcd i j = natAbs j := by rw [gcd_comm, gcd_eq_left H] theorem ne_zero_of_gcd {x y : ℤ} (hc : gcd x y ≠ 0) : x ≠ 0 ∨ y ≠ 0 := by contrapose! hc rw [hc.left, hc.right, gcd_zero_right, natAbs_zero] theorem exists_gcd_one {m n : ℤ} (H : 0 < gcd m n) : ∃ m' n' : ℤ, gcd m' n' = 1 ∧ m = m' * gcd m n ∧ n = n' * gcd m n := ⟨_, _, gcd_div_gcd_div_gcd H, (Int.ediv_mul_cancel gcd_dvd_left).symm, (Int.ediv_mul_cancel gcd_dvd_right).symm⟩ theorem exists_gcd_one' {m n : ℤ} (H : 0 < gcd m n) : ∃ (g : ℕ) (m' n' : ℤ), 0 < g ∧ gcd m' n' = 1 ∧ m = m' * g ∧ n = n' * g := let ⟨m', n', h⟩ := exists_gcd_one H ⟨_, m', n', H, h⟩ theorem pow_dvd_pow_iff {m n : ℤ} {k : ℕ} (k0 : k ≠ 0) : m ^ k ∣ n ^ k ↔ m ∣ n := by refine ⟨fun h => ?_, fun h => pow_dvd_pow_of_dvd h _⟩ rwa [← natAbs_dvd_natAbs, ← Nat.pow_dvd_pow_iff k0, ← Int.natAbs_pow, ← Int.natAbs_pow, natAbs_dvd_natAbs] theorem gcd_dvd_iff {a b : ℤ} {n : ℕ} : gcd a b ∣ n ↔ ∃ x y : ℤ, ↑n = a * x + b * y := by constructor · intro h rw [← Nat.mul_div_cancel' h, Int.ofNat_mul, gcd_eq_gcd_ab, Int.add_mul, mul_assoc, mul_assoc] exact ⟨_, _, rfl⟩ · rintro ⟨x, y, h⟩ rw [← Int.natCast_dvd_natCast, h] exact Int.dvd_add (dvd_mul_of_dvd_left gcd_dvd_left _) (dvd_mul_of_dvd_left gcd_dvd_right y) theorem gcd_greatest {a b d : ℤ} (hd_pos : 0 ≤ d) (hda : d ∣ a) (hdb : d ∣ b) (hd : ∀ e : ℤ, e ∣ a → e ∣ b → e ∣ d) : d = gcd a b := dvd_antisymm hd_pos (ofNat_zero_le (gcd a b)) (dvd_gcd hda hdb) (hd _ gcd_dvd_left gcd_dvd_right) /-- Euclid's lemma: if `a ∣ b * c` and `gcd a c = 1` then `a ∣ b`. Compare with `IsCoprime.dvd_of_dvd_mul_left` and `UniqueFactorizationMonoid.dvd_of_dvd_mul_left_of_no_prime_factors` -/ theorem dvd_of_dvd_mul_left_of_gcd_one {a b c : ℤ} (habc : a ∣ b * c) (hab : gcd a c = 1) : a ∣ b := by have := gcd_eq_gcd_ab a c simp only [hab, Int.ofNat_zero, Int.ofNat_succ, zero_add] at this have : b * a * gcdA a c + b * c * gcdB a c = b := by simp [mul_assoc, ← Int.mul_add, ← this] rw [← this] exact Int.dvd_add (dvd_mul_of_dvd_left (dvd_mul_left a b) _) (dvd_mul_of_dvd_left habc _) /-- Euclid's lemma: if `a ∣ b * c` and `gcd a b = 1` then `a ∣ c`. Compare with `IsCoprime.dvd_of_dvd_mul_right` and `UniqueFactorizationMonoid.dvd_of_dvd_mul_right_of_no_prime_factors` -/ theorem dvd_of_dvd_mul_right_of_gcd_one {a b c : ℤ} (habc : a ∣ b * c) (hab : gcd a b = 1) : a ∣ c := by rw [mul_comm] at habc exact dvd_of_dvd_mul_left_of_gcd_one habc hab /-- For nonzero integers `a` and `b`, `gcd a b` is the smallest positive natural number that can be written in the form `a * x + b * y` for some pair of integers `x` and `y` -/ theorem gcd_least_linear {a b : ℤ} (ha : a ≠ 0) : IsLeast { n : ℕ | 0 < n ∧ ∃ x y : ℤ, ↑n = a * x + b * y } (a.gcd b) := by simp_rw [← gcd_dvd_iff] constructor · simpa [and_true_iff, dvd_refl, Set.mem_setOf_eq] using gcd_pos_of_ne_zero_left b ha · simp only [lowerBounds, and_imp, Set.mem_setOf_eq] exact fun n hn_pos hn => Nat.le_of_dvd hn_pos hn /-! ### lcm -/ theorem lcm_comm (i j : ℤ) : lcm i j = lcm j i := by rw [Int.lcm, Int.lcm] exact Nat.lcm_comm _ _ theorem lcm_assoc (i j k : ℤ) : lcm (lcm i j) k = lcm i (lcm j k) := by rw [Int.lcm, Int.lcm, Int.lcm, Int.lcm, natAbs_ofNat, natAbs_ofNat] apply Nat.lcm_assoc @[simp] theorem lcm_zero_left (i : ℤ) : lcm 0 i = 0 := by rw [Int.lcm] apply Nat.lcm_zero_left @[simp] theorem lcm_zero_right (i : ℤ) : lcm i 0 = 0 := by rw [Int.lcm] apply Nat.lcm_zero_right @[simp] theorem lcm_one_left (i : ℤ) : lcm 1 i = natAbs i := by rw [Int.lcm] apply Nat.lcm_one_left @[simp] theorem lcm_one_right (i : ℤ) : lcm i 1 = natAbs i := by rw [Int.lcm] apply Nat.lcm_one_right theorem lcm_dvd {i j k : ℤ} : i ∣ k → j ∣ k → (lcm i j : ℤ) ∣ k := by rw [Int.lcm] intro hi hj exact natCast_dvd.mpr (Nat.lcm_dvd (natAbs_dvd_natAbs.mpr hi) (natAbs_dvd_natAbs.mpr hj)) theorem lcm_mul_left {m n k : ℤ} : (m * n).lcm (m * k) = natAbs m * n.lcm k := by simp_rw [Int.lcm, natAbs_mul, Nat.lcm_mul_left] theorem lcm_mul_right {m n k : ℤ} : (m * n).lcm (k * n) = m.lcm k * natAbs n := by simp_rw [Int.lcm, natAbs_mul, Nat.lcm_mul_right] end Int @[to_additive gcd_nsmul_eq_zero] theorem pow_gcd_eq_one {M : Type*} [Monoid M] (x : M) {m n : ℕ} (hm : x ^ m = 1) (hn : x ^ n = 1) : x ^ m.gcd n = 1 := by rcases m with (rfl | m); · simp [hn] obtain ⟨y, rfl⟩ := isUnit_ofPowEqOne hm m.succ_ne_zero rw [← Units.val_pow_eq_pow_val, ← Units.val_one (α := M), ← zpow_natCast, ← Units.ext_iff] at * rw [Nat.gcd_eq_gcd_ab, zpow_add, zpow_mul, zpow_mul, hn, hm, one_zpow, one_zpow, one_mul] variable {α : Type*} section GroupWithZero variable [GroupWithZero α] {a b : α} {m n : ℕ} protected lemma Commute.pow_eq_pow_iff_of_coprime (hab : Commute a b) (hmn : m.Coprime n) : a ^ m = b ^ n ↔ ∃ c, a = c ^ n ∧ b = c ^ m := by refine ⟨fun h ↦ ?_, by rintro ⟨c, rfl, rfl⟩; rw [← pow_mul, ← pow_mul']⟩ by_cases m = 0; · aesop by_cases n = 0; · aesop by_cases hb : b = 0; · exact ⟨0, by aesop⟩ by_cases ha : a = 0; · exact ⟨0, by have := h.symm; aesop⟩ refine ⟨a ^ Nat.gcdB m n * b ^ Nat.gcdA m n, ?_, ?_⟩ <;> · refine (pow_one _).symm.trans ?_ conv_lhs => rw [← zpow_natCast, ← hmn, Nat.gcd_eq_gcd_ab] simp only [zpow_add₀ ha, zpow_add₀ hb, ← zpow_natCast, (hab.zpow_zpow₀ _ _).mul_zpow, ← zpow_mul, mul_comm (Nat.gcdB m n), mul_comm (Nat.gcdA m n)] simp only [zpow_mul, zpow_natCast, h] exact ((Commute.pow_pow (by aesop) _ _).zpow_zpow₀ _ _).symm end GroupWithZero section CommGroupWithZero variable [CommGroupWithZero α] {a b : α} {m n : ℕ} lemma pow_eq_pow_iff_of_coprime (hmn : m.Coprime n) : a ^ m = b ^ n ↔ ∃ c, a = c ^ n ∧ b = c ^ m := (Commute.all _ _).pow_eq_pow_iff_of_coprime hmn lemma pow_mem_range_pow_of_coprime (hmn : m.Coprime n) (a : α) : a ^ m ∈ Set.range (· ^ n : α → α) ↔ a ∈ Set.range (· ^ n : α → α) := by simp [pow_eq_pow_iff_of_coprime hmn.symm]; aesop end CommGroupWithZero
Data\Int\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.Algebra.CharZero.Lemmas import Mathlib.Algebra.Order.Group.Int import Mathlib.Algebra.Ring.Int import Mathlib.Order.Interval.Finset.Basic /-! # Finite intervals of integers This file proves that `ℤ` is a `LocallyFiniteOrder` and calculates the cardinality of its intervals as finsets and fintypes. -/ open Finset Int namespace Int instance instLocallyFiniteOrder : LocallyFiniteOrder ℤ where finsetIcc a b := (Finset.range (b + 1 - a).toNat).map <| Nat.castEmbedding.trans <| addLeftEmbedding a finsetIco a b := (Finset.range (b - a).toNat).map <| Nat.castEmbedding.trans <| addLeftEmbedding a finsetIoc a b := (Finset.range (b - a).toNat).map <| Nat.castEmbedding.trans <| addLeftEmbedding (a + 1) finsetIoo a b := (Finset.range (b - a - 1).toNat).map <| Nat.castEmbedding.trans <| addLeftEmbedding (a + 1) finset_mem_Icc a b x := by simp_rw [mem_map, mem_range, Int.lt_toNat, Function.Embedding.trans_apply, Nat.castEmbedding_apply, addLeftEmbedding_apply] constructor · rintro ⟨a, h, rfl⟩ rw [lt_sub_iff_add_lt, Int.lt_add_one_iff, add_comm] at h exact ⟨Int.le.intro a rfl, h⟩ · rintro ⟨ha, hb⟩ use (x - a).toNat rw [← lt_add_one_iff] at hb rw [toNat_sub_of_le ha] exact ⟨sub_lt_sub_right hb _, add_sub_cancel _ _⟩ finset_mem_Ico a b x := by simp_rw [mem_map, mem_range, Int.lt_toNat, Function.Embedding.trans_apply, Nat.castEmbedding_apply, addLeftEmbedding_apply] constructor · rintro ⟨a, h, rfl⟩ exact ⟨Int.le.intro a rfl, lt_sub_iff_add_lt'.mp h⟩ · rintro ⟨ha, hb⟩ use (x - a).toNat rw [toNat_sub_of_le ha] exact ⟨sub_lt_sub_right hb _, add_sub_cancel _ _⟩ finset_mem_Ioc a b x := by simp_rw [mem_map, mem_range, Int.lt_toNat, Function.Embedding.trans_apply, Nat.castEmbedding_apply, addLeftEmbedding_apply] constructor · rintro ⟨a, h, rfl⟩ rw [← add_one_le_iff, le_sub_iff_add_le', add_comm _ (1 : ℤ), ← add_assoc] at h exact ⟨Int.le.intro a rfl, h⟩ · rintro ⟨ha, hb⟩ use (x - (a + 1)).toNat rw [toNat_sub_of_le ha, ← add_one_le_iff, sub_add, add_sub_cancel_right] exact ⟨sub_le_sub_right hb _, add_sub_cancel _ _⟩ finset_mem_Ioo a b x := by simp_rw [mem_map, mem_range, Int.lt_toNat, Function.Embedding.trans_apply, Nat.castEmbedding_apply, addLeftEmbedding_apply] constructor · rintro ⟨a, h, rfl⟩ rw [sub_sub, lt_sub_iff_add_lt'] at h exact ⟨Int.le.intro a rfl, h⟩ · rintro ⟨ha, hb⟩ use (x - (a + 1)).toNat rw [toNat_sub_of_le ha, sub_sub] exact ⟨sub_lt_sub_right hb _, add_sub_cancel _ _⟩ variable (a b : ℤ) theorem Icc_eq_finset_map : Icc a b = (Finset.range (b + 1 - a).toNat).map (Nat.castEmbedding.trans <| addLeftEmbedding a) := rfl theorem Ico_eq_finset_map : Ico a b = (Finset.range (b - a).toNat).map (Nat.castEmbedding.trans <| addLeftEmbedding a) := rfl theorem Ioc_eq_finset_map : Ioc a b = (Finset.range (b - a).toNat).map (Nat.castEmbedding.trans <| addLeftEmbedding (a + 1)) := rfl theorem Ioo_eq_finset_map : Ioo a b = (Finset.range (b - a - 1).toNat).map (Nat.castEmbedding.trans <| addLeftEmbedding (a + 1)) := rfl theorem uIcc_eq_finset_map : uIcc a b = (range (max a b + 1 - min a b).toNat).map (Nat.castEmbedding.trans <| addLeftEmbedding <| min a b) := rfl @[simp] theorem card_Icc : (Icc a b).card = (b + 1 - a).toNat := (card_map _).trans <| card_range _ @[simp] theorem card_Ico : (Ico a b).card = (b - a).toNat := (card_map _).trans <| card_range _ @[simp] theorem card_Ioc : (Ioc a b).card = (b - a).toNat := (card_map _).trans <| card_range _ @[simp] theorem card_Ioo : (Ioo a b).card = (b - a - 1).toNat := (card_map _).trans <| card_range _ @[simp] theorem card_uIcc : (uIcc a b).card = (b - a).natAbs + 1 := (card_map _).trans <| Int.ofNat.inj <| by -- Porting note (#11215): TODO: Restore `Int.ofNat.inj` and remove the `change` change ((↑) : ℕ → ℤ) _ = ((↑) : ℕ → ℤ) _ rw [card_range, sup_eq_max, inf_eq_min, Int.toNat_of_nonneg (sub_nonneg_of_le <| le_add_one min_le_max), Int.ofNat_add, Int.natCast_natAbs, add_comm, add_sub_assoc, max_sub_min_eq_abs, add_comm, Int.ofNat_one] theorem card_Icc_of_le (h : a ≤ b + 1) : ((Icc a b).card : ℤ) = b + 1 - a := by rw [card_Icc, toNat_sub_of_le h] theorem card_Ico_of_le (h : a ≤ b) : ((Ico a b).card : ℤ) = b - a := by rw [card_Ico, toNat_sub_of_le h] theorem card_Ioc_of_le (h : a ≤ b) : ((Ioc a b).card : ℤ) = b - a := by rw [card_Ioc, toNat_sub_of_le h] theorem card_Ioo_of_lt (h : a < b) : ((Ioo a b).card : ℤ) = b - a - 1 := by rw [card_Ioo, sub_sub, toNat_sub_of_le h] -- Porting note (#11119): removed `simp` attribute because `simpNF` says it can prove it theorem card_fintype_Icc : Fintype.card (Set.Icc a b) = (b + 1 - a).toNat := by rw [← card_Icc, Fintype.card_ofFinset] -- Porting note (#11119): removed `simp` attribute because `simpNF` says it can prove it theorem card_fintype_Ico : Fintype.card (Set.Ico a b) = (b - a).toNat := by rw [← card_Ico, Fintype.card_ofFinset] -- Porting note (#11119): removed `simp` attribute because `simpNF` says it can prove it theorem card_fintype_Ioc : Fintype.card (Set.Ioc a b) = (b - a).toNat := by rw [← card_Ioc, Fintype.card_ofFinset] -- Porting note (#11119): removed `simp` attribute because `simpNF` says it can prove it theorem card_fintype_Ioo : Fintype.card (Set.Ioo a b) = (b - a - 1).toNat := by rw [← card_Ioo, Fintype.card_ofFinset] theorem card_fintype_uIcc : Fintype.card (Set.uIcc a b) = (b - a).natAbs + 1 := by rw [← card_uIcc, Fintype.card_ofFinset] theorem card_fintype_Icc_of_le (h : a ≤ b + 1) : (Fintype.card (Set.Icc a b) : ℤ) = b + 1 - a := by rw [card_fintype_Icc, toNat_sub_of_le h] theorem card_fintype_Ico_of_le (h : a ≤ b) : (Fintype.card (Set.Ico a b) : ℤ) = b - a := by rw [card_fintype_Ico, toNat_sub_of_le h] theorem card_fintype_Ioc_of_le (h : a ≤ b) : (Fintype.card (Set.Ioc a b) : ℤ) = b - a := by rw [card_fintype_Ioc, toNat_sub_of_le h] theorem card_fintype_Ioo_of_lt (h : a < b) : (Fintype.card (Set.Ioo a b) : ℤ) = b - a - 1 := by rw [card_fintype_Ioo, sub_sub, toNat_sub_of_le h] theorem image_Ico_emod (n a : ℤ) (h : 0 ≤ a) : (Ico n (n + a)).image (· % a) = Ico 0 a := by obtain rfl | ha := eq_or_lt_of_le h · simp ext i simp only [mem_image, mem_range, mem_Ico] constructor · rintro ⟨i, _, rfl⟩ exact ⟨emod_nonneg i ha.ne', emod_lt_of_pos i ha⟩ intro hia have hn := Int.emod_add_ediv n a obtain hi | hi := lt_or_le i (n % a) · refine ⟨i + a * (n / a + 1), ⟨?_, ?_⟩, ?_⟩ · rw [add_comm (n / a), mul_add, mul_one, ← add_assoc] refine hn.symm.le.trans (add_le_add_right ?_ _) simpa only [zero_add] using add_le_add hia.left (Int.emod_lt_of_pos n ha).le · refine lt_of_lt_of_le (add_lt_add_right hi (a * (n / a + 1))) ?_ rw [mul_add, mul_one, ← add_assoc, hn] · rw [Int.add_mul_emod_self_left, Int.emod_eq_of_lt hia.left hia.right] · refine ⟨i + a * (n / a), ⟨?_, ?_⟩, ?_⟩ · exact hn.symm.le.trans (add_le_add_right hi _) · rw [add_comm n a] refine add_lt_add_of_lt_of_le hia.right (le_trans ?_ hn.le) simp only [zero_le, le_add_iff_nonneg_left] exact Int.emod_nonneg n (ne_of_gt ha) · rw [Int.add_mul_emod_self_left, Int.emod_eq_of_lt hia.left hia.right] end Int
Data\Int\LeastGreatest.lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Mario Carneiro -/ import Mathlib.Algebra.Order.Ring.Int import Mathlib.Data.Nat.Find /-! # Least upper bound and greatest lower bound properties for integers In this file we prove that a bounded above nonempty set of integers has the greatest element, and a counterpart of this statement for the least element. ## Main definitions * `Int.leastOfBdd`: if `P : ℤ → Prop` is a decidable predicate, `b` is a lower bound of the set `{m | P m}`, and there exists `m : ℤ` such that `P m` (this time, no witness is required), then `Int.leastOfBdd` returns the least number `m` such that `P m`, together with proofs of `P m` and of the minimality. This definition is computable and does not rely on the axiom of choice. * `Int.greatestOfBdd`: a similar definition with all inequalities reversed. ## Main statements * `Int.exists_least_of_bdd`: if `P : ℤ → Prop` is a predicate such that the set `{m : P m}` is bounded below and nonempty, then this set has the least element. This lemma uses classical logic to avoid assumption `[DecidablePred P]`. See `Int.leastOfBdd` for a constructive counterpart. * `Int.coe_leastOfBdd_eq`: `(Int.leastOfBdd b Hb Hinh : ℤ)` does not depend on `b`. * `Int.exists_greatest_of_bdd`, `Int.coe_greatest_of_bdd_eq`: versions of the above lemmas with all inequalities reversed. ## Tags integer numbers, least element, greatest element -/ namespace Int /-- A computable version of `exists_least_of_bdd`: given a decidable predicate on the integers, with an explicit lower bound and a proof that it is somewhere true, return the least value for which the predicate is true. -/ def leastOfBdd {P : ℤ → Prop} [DecidablePred P] (b : ℤ) (Hb : ∀ z : ℤ, P z → b ≤ z) (Hinh : ∃ z : ℤ, P z) : { lb : ℤ // P lb ∧ ∀ z : ℤ, P z → lb ≤ z } := have EX : ∃ n : ℕ, P (b + n) := let ⟨elt, Helt⟩ := Hinh match elt, le.dest (Hb _ Helt), Helt with | _, ⟨n, rfl⟩, Hn => ⟨n, Hn⟩ ⟨b + (Nat.find EX : ℤ), Nat.find_spec EX, fun z h => match z, le.dest (Hb _ h), h with | _, ⟨_, rfl⟩, h => add_le_add_left (Int.ofNat_le.2 <| Nat.find_min' _ h) _⟩ /-- If `P : ℤ → Prop` is a predicate such that the set `{m : P m}` is bounded below and nonempty, then this set has the least element. This lemma uses classical logic to avoid assumption `[DecidablePred P]`. See `Int.leastOfBdd` for a constructive counterpart. -/ theorem exists_least_of_bdd {P : ℤ → Prop} (Hbdd : ∃ b : ℤ , ∀ z : ℤ , P z → b ≤ z) (Hinh : ∃ z : ℤ , P z) : ∃ lb : ℤ , P lb ∧ ∀ z : ℤ , P z → lb ≤ z := by classical let ⟨b , Hb⟩ := Hbdd let ⟨lb , H⟩ := leastOfBdd b Hb Hinh exact ⟨lb , H⟩ theorem coe_leastOfBdd_eq {P : ℤ → Prop} [DecidablePred P] {b b' : ℤ} (Hb : ∀ z : ℤ, P z → b ≤ z) (Hb' : ∀ z : ℤ, P z → b' ≤ z) (Hinh : ∃ z : ℤ, P z) : (leastOfBdd b Hb Hinh : ℤ) = leastOfBdd b' Hb' Hinh := by rcases leastOfBdd b Hb Hinh with ⟨n, hn, h2n⟩ rcases leastOfBdd b' Hb' Hinh with ⟨n', hn', h2n'⟩ exact le_antisymm (h2n _ hn') (h2n' _ hn) /-- A computable version of `exists_greatest_of_bdd`: given a decidable predicate on the integers, with an explicit upper bound and a proof that it is somewhere true, return the greatest value for which the predicate is true. -/ def greatestOfBdd {P : ℤ → Prop} [DecidablePred P] (b : ℤ) (Hb : ∀ z : ℤ, P z → z ≤ b) (Hinh : ∃ z : ℤ, P z) : { ub : ℤ // P ub ∧ ∀ z : ℤ, P z → z ≤ ub } := have Hbdd' : ∀ z : ℤ, P (-z) → -b ≤ z := fun z h => neg_le.1 (Hb _ h) have Hinh' : ∃ z : ℤ, P (-z) := let ⟨elt, Helt⟩ := Hinh ⟨-elt, by rw [neg_neg]; exact Helt⟩ let ⟨lb, Plb, al⟩ := leastOfBdd (-b) Hbdd' Hinh' ⟨-lb, Plb, fun z h => le_neg.1 <| al _ <| by rwa [neg_neg]⟩ /-- If `P : ℤ → Prop` is a predicate such that the set `{m : P m}` is bounded above and nonempty, then this set has the greatest element. This lemma uses classical logic to avoid assumption `[DecidablePred P]`. See `Int.greatestOfBdd` for a constructive counterpart. -/ theorem exists_greatest_of_bdd {P : ℤ → Prop} (Hbdd : ∃ b : ℤ , ∀ z : ℤ , P z → z ≤ b) (Hinh : ∃ z : ℤ , P z) : ∃ ub : ℤ , P ub ∧ ∀ z : ℤ , P z → z ≤ ub := by classical let ⟨b, Hb⟩ := Hbdd let ⟨lb, H⟩ := greatestOfBdd b Hb Hinh exact ⟨lb, H⟩ theorem coe_greatestOfBdd_eq {P : ℤ → Prop} [DecidablePred P] {b b' : ℤ} (Hb : ∀ z : ℤ, P z → z ≤ b) (Hb' : ∀ z : ℤ, P z → z ≤ b') (Hinh : ∃ z : ℤ, P z) : (greatestOfBdd b Hb Hinh : ℤ) = greatestOfBdd b' Hb' Hinh := by rcases greatestOfBdd b Hb Hinh with ⟨n, hn, h2n⟩ rcases greatestOfBdd b' Hb' Hinh with ⟨n', hn', h2n'⟩ exact le_antisymm (h2n' _ hn) (h2n _ hn') end Int
Data\Int\Lemmas.lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad -/ import Mathlib.Data.Int.Bitwise import Mathlib.Data.Int.Order.Lemmas import Mathlib.Data.Set.Function import Mathlib.Order.Interval.Set.Basic /-! # Miscellaneous lemmas about the integers This file contains lemmas about integers, which require further imports than `Data.Int.Basic` or `Data.Int.Order`. -/ open Nat namespace Int theorem le_natCast_sub (m n : ℕ) : (m - n : ℤ) ≤ ↑(m - n : ℕ) := by by_cases h : m ≥ n · exact le_of_eq (Int.ofNat_sub h).symm · simp [le_of_not_ge h, ofNat_le] /-! ### `succ` and `pred` -/ -- Porting note (#10618): simp can prove this @[simp] theorem succ_natCast_pos (n : ℕ) : 0 < (n : ℤ) + 1 := lt_add_one_iff.mpr (by simp) /-! ### `natAbs` -/ variable {a b : ℤ} {n : ℕ} theorem natAbs_eq_iff_sq_eq {a b : ℤ} : a.natAbs = b.natAbs ↔ a ^ 2 = b ^ 2 := by rw [sq, sq] exact natAbs_eq_iff_mul_self_eq theorem natAbs_lt_iff_sq_lt {a b : ℤ} : a.natAbs < b.natAbs ↔ a ^ 2 < b ^ 2 := by rw [sq, sq] exact natAbs_lt_iff_mul_self_lt theorem natAbs_le_iff_sq_le {a b : ℤ} : a.natAbs ≤ b.natAbs ↔ a ^ 2 ≤ b ^ 2 := by rw [sq, sq] exact natAbs_le_iff_mul_self_le theorem natAbs_inj_of_nonneg_of_nonneg {a b : ℤ} (ha : 0 ≤ a) (hb : 0 ≤ b) : natAbs a = natAbs b ↔ a = b := by rw [← sq_eq_sq ha hb, ← natAbs_eq_iff_sq_eq] theorem natAbs_inj_of_nonpos_of_nonpos {a b : ℤ} (ha : a ≤ 0) (hb : b ≤ 0) : natAbs a = natAbs b ↔ a = b := by simpa only [Int.natAbs_neg, neg_inj] using natAbs_inj_of_nonneg_of_nonneg (neg_nonneg_of_nonpos ha) (neg_nonneg_of_nonpos hb) theorem natAbs_inj_of_nonneg_of_nonpos {a b : ℤ} (ha : 0 ≤ a) (hb : b ≤ 0) : natAbs a = natAbs b ↔ a = -b := by simpa only [Int.natAbs_neg] using natAbs_inj_of_nonneg_of_nonneg ha (neg_nonneg_of_nonpos hb) theorem natAbs_inj_of_nonpos_of_nonneg {a b : ℤ} (ha : a ≤ 0) (hb : 0 ≤ b) : natAbs a = natAbs b ↔ -a = b := by simpa only [Int.natAbs_neg] using natAbs_inj_of_nonneg_of_nonneg (neg_nonneg_of_nonpos ha) hb /-- A specialization of `abs_sub_le_of_nonneg_of_le` for working with the signed subtraction of natural numbers. -/ theorem natAbs_coe_sub_coe_le_of_le {a b n : ℕ} (a_le_n : a ≤ n) (b_le_n : b ≤ n) : natAbs (a - b : ℤ) ≤ n := by rw [← Nat.cast_le (α := ℤ), natCast_natAbs] exact abs_sub_le_of_nonneg_of_le (ofNat_nonneg a) (ofNat_le.mpr a_le_n) (ofNat_nonneg b) (ofNat_le.mpr b_le_n) /-- A specialization of `abs_sub_lt_of_nonneg_of_lt` for working with the signed subtraction of natural numbers. -/ theorem natAbs_coe_sub_coe_lt_of_lt {a b n : ℕ} (a_lt_n : a < n) (b_lt_n : b < n) : natAbs (a - b : ℤ) < n := by rw [← Nat.cast_lt (α := ℤ), natCast_natAbs] exact abs_sub_lt_of_nonneg_of_lt (ofNat_nonneg a) (ofNat_lt.mpr a_lt_n) (ofNat_nonneg b) (ofNat_lt.mpr b_lt_n) section Intervals open Set theorem strictMonoOn_natAbs : StrictMonoOn natAbs (Ici 0) := fun _ ha _ _ hab => natAbs_lt_natAbs_of_nonneg_of_lt ha hab theorem strictAntiOn_natAbs : StrictAntiOn natAbs (Iic 0) := fun a _ b hb hab => by simpa [Int.natAbs_neg] using natAbs_lt_natAbs_of_nonneg_of_lt (Right.nonneg_neg_iff.mpr hb) (neg_lt_neg_iff.mpr hab) theorem injOn_natAbs_Ici : InjOn natAbs (Ici 0) := strictMonoOn_natAbs.injOn theorem injOn_natAbs_Iic : InjOn natAbs (Iic 0) := strictAntiOn_natAbs.injOn end Intervals /-! ### `toNat` -/ theorem toNat_of_nonpos : ∀ {z : ℤ}, z ≤ 0 → z.toNat = 0 | 0, _ => rfl | (n + 1 : ℕ), h => (h.not_lt (by simp)).elim | -[n+1], _ => rfl /-! ### bitwise ops This lemma is orphaned from `Data.Int.Bitwise` as it also requires material from `Data.Int.Order`. -/ attribute [local simp] Int.zero_div @[simp] theorem div2_bit (b n) : div2 (bit b n) = n := by rw [bit_val, div2_val, add_comm, Int.add_mul_ediv_left, (_ : (_ / 2 : ℤ) = 0), zero_add] cases b · decide · show ofNat _ = _ rw [Nat.div_eq_of_lt] <;> simp · decide @[deprecated (since := "2024-04-02")] alias le_coe_nat_sub := le_natCast_sub @[deprecated (since := "2024-04-02")] alias succ_coe_nat_pos := succ_natCast_pos @[deprecated (since := "2024-04-02")] alias coe_natAbs := natCast_natAbs @[deprecated (since := "2024-04-02")] alias coe_nat_eq_zero := natCast_eq_zero @[deprecated (since := "2024-04-02")] alias coe_nat_ne_zero := natCast_ne_zero @[deprecated (since := "2024-04-02")] alias coe_nat_ne_zero_iff_pos := natCast_ne_zero_iff_pos @[deprecated (since := "2024-04-02")] alias abs_coe_nat := abs_natCast @[deprecated (since := "2024-04-02")] alias coe_nat_nonpos_iff := natCast_nonpos_iff end Int
Data\Int\Log.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.Order.Floor import Mathlib.Algebra.Order.Field.Power import Mathlib.Data.Nat.Log /-! # Integer logarithms in a field with respect to a natural base This file defines two `ℤ`-valued analogs of the logarithm of `r : R` with base `b : ℕ`: * `Int.log b r`: Lower logarithm, or floor **log**. Greatest `k` such that `↑b^k ≤ r`. * `Int.clog b r`: Upper logarithm, or **c**eil **log**. Least `k` such that `r ≤ ↑b^k`. Note that `Int.log` gives the position of the left-most non-zero digit: ```lean #eval (Int.log 10 (0.09 : ℚ), Int.log 10 (0.10 : ℚ), Int.log 10 (0.11 : ℚ)) -- (-2, -1, -1) #eval (Int.log 10 (9 : ℚ), Int.log 10 (10 : ℚ), Int.log 10 (11 : ℚ)) -- (0, 1, 1) ``` which means it can be used for computing digit expansions ```lean import Data.Fin.VecNotation import Mathlib.Data.Rat.Floor def digits (b : ℕ) (q : ℚ) (n : ℕ) : ℕ := ⌊q * ((b : ℚ) ^ (n - Int.log b q))⌋₊ % b #eval digits 10 (1/7) ∘ ((↑) : Fin 8 → ℕ) -- ![1, 4, 2, 8, 5, 7, 1, 4] ``` ## Main results * For `Int.log`: * `Int.zpow_log_le_self`, `Int.lt_zpow_succ_log_self`: the bounds formed by `Int.log`, `(b : R) ^ log b r ≤ r < (b : R) ^ (log b r + 1)`. * `Int.zpow_log_gi`: the galois coinsertion between `zpow` and `Int.log`. * For `Int.clog`: * `Int.zpow_pred_clog_lt_self`, `Int.self_le_zpow_clog`: the bounds formed by `Int.clog`, `(b : R) ^ (clog b r - 1) < r ≤ (b : R) ^ clog b r`. * `Int.clog_zpow_gi`: the galois insertion between `Int.clog` and `zpow`. * `Int.neg_log_inv_eq_clog`, `Int.neg_clog_inv_eq_log`: the link between the two definitions. -/ variable {R : Type*} [LinearOrderedSemifield R] [FloorSemiring R] namespace Int /-- The greatest power of `b` such that `b ^ log b r ≤ r`. -/ def log (b : ℕ) (r : R) : ℤ := if 1 ≤ r then Nat.log b ⌊r⌋₊ else -Nat.clog b ⌈r⁻¹⌉₊ theorem log_of_one_le_right (b : ℕ) {r : R} (hr : 1 ≤ r) : log b r = Nat.log b ⌊r⌋₊ := if_pos hr theorem log_of_right_le_one (b : ℕ) {r : R} (hr : r ≤ 1) : log b r = -Nat.clog b ⌈r⁻¹⌉₊ := by obtain rfl | hr := hr.eq_or_lt · rw [log, if_pos hr, inv_one, Nat.ceil_one, Nat.floor_one, Nat.log_one_right, Nat.clog_one_right, Int.ofNat_zero, neg_zero] · exact if_neg hr.not_le @[simp, norm_cast] theorem log_natCast (b : ℕ) (n : ℕ) : log b (n : R) = Nat.log b n := by cases n · simp [log_of_right_le_one] · rw [log_of_one_le_right, Nat.floor_natCast] simp -- See note [no_index around OfNat.ofNat] @[simp] theorem log_ofNat (b : ℕ) (n : ℕ) [n.AtLeastTwo] : log b (no_index (OfNat.ofNat n : R)) = Nat.log b (OfNat.ofNat n) := log_natCast b n theorem log_of_left_le_one {b : ℕ} (hb : b ≤ 1) (r : R) : log b r = 0 := by rcases le_total 1 r with h | h · rw [log_of_one_le_right _ h, Nat.log_of_left_le_one hb, Int.ofNat_zero] · rw [log_of_right_le_one _ h, Nat.clog_of_left_le_one hb, Int.ofNat_zero, neg_zero] theorem log_of_right_le_zero (b : ℕ) {r : R} (hr : r ≤ 0) : log b r = 0 := by rw [log_of_right_le_one _ (hr.trans zero_le_one), Nat.clog_of_right_le_one ((Nat.ceil_eq_zero.mpr <| inv_nonpos.2 hr).trans_le zero_le_one), Int.ofNat_zero, neg_zero] theorem zpow_log_le_self {b : ℕ} {r : R} (hb : 1 < b) (hr : 0 < r) : (b : R) ^ log b r ≤ r := by rcases le_total 1 r with hr1 | hr1 · rw [log_of_one_le_right _ hr1] rw [zpow_natCast, ← Nat.cast_pow, ← Nat.le_floor_iff hr.le] exact Nat.pow_log_le_self b (Nat.floor_pos.mpr hr1).ne' · rw [log_of_right_le_one _ hr1, zpow_neg, zpow_natCast, ← Nat.cast_pow] exact inv_le_of_inv_le hr (Nat.ceil_le.1 <| Nat.le_pow_clog hb _) theorem lt_zpow_succ_log_self {b : ℕ} (hb : 1 < b) (r : R) : r < (b : R) ^ (log b r + 1) := by rcases le_or_lt r 0 with hr | hr · rw [log_of_right_le_zero _ hr, zero_add, zpow_one] exact hr.trans_lt (zero_lt_one.trans_le <| mod_cast hb.le) rcases le_or_lt 1 r with hr1 | hr1 · rw [log_of_one_le_right _ hr1] rw [Int.ofNat_add_one_out, zpow_natCast, ← Nat.cast_pow] apply Nat.lt_of_floor_lt exact Nat.lt_pow_succ_log_self hb _ · rw [log_of_right_le_one _ hr1.le] have hcri : 1 < r⁻¹ := one_lt_inv hr hr1 have : 1 ≤ Nat.clog b ⌈r⁻¹⌉₊ := Nat.succ_le_of_lt (Nat.clog_pos hb <| Nat.one_lt_cast.1 <| hcri.trans_le (Nat.le_ceil _)) rw [neg_add_eq_sub, ← neg_sub, ← Int.ofNat_one, ← Int.ofNat_sub this, zpow_neg, zpow_natCast, lt_inv hr (pow_pos (Nat.cast_pos.mpr <| zero_lt_one.trans hb) _), ← Nat.cast_pow] refine Nat.lt_ceil.1 ?_ exact Nat.pow_pred_clog_lt_self hb <| Nat.one_lt_cast.1 <| hcri.trans_le <| Nat.le_ceil _ @[simp] theorem log_zero_right (b : ℕ) : log b (0 : R) = 0 := log_of_right_le_zero b le_rfl @[simp] theorem log_one_right (b : ℕ) : log b (1 : R) = 0 := by rw [log_of_one_le_right _ le_rfl, Nat.floor_one, Nat.log_one_right, Int.ofNat_zero] -- Porting note: needed to replace b ^ z with (b : R) ^ z in the below theorem log_zpow {b : ℕ} (hb : 1 < b) (z : ℤ) : log b ((b : R) ^ z : R) = z := by obtain ⟨n, rfl | rfl⟩ := Int.eq_nat_or_neg z · rw [log_of_one_le_right _ (one_le_zpow_of_nonneg _ <| Int.natCast_nonneg _), zpow_natCast, ← Nat.cast_pow, Nat.floor_natCast, Nat.log_pow hb] exact mod_cast hb.le · rw [log_of_right_le_one _ (zpow_le_one_of_nonpos _ <| neg_nonpos.mpr (Int.natCast_nonneg _)), zpow_neg, inv_inv, zpow_natCast, ← Nat.cast_pow, Nat.ceil_natCast, Nat.clog_pow _ _ hb] exact mod_cast hb.le @[mono] theorem log_mono_right {b : ℕ} {r₁ r₂ : R} (h₀ : 0 < r₁) (h : r₁ ≤ r₂) : log b r₁ ≤ log b r₂ := by rcases le_total r₁ 1 with h₁ | h₁ <;> rcases le_total r₂ 1 with h₂ | h₂ · rw [log_of_right_le_one _ h₁, log_of_right_le_one _ h₂, neg_le_neg_iff, Int.ofNat_le] exact Nat.clog_mono_right _ (Nat.ceil_mono <| inv_le_inv_of_le h₀ h) · rw [log_of_right_le_one _ h₁, log_of_one_le_right _ h₂] exact (neg_nonpos.mpr (Int.natCast_nonneg _)).trans (Int.natCast_nonneg _) · obtain rfl := le_antisymm h (h₂.trans h₁) rfl · rw [log_of_one_le_right _ h₁, log_of_one_le_right _ h₂, Int.ofNat_le] exact Nat.log_mono_right (Nat.floor_mono h) variable (R) /-- Over suitable subtypes, `zpow` and `Int.log` form a galois coinsertion -/ def zpowLogGi {b : ℕ} (hb : 1 < b) : GaloisCoinsertion (fun z : ℤ => Subtype.mk ((b : R) ^ z) <| zpow_pos_of_pos (mod_cast zero_lt_one.trans hb) z) fun r : Set.Ioi (0 : R) => Int.log b (r : R) := GaloisCoinsertion.monotoneIntro (fun r₁ _ => log_mono_right r₁.2) (fun _ _ hz => Subtype.coe_le_coe.mp <| (zpow_strictMono <| mod_cast hb).monotone hz) (fun r => Subtype.coe_le_coe.mp <| zpow_log_le_self hb r.2) fun _ => log_zpow (R := R) hb _ variable {R} /-- `zpow b` and `Int.log b` (almost) form a Galois connection. -/ theorem lt_zpow_iff_log_lt {b : ℕ} (hb : 1 < b) {x : ℤ} {r : R} (hr : 0 < r) : r < (b : R) ^ x ↔ log b r < x := @GaloisConnection.lt_iff_lt _ _ _ _ _ _ (zpowLogGi R hb).gc x ⟨r, hr⟩ /-- `zpow b` and `Int.log b` (almost) form a Galois connection. -/ theorem zpow_le_iff_le_log {b : ℕ} (hb : 1 < b) {x : ℤ} {r : R} (hr : 0 < r) : (b : R) ^ x ≤ r ↔ x ≤ log b r := @GaloisConnection.le_iff_le _ _ _ _ _ _ (zpowLogGi R hb).gc x ⟨r, hr⟩ /-- The least power of `b` such that `r ≤ b ^ log b r`. -/ def clog (b : ℕ) (r : R) : ℤ := if 1 ≤ r then Nat.clog b ⌈r⌉₊ else -Nat.log b ⌊r⁻¹⌋₊ theorem clog_of_one_le_right (b : ℕ) {r : R} (hr : 1 ≤ r) : clog b r = Nat.clog b ⌈r⌉₊ := if_pos hr theorem clog_of_right_le_one (b : ℕ) {r : R} (hr : r ≤ 1) : clog b r = -Nat.log b ⌊r⁻¹⌋₊ := by obtain rfl | hr := hr.eq_or_lt · rw [clog, if_pos hr, inv_one, Nat.ceil_one, Nat.floor_one, Nat.log_one_right, Nat.clog_one_right, Int.ofNat_zero, neg_zero] · exact if_neg hr.not_le theorem clog_of_right_le_zero (b : ℕ) {r : R} (hr : r ≤ 0) : clog b r = 0 := by rw [clog, if_neg (hr.trans_lt zero_lt_one).not_le, neg_eq_zero, Int.natCast_eq_zero, Nat.log_eq_zero_iff] rcases le_or_lt b 1 with hb | hb · exact Or.inr hb · refine Or.inl (lt_of_le_of_lt ?_ hb) exact Nat.floor_le_one_of_le_one ((inv_nonpos.2 hr).trans zero_le_one) @[simp] theorem clog_inv (b : ℕ) (r : R) : clog b r⁻¹ = -log b r := by cases' lt_or_le 0 r with hrp hrp · obtain hr | hr := le_total 1 r · rw [clog_of_right_le_one _ (inv_le_one hr), log_of_one_le_right _ hr, inv_inv] · rw [clog_of_one_le_right _ (one_le_inv hrp hr), log_of_right_le_one _ hr, neg_neg] · rw [clog_of_right_le_zero _ (inv_nonpos.mpr hrp), log_of_right_le_zero _ hrp, neg_zero] @[simp] theorem log_inv (b : ℕ) (r : R) : log b r⁻¹ = -clog b r := by rw [← inv_inv r, clog_inv, neg_neg, inv_inv] -- note this is useful for writing in reverse theorem neg_log_inv_eq_clog (b : ℕ) (r : R) : -log b r⁻¹ = clog b r := by rw [log_inv, neg_neg] theorem neg_clog_inv_eq_log (b : ℕ) (r : R) : -clog b r⁻¹ = log b r := by rw [clog_inv, neg_neg] @[simp, norm_cast] theorem clog_natCast (b : ℕ) (n : ℕ) : clog b (n : R) = Nat.clog b n := by cases' n with n · simp [clog_of_right_le_one] · rw [clog_of_one_le_right, (Nat.ceil_eq_iff (Nat.succ_ne_zero n)).mpr] <;> simp -- See note [no_index around OfNat.ofNat] @[simp] theorem clog_ofNat (b : ℕ) (n : ℕ) [n.AtLeastTwo] : clog b (no_index (OfNat.ofNat n : R)) = Nat.clog b (OfNat.ofNat n) := clog_natCast b n theorem clog_of_left_le_one {b : ℕ} (hb : b ≤ 1) (r : R) : clog b r = 0 := by rw [← neg_log_inv_eq_clog, log_of_left_le_one hb, neg_zero] theorem self_le_zpow_clog {b : ℕ} (hb : 1 < b) (r : R) : r ≤ (b : R) ^ clog b r := by rcases le_or_lt r 0 with hr | hr · rw [clog_of_right_le_zero _ hr, zpow_zero] exact hr.trans zero_le_one rw [← neg_log_inv_eq_clog, zpow_neg, le_inv hr (zpow_pos_of_pos _ _)] · exact zpow_log_le_self hb (inv_pos.mpr hr) · exact Nat.cast_pos.mpr (zero_le_one.trans_lt hb) theorem zpow_pred_clog_lt_self {b : ℕ} {r : R} (hb : 1 < b) (hr : 0 < r) : (b : R) ^ (clog b r - 1) < r := by rw [← neg_log_inv_eq_clog, ← neg_add', zpow_neg, inv_lt _ hr] · exact lt_zpow_succ_log_self hb _ · exact zpow_pos_of_pos (Nat.cast_pos.mpr <| zero_le_one.trans_lt hb) _ @[simp] theorem clog_zero_right (b : ℕ) : clog b (0 : R) = 0 := clog_of_right_le_zero _ le_rfl @[simp] theorem clog_one_right (b : ℕ) : clog b (1 : R) = 0 := by rw [clog_of_one_le_right _ le_rfl, Nat.ceil_one, Nat.clog_one_right, Int.ofNat_zero] -- Porting note: needed to replace b ^ z with (b : R) ^ z in the below theorem clog_zpow {b : ℕ} (hb : 1 < b) (z : ℤ) : clog b ((b : R) ^ z : R) = z := by rw [← neg_log_inv_eq_clog, ← zpow_neg, log_zpow hb, neg_neg] @[mono] theorem clog_mono_right {b : ℕ} {r₁ r₂ : R} (h₀ : 0 < r₁) (h : r₁ ≤ r₂) : clog b r₁ ≤ clog b r₂ := by rw [← neg_log_inv_eq_clog, ← neg_log_inv_eq_clog, neg_le_neg_iff] exact log_mono_right (inv_pos.mpr <| h₀.trans_le h) (inv_le_inv_of_le h₀ h) variable (R) /-- Over suitable subtypes, `Int.clog` and `zpow` form a galois insertion -/ def clogZPowGi {b : ℕ} (hb : 1 < b) : GaloisInsertion (fun r : Set.Ioi (0 : R) => Int.clog b (r : R)) fun z : ℤ => ⟨(b : R) ^ z, zpow_pos_of_pos (mod_cast zero_lt_one.trans hb) z⟩ := GaloisInsertion.monotoneIntro (fun _ _ hz => Subtype.coe_le_coe.mp <| (zpow_strictMono <| mod_cast hb).monotone hz) (fun r₁ _ => clog_mono_right r₁.2) (fun _ => Subtype.coe_le_coe.mp <| self_le_zpow_clog hb _) fun _ => clog_zpow (R := R) hb _ variable {R} /-- `Int.clog b` and `zpow b` (almost) form a Galois connection. -/ theorem zpow_lt_iff_lt_clog {b : ℕ} (hb : 1 < b) {x : ℤ} {r : R} (hr : 0 < r) : (b : R) ^ x < r ↔ x < clog b r := (@GaloisConnection.lt_iff_lt _ _ _ _ _ _ (clogZPowGi R hb).gc ⟨r, hr⟩ x).symm /-- `Int.clog b` and `zpow b` (almost) form a Galois connection. -/ theorem le_zpow_iff_clog_le {b : ℕ} (hb : 1 < b) {x : ℤ} {r : R} (hr : 0 < r) : r ≤ (b : R) ^ x ↔ clog b r ≤ x := (@GaloisConnection.le_iff_le _ _ _ _ _ _ (clogZPowGi R hb).gc ⟨r, hr⟩ x).symm end Int
Data\Int\ModEq.lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import Mathlib.Data.Nat.ModEq import Mathlib.Tactic.Abel import Mathlib.Tactic.GCongr.Core /-! # Congruences modulo an integer This file defines the equivalence relation `a ≡ b [ZMOD n]` on the integers, similarly to how `Data.Nat.ModEq` defines them for the natural numbers. The notation is short for `n.ModEq a b`, which is defined to be `a % n = b % n` for integers `a b n`. ## Tags modeq, congruence, mod, MOD, modulo, integers -/ namespace Int /-- `a ≡ b [ZMOD n]` when `a % n = b % n`. -/ def ModEq (n a b : ℤ) := a % n = b % n @[inherit_doc] notation:50 a " ≡ " b " [ZMOD " n "]" => ModEq n a b variable {m n a b c d : ℤ} -- Porting note: This instance should be derivable automatically instance : Decidable (ModEq n a b) := decEq (a % n) (b % n) namespace ModEq @[refl, simp] protected theorem refl (a : ℤ) : a ≡ a [ZMOD n] := @rfl _ _ protected theorem rfl : a ≡ a [ZMOD n] := ModEq.refl _ instance : IsRefl _ (ModEq n) := ⟨ModEq.refl⟩ @[symm] protected theorem symm : a ≡ b [ZMOD n] → b ≡ a [ZMOD n] := Eq.symm @[trans] protected theorem trans : a ≡ b [ZMOD n] → b ≡ c [ZMOD n] → a ≡ c [ZMOD n] := Eq.trans instance : IsTrans ℤ (ModEq n) where trans := @Int.ModEq.trans n protected theorem eq : a ≡ b [ZMOD n] → a % n = b % n := id end ModEq theorem modEq_comm : a ≡ b [ZMOD n] ↔ b ≡ a [ZMOD n] := ⟨ModEq.symm, ModEq.symm⟩ theorem natCast_modEq_iff {a b n : ℕ} : a ≡ b [ZMOD n] ↔ a ≡ b [MOD n] := by unfold ModEq Nat.ModEq; rw [← Int.ofNat_inj]; simp [natCast_mod] theorem modEq_zero_iff_dvd : a ≡ 0 [ZMOD n] ↔ n ∣ a := by rw [ModEq, zero_emod, dvd_iff_emod_eq_zero] theorem _root_.Dvd.dvd.modEq_zero_int (h : n ∣ a) : a ≡ 0 [ZMOD n] := modEq_zero_iff_dvd.2 h theorem _root_.Dvd.dvd.zero_modEq_int (h : n ∣ a) : 0 ≡ a [ZMOD n] := h.modEq_zero_int.symm theorem modEq_iff_dvd : a ≡ b [ZMOD n] ↔ n ∣ b - a := by rw [ModEq, eq_comm] simp [emod_eq_emod_iff_emod_sub_eq_zero, dvd_iff_emod_eq_zero] theorem modEq_iff_add_fac {a b n : ℤ} : a ≡ b [ZMOD n] ↔ ∃ t, b = a + n * t := by rw [modEq_iff_dvd] exact exists_congr fun t => sub_eq_iff_eq_add' alias ⟨ModEq.dvd, modEq_of_dvd⟩ := modEq_iff_dvd theorem mod_modEq (a n) : a % n ≡ a [ZMOD n] := emod_emod _ _ @[simp] theorem neg_modEq_neg : -a ≡ -b [ZMOD n] ↔ a ≡ b [ZMOD n] := by -- Porting note: Restore old proof once #3309 is through simp [-sub_neg_eq_add, neg_sub_neg, modEq_iff_dvd, dvd_sub_comm] @[simp] theorem modEq_neg : a ≡ b [ZMOD -n] ↔ a ≡ b [ZMOD n] := by simp [modEq_iff_dvd] namespace ModEq protected theorem of_dvd (d : m ∣ n) (h : a ≡ b [ZMOD n]) : a ≡ b [ZMOD m] := modEq_iff_dvd.2 <| d.trans h.dvd protected theorem mul_left' (h : a ≡ b [ZMOD n]) : c * a ≡ c * b [ZMOD c * n] := by obtain hc | rfl | hc := lt_trichotomy c 0 · rw [← neg_modEq_neg, ← modEq_neg, ← neg_mul, ← neg_mul, ← neg_mul] simp only [ModEq, mul_emod_mul_of_pos _ _ (neg_pos.2 hc), h.eq] · simp only [zero_mul, ModEq.rfl] · simp only [ModEq, mul_emod_mul_of_pos _ _ hc, h.eq] protected theorem mul_right' (h : a ≡ b [ZMOD n]) : a * c ≡ b * c [ZMOD n * c] := by rw [mul_comm a, mul_comm b, mul_comm n]; exact h.mul_left' @[gcongr] protected theorem add (h₁ : a ≡ b [ZMOD n]) (h₂ : c ≡ d [ZMOD n]) : a + c ≡ b + d [ZMOD n] := modEq_iff_dvd.2 <| by convert dvd_add h₁.dvd h₂.dvd using 1; abel @[gcongr] protected theorem add_left (c : ℤ) (h : a ≡ b [ZMOD n]) : c + a ≡ c + b [ZMOD n] := ModEq.rfl.add h @[gcongr] protected theorem add_right (c : ℤ) (h : a ≡ b [ZMOD n]) : a + c ≡ b + c [ZMOD n] := h.add ModEq.rfl protected theorem add_left_cancel (h₁ : a ≡ b [ZMOD n]) (h₂ : a + c ≡ b + d [ZMOD n]) : c ≡ d [ZMOD n] := have : d - c = b + d - (a + c) - (b - a) := by abel modEq_iff_dvd.2 <| by rw [this] exact dvd_sub h₂.dvd h₁.dvd protected theorem add_left_cancel' (c : ℤ) (h : c + a ≡ c + b [ZMOD n]) : a ≡ b [ZMOD n] := ModEq.rfl.add_left_cancel h protected theorem add_right_cancel (h₁ : c ≡ d [ZMOD n]) (h₂ : a + c ≡ b + d [ZMOD n]) : a ≡ b [ZMOD n] := by rw [add_comm a, add_comm b] at h₂ exact h₁.add_left_cancel h₂ protected theorem add_right_cancel' (c : ℤ) (h : a + c ≡ b + c [ZMOD n]) : a ≡ b [ZMOD n] := ModEq.rfl.add_right_cancel h @[gcongr] protected theorem neg (h : a ≡ b [ZMOD n]) : -a ≡ -b [ZMOD n] := h.add_left_cancel (by simp_rw [← sub_eq_add_neg, sub_self]; rfl) @[gcongr] protected theorem sub (h₁ : a ≡ b [ZMOD n]) (h₂ : c ≡ d [ZMOD n]) : a - c ≡ b - d [ZMOD n] := by rw [sub_eq_add_neg, sub_eq_add_neg] exact h₁.add h₂.neg @[gcongr] protected theorem sub_left (c : ℤ) (h : a ≡ b [ZMOD n]) : c - a ≡ c - b [ZMOD n] := ModEq.rfl.sub h @[gcongr] protected theorem sub_right (c : ℤ) (h : a ≡ b [ZMOD n]) : a - c ≡ b - c [ZMOD n] := h.sub ModEq.rfl @[gcongr] protected theorem mul_left (c : ℤ) (h : a ≡ b [ZMOD n]) : c * a ≡ c * b [ZMOD n] := h.mul_left'.of_dvd <| dvd_mul_left _ _ @[gcongr] protected theorem mul_right (c : ℤ) (h : a ≡ b [ZMOD n]) : a * c ≡ b * c [ZMOD n] := h.mul_right'.of_dvd <| dvd_mul_right _ _ @[gcongr] protected theorem mul (h₁ : a ≡ b [ZMOD n]) (h₂ : c ≡ d [ZMOD n]) : a * c ≡ b * d [ZMOD n] := (h₂.mul_left _).trans (h₁.mul_right _) @[gcongr] protected theorem pow (m : ℕ) (h : a ≡ b [ZMOD n]) : a ^ m ≡ b ^ m [ZMOD n] := by induction' m with d hd; · rfl rw [pow_succ, pow_succ] exact hd.mul h lemma of_mul_left (m : ℤ) (h : a ≡ b [ZMOD m * n]) : a ≡ b [ZMOD n] := by rw [modEq_iff_dvd] at *; exact (dvd_mul_left n m).trans h lemma of_mul_right (m : ℤ) : a ≡ b [ZMOD n * m] → a ≡ b [ZMOD n] := mul_comm m n ▸ of_mul_left _ /-- To cancel a common factor `c` from a `ModEq` we must divide the modulus `m` by `gcd m c`. -/ theorem cancel_right_div_gcd (hm : 0 < m) (h : a * c ≡ b * c [ZMOD m]) : a ≡ b [ZMOD m / gcd m c] := by letI d := gcd m c rw [modEq_iff_dvd] at h ⊢ -- Porting note: removed `show` due to leanprover-community/mathlib4#3305 refine Int.dvd_of_dvd_mul_right_of_gcd_one (?_ : m / d ∣ c / d * (b - a)) ?_ · rw [mul_comm, ← Int.mul_ediv_assoc (b - a) gcd_dvd_right, sub_mul] exact Int.ediv_dvd_ediv gcd_dvd_left h · rw [gcd_div gcd_dvd_left gcd_dvd_right, natAbs_ofNat, Nat.div_self (gcd_pos_of_ne_zero_left c hm.ne')] /-- To cancel a common factor `c` from a `ModEq` we must divide the modulus `m` by `gcd m c`. -/ theorem cancel_left_div_gcd (hm : 0 < m) (h : c * a ≡ c * b [ZMOD m]) : a ≡ b [ZMOD m / gcd m c] := cancel_right_div_gcd hm <| by simpa [mul_comm] using h theorem of_div (h : a / c ≡ b / c [ZMOD m / c]) (ha : c ∣ a) (ha : c ∣ b) (ha : c ∣ m) : a ≡ b [ZMOD m] := by convert h.mul_left' <;> rwa [Int.mul_ediv_cancel'] end ModEq theorem modEq_one : a ≡ b [ZMOD 1] := modEq_of_dvd (one_dvd _) theorem modEq_sub (a b : ℤ) : a ≡ b [ZMOD a - b] := (modEq_of_dvd dvd_rfl).symm @[simp] theorem modEq_zero_iff : a ≡ b [ZMOD 0] ↔ a = b := by rw [ModEq, emod_zero, emod_zero] @[simp] theorem add_modEq_left : n + a ≡ a [ZMOD n] := ModEq.symm <| modEq_iff_dvd.2 <| by simp @[simp] theorem add_modEq_right : a + n ≡ a [ZMOD n] := ModEq.symm <| modEq_iff_dvd.2 <| by simp theorem modEq_and_modEq_iff_modEq_mul {a b m n : ℤ} (hmn : m.natAbs.Coprime n.natAbs) : a ≡ b [ZMOD m] ∧ a ≡ b [ZMOD n] ↔ a ≡ b [ZMOD m * n] := ⟨fun h => by rw [modEq_iff_dvd, modEq_iff_dvd] at h rw [modEq_iff_dvd, ← natAbs_dvd, ← dvd_natAbs, natCast_dvd_natCast, natAbs_mul] refine hmn.mul_dvd_of_dvd_of_dvd ?_ ?_ <;> rw [← natCast_dvd_natCast, natAbs_dvd, dvd_natAbs] <;> tauto, fun h => ⟨h.of_mul_right _, h.of_mul_left _⟩⟩ theorem gcd_a_modEq (a b : ℕ) : (a : ℤ) * Nat.gcdA a b ≡ Nat.gcd a b [ZMOD b] := by rw [← add_zero ((a : ℤ) * _), Nat.gcd_eq_gcd_ab] exact (dvd_mul_right _ _).zero_modEq_int.add_left _ theorem modEq_add_fac {a b n : ℤ} (c : ℤ) (ha : a ≡ b [ZMOD n]) : a + n * c ≡ b [ZMOD n] := calc a + n * c ≡ b + n * c [ZMOD n] := ha.add_right _ _ ≡ b + 0 [ZMOD n] := (dvd_mul_right _ _).modEq_zero_int.add_left _ _ ≡ b [ZMOD n] := by rw [add_zero] theorem modEq_sub_fac {a b n : ℤ} (c : ℤ) (ha : a ≡ b [ZMOD n]) : a - n * c ≡ b [ZMOD n] := by convert Int.modEq_add_fac (-c) ha using 1; rw [mul_neg, sub_eq_add_neg] theorem modEq_add_fac_self {a t n : ℤ} : a + n * t ≡ a [ZMOD n] := modEq_add_fac _ ModEq.rfl theorem mod_coprime {a b : ℕ} (hab : Nat.Coprime a b) : ∃ y : ℤ, a * y ≡ 1 [ZMOD b] := ⟨Nat.gcdA a b, have hgcd : Nat.gcd a b = 1 := Nat.Coprime.gcd_eq_one hab calc ↑a * Nat.gcdA a b ≡ ↑a * Nat.gcdA a b + ↑b * Nat.gcdB a b [ZMOD ↑b] := ModEq.symm <| modEq_add_fac _ <| ModEq.refl _ _ ≡ 1 [ZMOD ↑b] := by rw [← Nat.gcd_eq_gcd_ab, hgcd]; rfl ⟩ theorem exists_unique_equiv (a : ℤ) {b : ℤ} (hb : 0 < b) : ∃ z : ℤ, 0 ≤ z ∧ z < b ∧ z ≡ a [ZMOD b] := ⟨a % b, emod_nonneg _ (ne_of_gt hb), by have : a % b < |b| := emod_lt _ (ne_of_gt hb) rwa [abs_of_pos hb] at this, by simp [ModEq]⟩ theorem exists_unique_equiv_nat (a : ℤ) {b : ℤ} (hb : 0 < b) : ∃ z : ℕ, ↑z < b ∧ ↑z ≡ a [ZMOD b] := let ⟨z, hz1, hz2, hz3⟩ := exists_unique_equiv a hb ⟨z.natAbs, by constructor <;> rw [natAbs_of_nonneg hz1] <;> assumption⟩ theorem mod_mul_right_mod (a b c : ℤ) : a % (b * c) % b = a % b := (mod_modEq _ _).of_mul_right _ theorem mod_mul_left_mod (a b c : ℤ) : a % (b * c) % c = a % c := (mod_modEq _ _).of_mul_left _ @[deprecated (since := "2024-04-02")] alias coe_nat_modEq_iff := natCast_modEq_iff end Int
Data\Int\NatPrime.lean
/- Copyright (c) 2020 Bryan Gin-ge Chen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Lacker, Bryan Gin-ge Chen -/ import Mathlib.Data.Nat.Prime.Basic /-! # Lemmas about `Nat.Prime` using `Int`s -/ open Nat namespace Int theorem not_prime_of_int_mul {a b : ℤ} {c : ℕ} (ha : a.natAbs ≠ 1) (hb : b.natAbs ≠ 1) (hc : a * b = (c : ℤ)) : ¬Nat.Prime c := not_prime_mul' (natAbs_mul_natAbs_eq hc) ha hb theorem succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul {p : ℕ} (p_prime : Nat.Prime p) {m n : ℤ} {k l : ℕ} (hpm : ↑(p ^ k) ∣ m) (hpn : ↑(p ^ l) ∣ n) (hpmn : ↑(p ^ (k + l + 1)) ∣ m * n) : ↑(p ^ (k + 1)) ∣ m ∨ ↑(p ^ (l + 1)) ∣ n := have hpm' : p ^ k ∣ m.natAbs := Int.natCast_dvd_natCast.1 <| Int.dvd_natAbs.2 hpm have hpn' : p ^ l ∣ n.natAbs := Int.natCast_dvd_natCast.1 <| Int.dvd_natAbs.2 hpn have hpmn' : p ^ (k + l + 1) ∣ m.natAbs * n.natAbs := by rw [← Int.natAbs_mul]; apply Int.natCast_dvd_natCast.1 <| Int.dvd_natAbs.2 hpmn let hsd := Nat.succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul p_prime hpm' hpn' hpmn' hsd.elim (fun hsd1 => Or.inl (by apply Int.dvd_natAbs.1; apply Int.natCast_dvd_natCast.2 hsd1)) fun hsd2 => Or.inr (by apply Int.dvd_natAbs.1; apply Int.natCast_dvd_natCast.2 hsd2) theorem Prime.dvd_natAbs_of_coe_dvd_sq {p : ℕ} (hp : p.Prime) (k : ℤ) (h : (p : ℤ) ∣ k ^ 2) : p ∣ k.natAbs := by apply @Nat.Prime.dvd_of_dvd_pow _ _ 2 hp rwa [sq, ← natAbs_mul, ← natCast_dvd, ← sq] end Int
Data\Int\Notation.lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad -/ /-! # Notation `ℤ` for the integers. -/ @[inherit_doc] notation "ℤ" => Int
Data\Int\Range.lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Kenny Lau -/ import Mathlib.Algebra.Order.Ring.Int /-! # Intervals in ℤ This file defines integer ranges. `range m n` is the set of integers greater than `m` and strictly less than `n`. ## Note This could be unified with `Data.List.Intervals`. See the TODOs there. -/ -- Porting note: Many unfolds about `Lean.Internal.coeM` namespace Int /-- List enumerating `[m, n)`. This is the ℤ variant of `List.Ico`. -/ def range (m n : ℤ) : List ℤ := ((List.range (toNat (n - m))) : List ℕ).map fun (r : ℕ) => (m + r : ℤ) theorem mem_range_iff {m n r : ℤ} : r ∈ range m n ↔ m ≤ r ∧ r < n := by simp only [range, List.mem_map, List.mem_range, lt_toNat, lt_sub_iff_add_lt, add_comm] exact ⟨fun ⟨a, ha⟩ => ha.2 ▸ ⟨le_add_of_nonneg_right (Int.natCast_nonneg _), ha.1⟩, fun h => ⟨toNat (r - m), by simp [toNat_of_nonneg (sub_nonneg.2 h.1), h.2] ⟩⟩ instance decidableLELT (P : Int → Prop) [DecidablePred P] (m n : ℤ) : Decidable (∀ r, m ≤ r → r < n → P r) := decidable_of_iff (∀ r ∈ range m n, P r) <| by simp only [mem_range_iff, and_imp] instance decidableLELE (P : Int → Prop) [DecidablePred P] (m n : ℤ) : Decidable (∀ r, m ≤ r → r ≤ n → P r) := by -- Porting note: The previous code was: -- decidable_of_iff (∀ r ∈ range m (n + 1), P r) <| by -- simp only [mem_range_iff, and_imp, lt_add_one_iff] -- -- This fails to synthesize an instance -- `Decidable (∀ (r : ℤ), r ∈ range m (n + 1) → P r)` apply decidable_of_iff (∀ r ∈ range m (n + 1), P r) apply Iff.intro <;> intros h _ _ · intro _; apply h simp_all only [mem_range_iff, and_imp, and_self, lt_add_one_iff] · simp_all only [mem_range_iff, and_imp, lt_add_one_iff] instance decidableLTLT (P : Int → Prop) [DecidablePred P] (m n : ℤ) : Decidable (∀ r, m < r → r < n → P r) := Int.decidableLELT P _ _ instance decidableLTLE (P : Int → Prop) [DecidablePred P] (m n : ℤ) : Decidable (∀ r, m < r → r ≤ n → P r) := Int.decidableLELE P _ _ end Int
Data\Int\Sqrt.lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import Mathlib.Data.Int.Defs import Mathlib.Data.Nat.Defs import Mathlib.Tactic.Common /-! # Square root of integers This file defines the square root function on integers. `Int.sqrt z` is the greatest integer `r` such that `r * r ≤ z`. If `z ≤ 0`, then `Int.sqrt z = 0`. -/ namespace Int /-- `sqrt z` is the square root of an integer `z`. If `z` is positive, it returns the largest integer `r` such that `r * r ≤ n`. If it is negative, it returns `0`. For example, `sqrt (-1) = 0`, `sqrt 1 = 1`, `sqrt 2 = 1` -/ @[pp_nodot] def sqrt (z : ℤ) : ℤ := Nat.sqrt <| Int.toNat z theorem sqrt_eq (n : ℤ) : sqrt (n * n) = n.natAbs := by rw [sqrt, ← natAbs_mul_self, toNat_natCast, Nat.sqrt_eq] theorem exists_mul_self (x : ℤ) : (∃ n, n * n = x) ↔ sqrt x * sqrt x = x := ⟨fun ⟨n, hn⟩ => by rw [← hn, sqrt_eq, ← Int.ofNat_mul, natAbs_mul_self], fun h => ⟨sqrt x, h⟩⟩ theorem sqrt_nonneg (n : ℤ) : 0 ≤ sqrt n := natCast_nonneg _ @[simp, norm_cast] theorem sqrt_natCast (n : ℕ) : Int.sqrt (n : ℤ) = Nat.sqrt n := by rw [sqrt, toNat_ofNat] -- See note [no_index around OfNat.ofNat] @[simp] theorem sqrt_ofNat (n : ℕ) : Int.sqrt (no_index (OfNat.ofNat n) : ℤ) = Nat.sqrt (OfNat.ofNat n) := sqrt_natCast _ end Int
Data\Int\Star.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 Mathlib.Algebra.Star.Order import Mathlib.Algebra.Order.Monoid.Submonoid import Mathlib.Algebra.Order.Ring.Basic /-! # Star ordered ring structure on `ℤ` This file shows that `ℤ` is a `StarOrderedRing`. -/ open AddSubmonoid Set namespace Int @[simp] lemma addSubmonoid_closure_range_pow {n : ℕ} (hn : Even n) : closure (range fun x : ℤ ↦ x ^ n) = nonneg _ := by refine le_antisymm (closure_le.2 <| range_subset_iff.2 hn.pow_nonneg) fun x hx ↦ ?_ have : x = x.natAbs • 1 ^ n := by simpa [eq_comm (a := x)] using hx rw [this] exact nsmul_mem (subset_closure $ mem_range_self _) _ @[simp] lemma addSubmonoid_closure_range_mul_self : closure (range fun x : ℤ ↦ x * x) = nonneg _ := by simpa only [sq] using addSubmonoid_closure_range_pow even_two instance instStarOrderedRing : StarOrderedRing ℤ where le_iff a b := by simp [le_iff_exists_nonneg_add a b] end Int
Data\Int\SuccPred.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.Ring.Int import Mathlib.Data.Nat.SuccPred /-! # Successors and predecessors of integers In this file, we show that `ℤ` is both an archimedean `SuccOrder` and an archimedean `PredOrder`. -/ open Function Order namespace Int -- so that Lean reads `Int.succ` through `SuccOrder.succ` @[instance] abbrev instSuccOrder : SuccOrder ℤ := { SuccOrder.ofSuccLeIff succ fun {_ _} => Iff.rfl with succ := succ } -- so that Lean reads `Int.pred` through `PredOrder.pred` @[instance] abbrev instPredOrder : PredOrder ℤ where pred := pred pred_le _ := (sub_one_lt_of_le le_rfl).le min_of_le_pred ha := ((sub_one_lt_of_le le_rfl).not_le ha).elim le_pred_of_lt {_ _} := le_sub_one_of_lt le_of_pred_lt {_ _} := le_of_sub_one_lt @[simp] theorem succ_eq_succ : Order.succ = succ := rfl @[simp] theorem pred_eq_pred : Order.pred = pred := rfl theorem pos_iff_one_le {a : ℤ} : 0 < a ↔ 1 ≤ a := Order.succ_le_iff.symm theorem succ_iterate (a : ℤ) : ∀ n, succ^[n] a = a + n | 0 => (add_zero a).symm | n + 1 => by rw [Function.iterate_succ', Int.ofNat_succ, ← add_assoc] exact congr_arg _ (succ_iterate a n) theorem pred_iterate (a : ℤ) : ∀ n, pred^[n] a = a - n | 0 => (sub_zero a).symm | n + 1 => by rw [Function.iterate_succ', Int.ofNat_succ, ← sub_sub] exact congr_arg _ (pred_iterate a n) instance : IsSuccArchimedean ℤ := ⟨fun {a b} h => ⟨(b - a).toNat, by rw [succ_eq_succ, succ_iterate, toNat_sub_of_le h, ← add_sub_assoc, add_sub_cancel_left]⟩⟩ instance : IsPredArchimedean ℤ := ⟨fun {a b} h => ⟨(b - a).toNat, by rw [pred_eq_pred, pred_iterate, toNat_sub_of_le h, sub_sub_cancel]⟩⟩ /-! ### Covering relation -/ protected theorem covBy_iff_succ_eq {m n : ℤ} : m ⋖ n ↔ m + 1 = n := succ_eq_iff_covBy.symm @[simp] theorem sub_one_covBy (z : ℤ) : z - 1 ⋖ z := by rw [Int.covBy_iff_succ_eq, sub_add_cancel] @[simp] theorem covBy_add_one (z : ℤ) : z ⋖ z + 1 := Int.covBy_iff_succ_eq.mpr rfl @[simp, norm_cast] theorem natCast_covBy {a b : ℕ} : (a : ℤ) ⋖ b ↔ a ⋖ b := by rw [Nat.covBy_iff_succ_eq, Int.covBy_iff_succ_eq] exact Int.natCast_inj end Int alias ⟨_, CovBy.intCast⟩ := Int.natCast_covBy @[deprecated (since := "2024-05-27")] alias Nat.cast_int_covBy_iff := Int.natCast_covBy @[deprecated (since := "2024-05-27")] alias CovBy.cast_int := CovBy.intCast
Data\Int\Cast\Basic.lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Gabriel Ebner -/ import Mathlib.Data.Int.Cast.Defs import Mathlib.Algebra.Group.Basic /-! # Cast of integers (additional theorems) This file proves additional properties about the *canonical* homomorphism from the integers into an additive group with a one (`Int.cast`). There is also `Data.Int.Cast.Lemmas`, which includes lemmas stated in terms of algebraic homomorphisms, and results involving the order structure of `ℤ`. By contrast, this file's only import beyond `Data.Int.Cast.Defs` is `Algebra.Group.Basic`. -/ universe u namespace Nat variable {R : Type u} [AddGroupWithOne R] @[simp, norm_cast] theorem cast_sub {m n} (h : m ≤ n) : ((n - m : ℕ) : R) = n - m := eq_sub_of_add_eq <| by rw [← cast_add, Nat.sub_add_cancel h] -- `HasLiftT` appeared in the type signature @[simp, norm_cast] theorem cast_pred : ∀ {n}, 0 < n → ((n - 1 : ℕ) : R) = n - 1 | 0, h => by cases h | n + 1, _ => by rw [cast_succ, add_sub_cancel_right]; rfl end Nat open Nat namespace Int variable {R : Type u} [AddGroupWithOne R] @[simp, norm_cast squash] theorem cast_negSucc (n : ℕ) : (-[n+1] : R) = -(n + 1 : ℕ) := AddGroupWithOne.intCast_negSucc n -- expected `n` to be implicit, and `HasLiftT` @[simp, norm_cast] theorem cast_zero : ((0 : ℤ) : R) = 0 := (AddGroupWithOne.intCast_ofNat 0).trans Nat.cast_zero -- type had `HasLiftT` -- This lemma competes with `Int.ofNat_eq_natCast` to come later @[simp high, nolint simpNF, norm_cast] theorem cast_natCast (n : ℕ) : ((n : ℤ) : R) = n := AddGroupWithOne.intCast_ofNat _ -- expected `n` to be implicit, and `HasLiftT` -- See note [no_index around OfNat.ofNat] @[simp, norm_cast] theorem cast_ofNat (n : ℕ) [n.AtLeastTwo] : ((no_index (OfNat.ofNat n) : ℤ) : R) = OfNat.ofNat n := by simpa only [OfNat.ofNat] using AddGroupWithOne.intCast_ofNat (R := R) n @[simp, norm_cast] theorem cast_one : ((1 : ℤ) : R) = 1 := by erw [cast_natCast, Nat.cast_one] -- type had `HasLiftT` @[simp, norm_cast] theorem cast_neg : ∀ n, ((-n : ℤ) : R) = -n | (0 : ℕ) => by erw [cast_zero, neg_zero] | (n + 1 : ℕ) => by erw [cast_natCast, cast_negSucc] | -[n+1] => by erw [cast_natCast, cast_negSucc, neg_neg] -- type had `HasLiftT` @[simp, norm_cast] theorem cast_subNatNat (m n) : ((Int.subNatNat m n : ℤ) : R) = m - n := by unfold subNatNat cases e : n - m · simp only [ofNat_eq_coe] simp [e, Nat.le_of_sub_eq_zero e] · rw [cast_negSucc, ← e, Nat.cast_sub <| _root_.le_of_lt <| Nat.lt_of_sub_eq_succ e, neg_sub] -- type had `HasLiftT` @[simp] theorem cast_negOfNat (n : ℕ) : ((negOfNat n : ℤ) : R) = -n := by simp [Int.cast_neg, negOfNat_eq] @[simp, norm_cast] theorem cast_add : ∀ m n, ((m + n : ℤ) : R) = m + n | (m : ℕ), (n : ℕ) => by simp [-Int.natCast_add, ← Int.ofNat_add] | (m : ℕ), -[n+1] => by erw [cast_subNatNat, cast_natCast, cast_negSucc, sub_eq_add_neg] | -[m+1], (n : ℕ) => by erw [cast_subNatNat, cast_natCast, cast_negSucc, sub_eq_iff_eq_add, add_assoc, eq_neg_add_iff_add_eq, ← Nat.cast_add, ← Nat.cast_add, Nat.add_comm] | -[m+1], -[n+1] => show (-[m + n + 1+1] : R) = _ by rw [cast_negSucc, cast_negSucc, cast_negSucc, ← neg_add_rev, ← Nat.cast_add, Nat.add_right_comm m n 1, Nat.add_assoc, Nat.add_comm] -- type had `HasLiftT` @[simp, norm_cast] theorem cast_sub (m n) : ((m - n : ℤ) : R) = m - n := by simp [Int.sub_eq_add_neg, sub_eq_add_neg, Int.cast_neg, Int.cast_add] -- type had `HasLiftT` theorem cast_two : ((2 : ℤ) : R) = 2 := cast_ofNat _ theorem cast_three : ((3 : ℤ) : R) = 3 := cast_ofNat _ theorem cast_four : ((4 : ℤ) : R) = 4 := cast_ofNat _ end Int
Data\Int\Cast\Defs.lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Gabriel Ebner -/ import Mathlib.Data.Nat.Cast.Defs /-! # Cast of integers This file defines the *canonical* homomorphism from the integers into an additive group with a one (typically a `Ring`). In additive groups with a one element, there exists a unique such homomorphism and we store it in the `intCast : ℤ → R` field. Preferentially, the homomorphism is written as a coercion. ## Main declarations * `Int.cast`: Canonical homomorphism `ℤ → R`. * `AddGroupWithOne`: Type class for `Int.cast`. -/ universe u /-- Default value for `IntCast.intCast` in an `AddGroupWithOne`. -/ protected def Int.castDef {R : Type u} [NatCast R] [Neg R] : ℤ → R | (n : ℕ) => n | Int.negSucc n => -(n + 1 : ℕ) /-! ### Additive groups with one -/ /-- An `AddGroupWithOne` is an `AddGroup` with a 1. It also contains data for the unique homomorphisms `ℕ → R` and `ℤ → R`. -/ class AddGroupWithOne (R : Type u) extends IntCast R, AddMonoidWithOne R, AddGroup R where /-- The canonical homomorphism `ℤ → R`. -/ intCast := Int.castDef /-- The canonical homomorphism `ℤ → R` agrees with the one from `ℕ → R` on `ℕ`. -/ intCast_ofNat : ∀ n : ℕ, intCast (n : ℕ) = Nat.cast n := by intros; rfl /-- The canonical homomorphism `ℤ → R` for negative values is just the negation of the values of the canonical homomorphism `ℕ → R`. -/ intCast_negSucc : ∀ n : ℕ, intCast (Int.negSucc n) = - Nat.cast (n + 1) := by intros; rfl /-- An `AddCommGroupWithOne` is an `AddGroupWithOne` satisfying `a + b = b + a`. -/ class AddCommGroupWithOne (R : Type u) extends AddCommGroup R, AddGroupWithOne R, AddCommMonoidWithOne R
Data\Int\Cast\Field.lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import Mathlib.Algebra.Field.Defs import Mathlib.Algebra.Ring.Int /-! # Cast of integers into fields This file concerns the canonical homomorphism `ℤ → F`, where `F` is a field. ## Main results * `Int.cast_div`: if `n` divides `m`, then `↑(m / n) = ↑m / ↑n` -/ namespace Int open Nat variable {α : Type*} /-- Auxiliary lemma for norm_cast to move the cast `-↑n` upwards to `↑-↑n`. (The restriction to `DivisionRing` is necessary, otherwise this would also apply in the case where `R = ℤ` and cause nontermination.) -/ @[norm_cast] theorem cast_neg_natCast {R} [DivisionRing R] (n : ℕ) : ((-n : ℤ) : R) = -n := by simp @[simp] theorem cast_div [DivisionRing α] {m n : ℤ} (n_dvd : n ∣ m) (hn : (n : α) ≠ 0) : ((m / n : ℤ) : α) = m / n := by rcases n_dvd with ⟨k, rfl⟩ have : n ≠ 0 := by rintro rfl; simp at hn rw [Int.mul_ediv_cancel_left _ this, mul_comm n, Int.cast_mul, mul_div_cancel_right₀ _ hn] end Int