open import Cat.Diagram.Pullback.Properties
open import Cat.Instances.Sets.Complete
open import Cat.Morphism.Factorisation
open import Cat.Morphism.StrongEpi
open import Cat.Diagram.Pullback
open import Cat.Instances.Sets
open import Cat.Prelude
open import Cat.Regular

open import Data.Set.Surjection

module Cat.Regular.Instances.Sets where

Sets is regularπŸ”—

We can prove that the category of is regular by investigating the relationship between surjections, regular epimorphisms, and arbitrary epimorphisms. Fortunately, they all coincide, and we already know that is finitely complete, so it only remains to show that morphisms have an epi-mono factorisation, and that epimorphy is stable under pullbacks.

Sets-regular : βˆ€ {β„“} β†’ is-regular (Sets β„“)
Sets-regular .has-is-lex = Sets-finitely-complete

For the factorisation, we go with the pre-existing notion of image, not only because we’re trying to compute an image factorisation, but because there is a natural surjection and an embedding

Sets-regular .factor {a} {b} f = Ξ» where
  .mediating β†’ el! (image f)
  .mediate x β†’ (f x) , inc (x , refl)
  .forget    β†’ fst

  .mediate∈E β†’ inc (is-regular-epiβ†’is-strong-epi (Sets _) {a} {el! (image f)} _
    (surjective→regular-epi _ _ _ λ {
      (x , y) β†’ βˆ₯-βˆ₯-rec squash (Ξ» { (pre , p) β†’ inc (pre , Ξ£-prop-path! p) }) y }))

  .forget∈M  β†’ inc (embeddingβ†’monic (Subset-proj-embedding (Ξ» _ β†’ squash)))
  .factors   β†’ refl

It additionally suffices to verify this only for our choice of pullbacks (rather than arbitrary pullback squares), for which the following calculation does perfectly:

Sets-regular .stable =
  canonically-stable
    (Ξ» {a} {b} β†’ is-strong-epi (Sets _) {a} {b}) Sets-is-category Sets-pullbacks
    Ξ» {a} {b} {c} f g (f-epi , _) β†’
    let
      rem₁ : is-surjective f
      rem₁ = epiβ†’surjective a b f Ξ» {c} β†’ f-epi {c}

      T : Set _
      T = Sets-pullbacks {A = c} {a} {b} g f .Pullback.apex

      pb : ∣ T ∣ β†’ ∣ c ∣
      pb = Sets-pullbacks {A = c} {a} {b} g f .Pullback.p₁

      remβ‚‚ : is-surjective pb
      remβ‚‚ x = do
        (f^*fx , p) ← rem₁ (g x)
        pure ((x , f^*fx , sym p) , refl)
    in
      is-regular-epi→is-strong-epi (Sets _) {a = el! _} {c} _
        (surjective→regular-epi _ _ _ rem₂)