/
A prettier printer Philip Wadler Joyce Kilmer and most computer scientists agree there A prettier printer Philip Wadler Joyce Kilmer and most computer scientists agree there

A prettier printer Philip Wadler Joyce Kilmer and most computer scientists agree there - PDF document

marina-yarberry
marina-yarberry . @marina-yarberry
Follow
428 views
Uploaded On 2014-11-13

A prettier printer Philip Wadler Joyce Kilmer and most computer scientists agree there - PPT Presentation

In our love a64256air with the tree it is parsed pattern matched pruned and printed A pretty printer is a tool often a library of routines that aids in converting a tree into text The text should occupy a minimal number of lines while retaining ind ID: 11428

our love a64256air

Share:

Link:

Embed:

Download Presentation from below link

Download Pdf The PPT/PDF document "A prettier printer Philip Wadler Joyce K..." is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.


Presentation Transcript

2Aprettierprinter1AsimpleprettyprinterTobegin,weconsiderthesimplecasewhereeachdocumenthasonlyonepossiblelayout|thatis,noattemptismadetocompressstructureontoasingleline.Therearesixoperatorsforthispurpose.�()::Doc�-Doc�-Docnil::Doctext::String�-Docline::Docnest::Int�-Doc�-Doclayout::Doc�-StringHere�istheassociativeoperationthatconcatenatestwodocuments,whichhastheemptydocumentnilasitsleftandrightunit.Thefunctiontextconvertsastringtothecorrespondingdocument,andthedocumentlinedenotesalinebreak;weadopttheconventionthatthestringpassedtotextdoesnotcontainnewlinecharacters,sothatlineisalwaysusedforthispurpose.Thefunctionnestaddsindentationtoadocument.Finally,thefunctionlayoutconvertsadocumenttoastring.(Inpractice,onemightchoosetomake(text"\n")behavelikeline,where"\n"isthestringconsistingofasinglenewline.)Onesimpleimplementationofsimpledocumentsisasstrings,with�asstringconcatenation,nilastheemptystring,textastheidentityfunction,lineasthestringconsistingofasinglenewline,nestiasthefunctionthataddsispacesaftereachnewline(toincreaseindentation),andlayoutastheidentityfunction.Thissimpleimplmentationisnotespeciallyecient,sincenestingexamineseverycharacterofthenesteddocument,nordoesitgeneralizeeasily.Wewillconsideramorealgebraicimplementationshortly.Notethatindentationisaddedonlyatanexplicitnewline,notatthebeginningofastring.ReadersfamiliarwithHughes'sprettyprintermay ndthischoicesurprising,butitispreciselythischoicethatenablestheuseofoneconcatenationoperatorratherthantwo.Asanexample,hereisasimpletreedatatype,andfunctionstoconvertatreetoadocument.dataTree=NodeString[Tree]showTree(Nodests)=texts�nest(lengths)(showBracketts)showBracket[]=nilshowBracketts=text"["�nest1(showTreests)�text"]"showTrees[t]=showTreetshowTrees(t:ts)=showTreet�text","�line�showTreestsThisproducesoutputinthefollowingstyle.aaa[bbbbb[ccc, 4AprettierprinterAndhereisitsnormalform.text"bbbbb["�nest2line�text"ccc,"�nest2line�text"dd"�nest0line�text"]"Hence,thedocumentprintsasfollows.bbbbb[ccc,dd]Thefollowinglawsareadequatetoreduceadocumenttonormalform,takentogetherwiththefactthat�isassociativewithunitnil.text(s++t)=texts�textttext""=nilnest(i+j)x=nesti(nestjx)nest0x=xnesti(x�y)=nestix�nestiynestinil=nilnesti(texts)=textsAllbutthelastlawcomeinpairs:eachlawonabinaryoperatorispairedwithacorrespondinglawforitsunit.The rstpairoflawsstatethattextisahomo-morphismfromstringconcatenationtodocumentconcatenation.Thenextpairoflawsstatethatnestisahomomorphismfromadditiontocomposition.Thepairafterthatstatethatnestdistributesthroughconcatenation.Thelastlawstatesthatnestingisabsorbedbytext.Inreducingatermtonormalform,the rstfourlawsareappliedlefttoright,whilethelastthreeareappliedrighttoleft.Wecanalsogivelawsthatrelateadocumenttoitslayout.layout(x�y)=layoutx++layoutylayoutnil=""layout(texts)=slayout(nestiline)='\n':copyi''The rsttwolawsstatethatlayoutisahomomorphismfromdocumentconcatena-tiontostringconcatenation.Inthissense,layoutistheinverseoftext,whichispreciselywhatthenextlawstates.The nallawstatesthatthelayoutofanestedlineisanewlinefollowedbyonespaceforeachlevelofindentation.Asimple,butadequate,implementationcanbederiveddirectlyfromtheal-gebraofdocuments.Werepresentadocumentasaconcatenationofitems,whereeachitemiseitheratextoralinebreakindentedagivenamount. 6Aprettierprinter2AprettyprinterwithalternativelayoutsWenowconsiderdocumentswithmultiplepossiblelayouts.Whereasbeforewemightviewadocumentasequivalenttoastring,nowwewillviewitasequivalenttoasetofstrings,eachcorrespondingtoadi erentlayoutofthesamedocument.Thisextensionisachievedbyaddingasinglefunction.group::Doc�-DocGivenadocument,representingasetoflayouts,groupreturnsthesetwithonenewelementadded,representingthelayoutinwhicheverythingiscompressedononeline.Thisisachievedbyreplacingeachnewline(andthecorrespondingindentation)withtextconsistingofasinglespace.(Variantsmightbeconsideredwhereeachnewlinecarrieswithitthealternatetextitshouldbereplacedby.Forinstance,somenewlinesmightbereplacedbytheemptytext,otherswithasinglespace.)Thefunctionlayoutisreplacedbyonethatchoosestheprettiestamongasetoflayouts.Ittakesasanadditionalparameterthepreferredmaximumlinewidthofthechosenlayout.pretty::Int�-Doc�-String(Variantsmightbeconsideredwithadditionalparameters,forinstancea`ribbonwidth'indicatingthemaximumnumberofnon-indentationcharactersthatshouldappearonaline.)Asanexample,hereisarevisionofthe rstformofthefunctiontoconvertatreetoadocument,whichdi ersbytheadditionofacalltogroup.showTree(Nodests)=group(texts�nest(lengths)(showBracketts))Ifthepreviousdocumentisprintedwithpretty30,thisde nitionproducesthefollowingoutput.aaa[bbbbb[ccc,dd],eee,ffff[gg,hhh,ii]]This tstreesontoonelinewherepossible,butintroducessucientlinebreakstokeepthetotalwidthlessthan30characters.Toformalizethesemanticsofthenewoperations,weaddtwoauxiliaryoper-ators.&#x|000;()::Doc&#x|000;-Doc&#x|000;-Docflatten::Doc&#x|000;-DocThe&#x|000;operatorformstheunionofthetwosetsoflayouts.Theflattenoperatorreplaceseachlinebreak(anditsassociatedindentation)byasinglespace.Adocumentalwaysrepresentsanon-emptysetoflayouts,wherealllayoutsintheset attentothesamelayout.Asaninvariant,werequirein(x&#x|000;y)thatall 8AprettierprinterdataDoc=Nil|String`Text`Doc|Int`Line`Doc|Doc`Union`DocTheseconstructorsrelatetothedocumentoperatorsasfollows.Nil=nils`Text`x=texts�xi`Line`x=nestiline�xx`Union`y=x&#x|000;yWenowhavetwoinvariantson(x`Union`y).Asbefore,werequirethatxandy attentothesamelayout.Additionally,werequirethatno rstlineofadocumentinxisshorterthansome rstlineofadocumentiny;or,equivalently,thatevery rstlineinxisatleastaslongasevery rstlineiny.WemustinsuretheseinvariantswhereverwecreataUnion.Toachieveacceptableperformance,wewillexploitthedistributivelaw,andusetherepresentation(s`Text`(x`Union`y))inpreferencetotheequivalent((s`Text`x)`Union`(s`Text`y)).Forinstance,considerthedocumentgroup(group(group(group(text"hello"ကline�text"a")�line�text"b")�line�text"c")�line�text"d")Thishasthefollowingpossiblelayouts:helloabchelloabhelloahellocbacbcTolaythisoutwithinamaximumwidthof5,wemustpickthelastofthese{andwewouldliketoeliminatetheothersinonefellswoop.Toachievethis,wepickarepresentationthatbringstothefrontanycommonstring.Forinstance,werepresenttheabovedocumentintheform"hello"`Text`((""`Text`x)`Union`(0`Line`y))forsuitabledocumentsxandy.Here"hello"hasbeenfactoredoutofallthelayoutsinxandy,and""hasbeenfactoredoutofallthelayoutsinx.Since"hello"followedby""occupies6charactersandthelinewidthis5,wemayimmediatelychoosetherightoperandof`Union`withoutfurtherexaminationofx,asdesired. 10Aprettierprintertexts�groupx={definitionText}s`Text`groupxDistributionisusedtobringtogetherthetwoinstancesoftextgeneratedbythede nitionofgroup.Aswesawabove,thisfactoringiscrucialinecientlychoosingarepresentation.Theotherlinesofgroupandflattenarealsoeasilyderived.Thelastlineofeachfollowsfromtheinvariantthatthetwooperandsofaunionboth attentothesamedocument.Next,itisnecessarytochoosethebestamongthesetofpossiblelayouts.Thisisdonewithafunctionbest,whichtakesadocumentthatmaycontainunions,andreturnsadocumentcontainingnounions.Amoment'sthoughtrevealsthatthisoperationrequirestwoadditionalparameters:onespeci estheavailablewidthw,andthesecondspeci esthenumberofcharacterskalreadyplacedonthecurrentline(includingindentation).Thecodeisfairlystraightforward.bestwkNil=Nilbestwk(i`Line`x)=i`Line`bestwixbestwk(s`Text`x)=s`Text`bestw(k+lengths)xbestwk(x`Union`y)=betterwk(bestwkx)(bestwky)betterwkxy=iffits(w-k)xthenxelseyThetwomiddlecasesadjustthecurrentposition:foranewlineitissettotheindentation,andfortextitisincrementedbythestringlength.Foraunion,thebetterofthebestofthetwooptionsisselected.Itisessentialforeciencythattheinnercomputationofbestisperformedlazily.Bytheinvariantforunions,no rstlineoftheleftoperandmaybeshorterthanany rstlineoftherightoperand.Hence,bythecriteriongivenpreviously,the rstoperandispreferredifit ts,andthesecondoperandotherwise.Itislefttodeterminewhetheradocument's rstline tsintowspaces.Thisisalsostraightforward.fitswx|w0=FalsefitswNil=Truefitsw(s`Text`x)=fits(w-lengths)xfitsw(i`Line`x)=TrueIftheavailablewidthislessthanzero,thenthedocumentcannot t.Otherwise,ifthedocumentisemptyorbeginswithanewlinethenit tstrivially,whileifthedocumentbeginswithtextthenit tsiftheremainingdocument tsintheremainingspace.Handlingnegativewidthsisnotmerelyesoteric,asthecasefortextmayyieldanegativewidth.Nocaseisrequiredforunions,sincethefunctionisonlyappliedtothebestlayoutofaset.Finally,toprettyprintadocumentoneselectsthebestlayoutandconvertsittoastring. 12Aprettierprinternil=NILx�y=x:ကynestix=NESTixtexts=TEXTsline=LINEAgain,asaninvariant,werequirein(x&#x|000;:y)thatalllayoutsinxandy attentothesamelayout,andthatno rstlineinxisshorterthanany rstlineiny.De nitionsofgroupandflattenarestraightforward.groupx=flattenx&#x|000;:xflattenNIL=NILflatten(x�:y)=flattenx�:flattenyflatten(NESTix)=flattenxflatten(TEXTs)=TEXTsflattenLINE=TEXT""flatten(x&#x|000;:y)=flattenxThesefollowimmediatelyfromtheequationsgivenpreviously.Therepresentationfunctionmapsalistofindentation-documentpairsintothecorrespondingdocument.repz=fold�()nil[nestix|(i,x)z]Theoperationto ndthebestlayoutofadocumentisgeneralizedtoactonalistofindentation-documentpairs.Thegeneralizedoperationisde nedbycomposingtheoldoperationwiththerepresentationfunction.bewkz=bestwk(repz)(hypothesis)Thenewde nitioniseasilyderivedfromtheold.bestwkx=bewk[(0,x)]bewk[]=Nilbewk((i,NIL):z)=bewkzbewk((i,x�:y):z)=bewk((i,x):(i,y):z)bewk((i,NESTjx):z)=bewk((i+j,x):z)bewk((i,TEXTs):z)=s`Text`bew(k+lengths)zbewk((i,LINE):z)=i`Line`bewizbewk((i,x&#x|000;:y):z)=betterwk(bewk((i,x):z))(bewk((i,y):z))Hereisthederivationofthe rstline.bestwkx={0isunitfornest}bestwk(nest0x) 14Aprettierprinter4ExamplesAnumberofconveniencefunctionscanbede ned.x&#x+000;y=x�text""�yx&#x/000;y=x�line�yfolddocf[]=nilfolddocf[x]=xfolddocf(x:xs)=fx(folddocfxs)spread=folddoc&#x+000;()stack=folddoc&#x/000;()Thereadermaycomeupwithmanyothers.Oftenalayoutconsistsofanopeningbracket,anindentedportion,andaclosingbracket.bracketlxr=group(textl�nest2(line�x)�line�textr)Thefollowingabbreviatesthesecondtreelayoutfunction.showBracket'ts=bracket"["(showTrees'ts)"]"Anotheruseofbracketappearsbelow.Thefunctionfillwordstakesastring,andreturnsadocumentthat llseachlinewithasmanywordsaswill t.Ituseswords,fromtheHaskellstandardlibrary,tobreakastringintoalistofwords.x&#x+/00;y=x�(text""&#x|000;:line)�yfillwords=folddoc&#x+/00;().maptext.wordsRecallthatwedonotexpose&#x|000;:totheuser,butx&#x+/00;ymaybesafelyex-posed,becauseitsatis estheinvariantrequiredby&#x|000;:.Bothtext""andline attentothesamelayout,andtheformerhasalonger rstlinethanthelatter.Alternatively,onecanrewritetheabovebynotingthat(text""&#x|000;:line)isequivalentto(groupline).Avariantoffillwordsisfill,whichcollapsesalistofdocumentsintoadocument.Itputsaspacebetweentwodocumentswhenthisleadstoreason-ablelayout,andanewlineotherwise.(IstolethisfunctionfromPeytonJones'sexpansionofHughes'sprettyprinterlibrary.)fill[]=nilfill[x]=xfill(x:y:zs)=(flattenx&#x+000;fill(flatteny:zs))&#x|000;:(x&#x/000;fill(y:zs)) 16Aprettierprinterhref="http://www.eg.com/" -52;倀link&#x/a00;elsewhere.&#x/p00;Observehowembeddedmarkupeitheris attenedorappearsonalinebyitself.Ifthetwooccurrencesofflattendidnotappearinfill,thenonemighthavelayoutssuchasthefollowing.color="red"font="Times"size="10"&#xp-52;倀Hereissomem00;emphasized&#x/em0;text.Hereisahref="http://www.eg.com/" ]TJ;&#x 10.;ѡ ;&#x-12.;॑ ;&#xTd[0;link&#x/a00;elsewhere.&#x/p00;Thislatterlayoutisnotsopretty,becausethestartandclosetagsoftheemphasisandanchorelementsarecrammedtogetherwithothertext,ratherthangettinglinestothemselves.5RelatedworkandconclusionAlgebraHugheshastwofundamentallydi erentconcatenationoperators.Hishor-izontalconcatenationoperator(alsowritten�)iscomplex:anynestingonthe rstlineofthesecondoperandiscancelled,andallsucceedinglinesofthesecondoperandmustbeindentedasfarasthetextonthelastlineofthe rstoperand.Hisverticalconcatenationoperator(written$$)issimple:italwaysaddsanewlinebetweendocuments.Foradetaileddescription,seeHughes(1995).Hughes'soperatorsarebothassociative,butassociatewitheachotherinonlyoneoftwopossibleways.Thatis,ofthetwoequations,x$$(y�z)=(x$$y)�zx�(y$$z)=(x�y)$$zthe rstholdsbuttheseconddoesnot.Horizontalconcatenationhasaleftunit,butbecausehorizontalcompositioncancelsnestingofitssecondargument,itisinherentlyinimicabletoarightunit.Verticalconcatenationalwaysaddsanewline,soithasneitherunit.Incomparison,hereeverythingisbasedonasingleconcatenationoperatorthatisassociativeandhasbothaleftandrightunit.Wecande neananalogueofverticalconcatenation.x&#x/000;y=x�line�yItfollowsimmediatelythat&#x/000;isassociative,andthat�and&#x/000;associatewitheachotherbothways,though&#x/000;hasneitherunit. 18Aprettierprinterexploitingthefactthattheindentationoperatordistributesthroughconcatenation.Onemightsay,theprettierprinterhatchedinBird'snest.6AcknowledgementsIthankRichardBird,KoenClaessen,JohnHughes,SamKamin,DanielJ.P.Leijen,Je reyLewis,ChrisOkasaki,SimonPeytonJones,andAndreasRossbergforcommentsonearlierversionsofthisnote.7Code--Theprettyprinterinfixr5&#x|000;:infixr6�:infixr6�dataDOC=NIL|DOC�:DOC|NESTIntDOC|TEXTString|LINE|DOC&#x|000;:DOCdataDoc=Nil|String`Text`Doc|Int`Line`Docnil=NILx�y=x�:ynestix=NESTixtexts=TEXTsline=LINEgroupx=flattenx&#x|000;:xflattenNIL=NILflatten(x�:y)=flattenx�:flattenyflatten(NESTix)=NESTi(flattenx)flatten(TEXTs)=TEXTsflattenLINE=TEXT""flatten(x&#x|000;:y)=flattenxlayoutNil="" 20Aprettierprinterfill[x]=xfill(x:y:zs)=(flattenx&#x+000;fill(flatteny:zs))&#x|000;:(x&#x/000;fill(y:zs))--TreeexampledataTree=NodeString[Tree]showTree(Nodests)=group(texts�nest(lengths)(showBracketts))showBracket[]=nilshowBracketts=text"["�nest1(showTreests)�text"]"showTrees[t]=showTreetshowTrees(t:ts)=showTreet�text","�line�showTreestsshowTree'(Nodests)=texts�showBracket'tsshowBracket'[]=nilshowBracket'ts=bracket"["(showTrees'ts)"]"showTrees'[t]=showTreetshowTrees'(t:ts)=showTreet�text","�line�showTreeststree=Node"aaa"[Node"bbbbb"[Node"ccc"[],Node"dd"[]],Node"eee"[],Node"ffff"[Node"gg"[],Node"hhh"[],Node"ii"[]]]testtreew=putStr(prettyw(showTreetree))testtree'w=putStr(prettyw(showTree'tree))--XMLexampledataXML=EltString[Att][XML]|TxtString 22Aprettierprinter[Hughes1995]JohnHughes.Thedesignofapretty-printerlibrary.InJ.JeuringandE.Meijer,editors,AdvancedFunctionalProgramming,SpringerVerlagLNCS925,1995.[Oppen1980]DerekOppen.Pretty-printing.ACMTransactionsonProgrammingLanguagesandSystems,2(4):1980.[PeytonJones1997]SimonPeytonJones.Haskellpretty-printerlibrary,1997.Availablefromhttp://www.haskell.org/libraries/#prettyprinting.