ebook img

Quotients in monadic programming: Projective algebras are equivalent to coalgebras PDF

0.23 MB·
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview Quotients in monadic programming: Projective algebras are equivalent to coalgebras

Quotients in monadic programming: Projective algebras are equivalent to coalgebras 7 1 0 DuskoPavlovic∗ Peter-Michael Seidel 2 b UniversityofHawaii,HonoluluHI, USA e F 7 ] Abstract O L Inmonadicprogramming,datatypesarepresentedasfreealgebras,generated bydatavalues,andbythealgebraicoperationsandequationscapturingsomecom- . s putational effects. These algebras are free in the sense that they satisfy just the c equations imposed by their algebraic theory, and remain free of any additional [ equations. Theconsequence isthattheydonotadmitquotient types. Thisis,of 2 course, ofteninconvenient. Wheneveracomputationinvolvesdatawithmultiple v representatives, and they need to be identified according to some equations that 1 arenotsatisfiedbyalldata,themonadicprogrammerhastoleavetheuniverseof 0 freealgebras,andresorttoexplicitdestructors.Wecharacterizethesituationwhen 6 these destructors are preserved under all operations, and the resulting quotients 7 of freealgebras are alsotheir subalgebras. Such quotients are calledprojective. 0 . Althoughpopularinuniversalalgebra,projectivealgebrasdidnotattractmuchat- 1 tentioninthemonadicsetting,wheretheyturnouttohaveasurprisingavatar:for 0 anygivenmonad,asuitablecategoryofprojectivealgebrasisequivalentwiththe 7 categoryofcoalgebrasforthecomonadinducedbyanymonadresolution. Fora 1 monadic programmer, this equivalence provides a convenient way to implement : v polymorphicquotientsascoalgebras. Thedualcorrespondenceofinjectivecoal- i gebrasandallalgebrasleadstoadifferentfamilyofquotienttypes,whichseems X to have a different family of applications. Both equivalences also entail several r a generalcorollariesconcerningmonadicityandcomonadicity. 1 Introduction 1.1 The story Background:Monadicprogramming. Monadsareoneoffunctionalprogrammers’ favoritetools,andpossiblyoneofthemostpopularcategoricalconcepts[14,13].Asa typeconstructor,amonadgivesrisetodatatypesthatcapturenotonlythedatavalues, butalsosomecomputationaleffectsofinterest[35,42]. While thisisachievedusing ∗SupportedbyAFOSRandNSF. 1 averysimpleandconvenientsetoftools,thehistoryoftheunderlyingideasisconvo- luted, and the conceptualand technicalbackgroundof monadic programmingcovers enoughterritoryofalgebraandofcategorytheorytoconcealmanymathematicalmys- teries. The conceptual origin of monadic programming was probably the idea that data structures can be captured as algebraic theories, which goes back to the early days ofsemanticsofcomputation[20,21]. Thetechnicaloriginofmonadicprogramming wasthentheideathatalgebraictheoriescanbecapturedasmonads,whichgoesback even further, to the early days of category theory [33, 34, Ch. I]. The upshot of the view of data-structures-as-algebraic-theories is that computational datatypes, as do- mainsofinductiveandrecursivedefinitions,canbeviewedasinitial,orfreealgebras, implementinginductionasauniversalproperty. Theupshotoftheviewofalgebraic- theories-as-monadsinthiscontextisthefactthatmonadsencapsulateandhidebehind theirstandardstructure1thediverseandoftenbewilderingsetsofalgebraicoperations, andmakethemavailableonlythroughuniformlystructuredmonadiccombinators. The mainfeatureof computationalmonadsis thustheir succinctandelegantren- dering of inductive datatypes as free algebras. But this main feature is perhaps also theirmainlimitation:thequotientsoffreealgebrasarenotfreealgebras. Problem: Quotient types. Whenevera data value can be given by differentrepre- sentatives,itsdatatypeisaquotient. E.g.,eachrationalnumbercanberepresentedby infinitelymanyfractions(3 = 39 = 273 = ···), so thedatatypeof rationalsisa quo- 7 91 637 tientofthedatatypeoforderedpairsofintegers. Setsareaquotientofbags,bagsare aquotientoflists, andsoon. Identifyingtheequivalentrepresentativescanbeahard andimportantcomputationaltask, tackledin typetheoryfromthe outset, goingback to Martin-Löf, and still further back to Leibniz. Different applications often justify differentimplementations[1,6],whichvaryfromsimplycarryingexplicitequivalence relationswithsetoids[11,31],throughcarryingcoherentequivalenceswithgroupoids [25,24,3],allthewaytotherichstructureofhomotopytypes[8,40],wheretheprob- lemofquotientsintypetheoryandtheproblemofinvariantsingeometryseemtobe solvingeachother. Thebasicideaofmonadicprogramming,topresentdatatypesasfreealgebras,pre- cludesdirectimplementationsofquotienttypes,sinceaquotientofafreealgebraisin generalnotfree.Thisisoftenviewedasafeature,sincepolymorphismrequiresthatall datasatisfyexactlythesameequations,whichforalgebrasmeansthattheyshouldsat- isfyjusttheequationsimposedbytheiralgebraictheory,andnoadditionalequations. Whennecessary, the additionalequationscanbe imposedbyexplicitdestructors, but thepolymorphicconstructionsgenerallydonotcarryovertosuchquotients,unlessthe destructorspreservethem. Underwhichconditionsdoesthathappen? Solution: Projective algebras. In the present paper, we study a special family of quotientsoffreealgebras: thosethatalsohappentobetheirsubalgebras. Thismeans thattheycan be implementednotonlyby imposingadditionalequations, butalso by 1Godementintroducedmonadsunderthenamestandardconstruction,standardizingthesheafcohomol- ogyconstruction[19]. 2 adjoiningsuitableoperations,calledprojectors,asdescribedbelow. Analgebrawhich isbothaquotientandasubalgebraofafreealgebra,i.e. itsretract,issaidtobeprojec- tive[22,§82]2. Sinceprojectorsinducepreciselythequotientsthatarepreservedbyall functors[36], thisaproachseemsnecessaryandsufficientforextendingpolymorphic constructionsfromfreealgebrastotheirquotients.Theequivalenceofprojectivealge- brasfora monadandallcoalgebrasforanyofthe correspondingcomonads,claimed inthetitleofthepaper,suggestsalinkbetweentheproblemofpolymorphicquotients in monadic programmingand the ideas of comonadic programming, put forward by severalauthors[17, 41, 2]. Theduallinkofinjectivealgebrasfora comonadandall algebras for any of the corresponding monads suggests a link between polymorphic quotientsof cofree coalgebrasand unrestrictedquotientsof algebras. We proceedto workouttheselinks. Prerequisites This is a paper about categorical semantics of computation, so the prerequisites are mostlycategorical. ThemainbackgrounddefinitionsarereproducedintheAppendix. Averysuccinctoverviewoftheunderlyingconceptscanbefoundin[28,Sec.I.3]. 1.2 Motivatingexample LetCbeacartesianclosedcategory,i.e. givenwithanadjunction A× C ⊥ C (1) A⇒ foreveryobjectA. FixanobjectS asastatespace,andconsiderthemonad ←− S : C →− C (2) X 7→ S ⇒(S ×X) inducedbytheadjunction(1)instantiatedtoS. Asexplainedin[35], thecategoryof ←− free S-algebrasC←− capturescomputationswith explicitstate, orwith side effects. A S computationovertheinputsoftypeA,theoutputsoftypeB,andthestatesoftypeS is presentedasafreealgebrahomomorphism f ∈ C←−(A,B),whichcanbeconveniently S viewed as a C-morphism in the form A −−−f→ S ⇒ (S × B) [32]. This computation f(a) thusmaps everyinputa ∈ A to a functionS −−−−→ S × B, determiningat each state s ∈ S anextstate,andanoutput. Equivalently,suchmorphismscanbeviewedinthe f′ transposedformS ×A−−−−→S ×B,assigningtoeachstateandeveryinputanextstate and an output. This transposed form of homomorphismsbetween free algebras will turnouttobemoreconvenientforthepurposesofthispaper. Inthecase ofthestate ←− monad S,suchhomomorphismscaptureMealymachines[15,23,26,Sec.2.7(a)]. 2Thenameisborrowedfromtheoryofmodules,wheretheretractsoffreemodulesarealsocalledpro- jective. 3 Towards a more concrete example, consider the following model of data release f policiesfrom[39]. SupposethataMealymachineS ×A→− S ×Bmodelsadatabase. S areitsstates,Aaretheinputs(insertions,queries,...) thattheusersmayenter,and g Baretheoutputssuppliedbythedatabase.AstatelessmapA→− Bcanbethoughtofa rudimentarydeterministicchannel,justmappingdataoftypeAtodataoftypeB.Since therearemultipleusers,theremaybeprivacypolicies,andauthorizationpoliciesthat ψ needto be implemented. A privacypolicycanbe viewed asa mapS ×B −→ S ×B, whichprojectsanyoutputb ∈ Bofthedatabaseatastate s ∈ S toasanitized,public componentψ(s,b)ofthestateandtheoutputofthedatabase,andfiltersoutallprivate ϕ data.AnauthorizationpolicycanbesimilarlyviewedasamapS ×A→− S ×A,which projects any database state s ∈ S, and any user input a ∈ A (including the relevant credentials)to the authorizedcomponentϕ(s,a) of the state and the input. Since the publiccomponentsshouldnotcontainanyprivateresiduetobefilteredoutinasecond runofψ,andtheauthorizedcomponentsshouldnotcontainanyunauthorizedresidue, thepoliciesshouldbeidempotent,i.e. satisfytheequations ϕ◦ϕ=ϕ ψ◦ψ=ψ Such equations define projectors. There are at least two different ways to interpret projectors as policies. One is to view them as policy specifications. The database f ψ ϕ S ×A→− S ×BthenimplementsthepoliciesS ×B−→S ×BandS ×A→− S ×Aifit satisfiestheequation f = ψ◦ f ◦ϕ (3) whichiseasilyseentobeequivalenttothepairofequations ψ◦ f = f = f ◦ϕ (4) In other words, a compliant database only ever supplies public data, and only ever permitsauthorizedrequests. A different view to interpret projectors as policies is to view them as policy im- f plementations. The database S × A →− S × B then does not implement the policies ϕ itself,butneedstobeprecomposedwiththeauthorizationpolicyS ×A →− S ×Aand ψ postcomposedwiththeprivacypolicyS ×B −→ S ×B. However,sinceeachofthese f policiesregulatesthesamedatarelease,thedatabaseS ×A→− S ×Bisconsistentwith ψ ϕ thepoliciesS ×B−→S ×BandS ×A→− S ×Aifitsatisfiestheequation ψ◦ f = f ◦ϕ (5) It is obvious that compliance implies consistency. A consistent database, however, doesnothavetobecompliant. Thereasonisthataconsistentdatabasedoesnothave toimplementthepoliciesitself,butitrequiresseparatepolicyimplementationsatthe inputandattheoutput. Onitsown,suchadatabasemayacceptunauthorizedrequests and it may supply private data. Its consistency means that if we make sure that no 4 unauthorizedrequestsaresubmitted,thenwecanbesurethatnoprivateresponseswill besupplied,andviceversa. Moreprecisely,adatabase f isconsistentwiththepolicies ϕ and ψ whenever a request consistent with ϕ results in a response consistent with ψ, andallresponsesconsistentwith ψ canbeobtainedonrequestsconsistentwith ϕ. Sincethetwopoliciesthuspreciselyenforceeachotheronadatabaseconsistentwith them,theyimplementthesame datareleaseprocessonthisdatabase, whichcanthus beimplementedeitherasanauthorizationpolicy,orasaprivacypolicy. Lifting this distinction between compliance and consistency from databases and statemonads,toadistinctionbetweentwotypesofhomomorphismsbetweenprojec- tivealgebras,wearriveatthemainresultsofthepaper. 1.3 The setting and theresult EveryadjunctionF∗ ⊣ F :B→− Adetermines ∗ ←− • themonad F =F F∗ :A→− A,withtheinducedcategoriesof ∗ – freealgebrasA←−, F – projectivealgebrasA(cid:9),and ←− F ←− – allalgebrasAF, andontheotherhand →− • thecomonad F = F∗F :B→− B,withtheinducedcategoriesof ∗ – cofreecoalgebrasB→−, F – injectivecoalgebrasB(cid:9),and →− F →− – allcoalgebrasBF. ←− Theotherwayaround,givenamonad F : A→− A, anyadjunctionF∗ ⊣ F : B→− A ∗ ←− ←− →− such that F = F F∗ is a resolution of F; and given a comonad F : B →− B, any ∗ →− →− adjunction such that F = F∗F is a resolution of F. Each of the above categories ∗ defined for a monad (resp. for a comonad) gives its resolution. The definitions are standard,andcanbefoundintheAppendix. Inthispaper,weintroducethecategories of • projectivealgebraswithconsistentmorphismsA",and F • injectivecoalgebraswithconsistentmorphismsB#. F Weprovethefollowingequivalencesofcategories ←− →− AF ≃B# BF ≃A" (6) F F 5 undertheassumptionthatthecategoriesAandBareCauchy3complete,whichmeans thattheysplitidempotents. Thisisaverymildassumption,sincetheCauchycomple- tion,theweakestofallcategoricalcompletions,iseasytoconstructforanycategory, asspelledoutinProp.2.2. Overviewofthe paper Sec. 2 begins with a discussion about projectors, and analyzes projectors over free algebras,whichdetermineprojectivealgebras. InSec.3westate andprovethemain theorem,showingthatprojectorsoverfreealgebrascorrespondtocoalgebras.Wealso statethedualversion,whichsaysthatprojectorsovercofreecoalgebrascorrespondto algebras. In Sec. 4, we return to the motivating example from Sec. 1.2, and analyze thedifferentcategoricalformalisationsofdatareleasepolicies. Sec.5closesthepaper withcommentsabouttherelatedpastwork,andaboutthefuturework. 2 Projectors over algebras and coalgebras 2.1 Projectors ingeneral Consideranequalizerandcoequalizerdiagram ϕ E i A A q Q id foranarbitraryendomorphismϕ.Intuitively,theequalizerEconsistsofthefixedpoints ofϕ, whereasthecoequalizerQ isthequotientwhereeachelementof Aisidentified with all of its direct and inverse images along ϕ, which together form its orbit. The obviousmapE→− Qmapseachfixedpointintoauniqueorbit;butsomeorbitsmaynot containanyfixedpoints.Weareinterestedinthesituationwheneachorbitdoescontain a fixedpoint, so thateachequivalenceclassfrom Q hasa canonicalrepresentativein E. This means that the iterated applications of ϕ push each element of A along its orbittowardsafixedpoint. Itcanbeshownthatthissituationischaracterizedbythe requirementthatthefollowingcountablyextendeddiagramcommutes ϕ ϕ ϕ A A A ··· id In terms of elements, this means that for every x ∈ A there is some n ∈ N such that ϕn+1(x) = ϕn(x). Inotherwords,ϕthusequipsAwiththestructureofaforest,where theequivalenceclassesthatformQarethecomponenttrees,andtheelementsofEare theirroots.Projectorsarethespecialcaseofthissituation,wherealreadythediagram ϕ ϕ A A A id 3ThehabitofattributingcategoricalconceptstoXIXcenturymathematiciansandphilosophershasstyled theterminologyinsomepartsofcategorytheory. 6 commutes. The forest thus reduces to a shrub, where each component may branch at the rootas wide as it likes, but can onlygrow one layer tall, and cannotgrowany furtherbranches.Thefollowingsummarizes[7,Sec.IV.7.5]. Proposition2.1. If the endomorphism A →−ϕ A satisfies ϕ◦ϕ = ϕ, then for any pair q A B,thefollowingstatementsareequivalent: i (a) iisanequalizerandqisacoequalizerofϕandid B i q ϕ A A id (b) i◦q=ϕandq◦i=id. ϕ Definition 2.1. An endomorphism A →− A is called a projector (or idempotent) if q ϕ◦ϕ = ϕ. Its splitting is an object B with a pair of arrows A B such that i i◦q=ϕandq◦i=id. Moresuccinctly,wewriteA#ϕ B. Since the projectors and their splittings are defined by equations, every functor mustpreservethem.Sinceasplittingconsistsofanequalizerandacoequalizer,itisan equalizerandacoequalizerthatmustbepreservedbyallfunctors. Definition 2.2. A categorical property is called absolute when it is preserved by all functors. A category that has all absolute limits and absolute colimits is said to be Cauchycomplete. It follows from the results of [36], as well as from the differentapproach in [16, Sec.I.6.5],thatallabsolutelimitsandcolimitsboildowntosplittings. Proposition2.2. ForanycategoryCthefollowingstatementsareequivalent (a) CisCauchycomplete, (b) allprojectorssplitinC, (c) theobviousembeddingC֒→C(cid:9) isanequivalence,where |C(cid:9)| = {A→−ϕ A|ϕ◦ϕ=ϕ} a A∈|C| f  A B  C(cid:9)(A→−ϕ A,B−→ψ B) = f ∈C(A,B)(cid:12)(cid:12) ϕ ψ  (cid:12) f  (cid:12) A B  7 TheabsolutecompletionC(cid:9)issometimescalledKaroubienvelopeofC[7,Sec.IV.7.5]. Two categoriesare Morita equivalent when their Cauchy completionsare equivalent [16,Thm.7.9.4]. Notethattheconditionψ◦ f ◦ϕ = f isequivalentwiththerequire- mentthatboth f ◦ϕ= f andψ◦ f = f arevalid. Assumption. In the rest of this paper, we assume that each of the categories under consideration is Cauchy complete, i.e. that projectors split in it. Any category C that does not fulfill this assumption should be replaced by its Karoubi envelopeC(cid:9), describedinProp.2.2(c). 2.2 Projectivealgebras overfree algebras Inhomologicalalgebra,projectivemodulesareusuallydefinedasdirectsummandsof freemodules. In the terminologyofthe precedingsection, thismeansthattheyarise bysplittingtheprojectorsoverfreemodules. Itisnaturaltodefineprojectivealgebras inasimilarway:asprojectorsoverfreealgebras[22,§82]. Intheusual(Kleisli)viewofthecategoryoffreealgebras[32],reproducedinthe Appendix,amorphism f ∈A←−(A,B)isamorphismA→−f ←F−BinA,anditscomposition withg∈A←−(B,C),whichisBF→−g ←F−CinAisdefinedby F g◦←− f = A−−→f ←F−B−←−F−→g ←F−←F−C −−µ→←F−C ∈ A←−(A,C) F   F Aprojectorϕ∈A←−(A,A)overthefreealgebrageneratedbyAisthusanA-morphism F A →−ϕ ←F−Asuchthatϕ◦←F− ϕ = µA◦←F−ϕ◦ϕ = ϕ. Astheyexpand,thecalculationswith projectorsintheKleisliformofcategoryA←−dogetincreasinglyclumsy. ←− F Whenamonad F : A→− AisinducedbyanadjunctionF∗ ⊣ F : B→− Asothat ∗ ←− F = F F∗,thenthecategoryoffreealgebrascanbeequivalentlydefinedby ∗ |A←−| = |A| F A←−(X,Y) = B(F∗X,F∗Y) F Itiseasytocheckthatthenaturalbijections A(X,F F∗Y) (cid:27) B(F∗X,F∗Y) ∗ ←− maptheKleislicompositionofthemorphismsinA(X,FY)totheordinarycomposition ←− oftheiradjunctiontransposesinB(F∗X,F∗Y). Ifthehomomorphismsbetweenfree F- algebrasarepresentedastheelementsofB(F∗X,F∗Y),thenaprojectorϕ ∈ A←−(X,X) F is just a B-morphism F∗X →−ϕ F∗X such that ϕ◦ϕ = ϕ. The category of projective ←− F-algebrasand compliant homomorphisms(explainedin Sec. 1.2) is thusdefined as 8 follows: |A(cid:9)| = ϕ∈B(F∗X,F∗X) ϕ◦ϕ=ϕ ←F− Xa∈|A|n (cid:12)(cid:12)(cid:12) o (cid:12)  F∗X h F∗Y  A(cid:9)←F−(ϕ,ψ) = h∈B(F∗X,F∗Y)(cid:12)(cid:12) ϕ ψ   (cid:12)(cid:12) F∗X h F∗Y  whereψ ∈ B(F∗C,F∗C) is anotherprojectivealgebra, viewedas a projectoroverthe freealgebrageneratedbyC ∈|A|. 2.3 Projectivealgebras among allalgebras ←− ←− Thecategoryoffree F-algebrasA←− embedsfullyandfaithfullyintothecategoryAF ←− F ofall F-algebrasbythefunctor ←− A M AF (7) ←− F definedby X ∈ A←− F∗X→−h F∗Y ∈A←−(X,Y) (cid:12) F(cid:12) (cid:18) (cid:19) F (cid:18)←F−←F−X→−µ ←F−(cid:12)(cid:12) X(cid:19)(cid:12)(cid:12)∈(cid:12)A←F−(cid:12) and (cid:18)←F−X −F−∗→h ←F−Y(cid:19) ∈ A←F− µX,µY (cid:12) (cid:12) (cid:0) (cid:1) (cid:12) (cid:12) whereF hisanalgebrahomomorphismbecauseµ= F ε,andthenaturalityofεthus ∗ ∗ ←− ←− impliesF h◦µ =µ ◦ FF h. SincetheprojectorsinAF splitwhenevertheysplitin ∗ X Y ∗ A,asassumedhere,theembeddingMhasauniqueextensionM(cid:9), A(cid:9) M(cid:9) A←F− ←− F (8) M A ←− F ←− whichmapseachϕ∈|A(cid:9)|toasplittingαoftheprojectorF ϕ∈AF(µ ,µ ) ←− ∗ X X F ←F−←F−X ←F−q ←F−A ←F−i ←F−←F−X (9) µ α µ ←F−X q A i ←F−X F∗ϕ ←− ←− α ←−←− µ An F-algebraFA−→Aisthusprojectiveifitisaretractofsomefreealgebra FFX→− ←− ←− FX, i.e. if there are an X ∈ |A| and some homomorphismsq ∈ AF(µ ,α) and i ∈ X ←− AF(α,µ )suchthatq◦i=id. X 9 ←− α Itturnsout,however,thateachprojectivealgebra FA−→Aisnotjustaretractofa freealgebraoversomeX ∈|A|,butaretractofthefreealgebraoveritsowncarrierA. ←− α Proposition 2.3. An algebra FA −→ A is projective if and only if there is a unique ←− algebrahomomorphismα∈AF(α,µ )suchthatα◦α=id. A ←− ←− ←−←− ←− ←− FA Fα FFA Fα FA α µA α ←− A FA A α α ←− ←− Proof. Toconstructα ∈ AF(α,µ ),extendthealgebrahomomorphismq ∈ AF(µ ,α) A X ←− ←− ←− ←− ←− to F(q◦η)∈AF(µ ,µ )andprecomposewithi∈AF(α,µ ).Henceα= Fq◦Fη◦i∈ X A X ←− AF(α,µ ),asdisplayedinthemiddlerowofthefollowingdiagram. A ←F−A ←F−i ←F−←F−X ←F−←F−η ←F−←F−←F−X ←F−←F−q ←F−←F−A α µ µ µ ←− ←F−η ←−←− ←− A FX FFX FA i ←− Fq µ α id ←− FX A q ←− Thecommutativityoftheupperthreesquaresimpliesthatαisan F-algebrahomomor- phism. The commutativityof the lower square and the triangle implies that α◦α = q◦i=id. ←− α Toseethatαisunique,i.e. thatitistheonlywaytodisplay FA−→Aasasubalge- ←−←− µ ←− braof FFA→− FA,notethatthecompositehomomorphismα◦αisaprojectoronthe freealgebra←F−←F−A→−µ ←F−A,andthat←F−A։α Aisthesplittingofthisprojector. ←−←− ←− ←− ←− ←−←− Fα Fα FFA FA FFA µ α µ ←− ←− FA A FA α α Whilethesplittingofaprojectorisuniqueuptoanisomorphism,fixingonecomponent ofthesplittingdeterminestheotheroneon-the-nose:sinceαisanepi,α ◦α=α ◦α 0 1 impliesthatα =α . (cid:3) 0 1 The precedingpropositionthussays thateveryprojectivealgebra←F−A ։α A hasa uniqueembeddingA ֌α ←F−A intothefreealgebraµ overitscarrier A. With noloss A 10

See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.