/
typeswouldimplementanequals typeswouldimplementanequals

typeswouldimplementanequals - PDF document

mitsue-stanley
mitsue-stanley . @mitsue-stanley
Follow
364 views
Uploaded On 2015-09-18

typeswouldimplementanequals - PPT Presentation

methodwhichcomparestheboxedvaluesBycontrastinJava alwaysmeansreferenceequalityonreferencetypesWhilethisisabitmoreecienttoimplementitalsointroducesaseriouscoherenceproblembecauseboxedversionso ID: 132533

methodwhichcomparestheboxedvalues.Bycontrast inJava == alwaysmeansref-erenceequalityonreferencetypes.Whilethisisabitmoreecienttoimplement italsointroducesaseriouscoherenceproblembecauseboxedversionso

Share:

Link:

Embed:

Download Presentation from below link

Download Pdf The PPT/PDF document "typeswouldimplementanequals" 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

typeswouldimplementanequals methodwhichcomparestheboxedvalues.Bycontrast,inJava,== alwaysmeansref-erenceequalityonreferencetypes.Whilethisisabitmoreecienttoimplement,italsointroducesaseriouscoherenceproblembecauseboxedversionsofequalvaluesmightnolongerbeequalwithrespectto== .Somesituationsrequirereferenceequalityinsteadofuser-denedequality.Anexampleishash-consing,whereeciencyisparamount.Forthesecases,classAnyRef de-nesanadditionaleq method,whichcannotbeoverridden,andisimplementedasreferenceequality(i.e.,itbehaveslike== inJavaforreferencetypes).3.2OperationsAnotheraspectofScala'suniedobjectmodelisthatev-eryoperationisamessagesend,thatis,theinvocationofamethod.Forinstancetheadditionx+y isinterpretedasx.+(y) ,i.e.theinvocationofthemethod+ withx asthereceiverobjectandy asthemethodargument.Thisidea,whichhasbeenappliedoriginallyinSmalltalk,isadaptedtothemoreconventionalsyntaxofScalaasfollows.First,Scalatreatsoperatornamesasordinaryidentiers.Moreprecisely,anidentieriseitherasequenceoflettersanddigitsstartingwithaletter,orasequenceofoperatorchar-acters.Hence,itispossibletodenemethodscalled+ , ,or:: ,forexample.Next,Scalatreatseveryoccurrenceofanidentierbetweentwoexpressionsasamethodcall.Forinstance,inListing 1 ,onecouldhaveusedtheoperatorsyn-tax(argstartsWith"­") assyntacticsugarforthemoreconventionalsyntax(arg.startsWith("­")) .Asanexamplehowuser-denedoperatorsaredeclaredandapplied,considerthefollowingimplementationofaclassNat fornaturalnumbers.Thisclass(veryine-ciently)representsnumbersasinstancesoftwoclassesZero andSucc .ThenumberNwouldhenceberepresentedasnewSuccN(Zero) .Westarttheimplementationwithanab-stractclassspecifyingtheoperationssupportedbynaturalnumbers.AccordingtothedenitionofclassNat ,naturalnumbersprovidetwoabstractmethodsisZero ,andpred ,aswellasthreeconcretemethodssucc ,+ ,and­ .abstractclassNat{defisZero:booleandefpred:Natdefsucc:Nat=newSucc(this)def+(x:Nat):Nat=if(x.isZero)thiselsesucc+x.preddef­(x:Nat):Nat=if(x.isZero)thiselsepred­x.pred} NotethatScalaallowsonetodeneparameterlessmethodssuchasisZero ,pred ,andsucc inclassNat .Suchmethodsareinvokedeverytimetheirnameisselected;noargumentlistispassed.Notealsothatabstractclassmembersareidentiedsyntacticallybecausetheylackadenition;noadditionalabstract modierisneededforthem.WenowextendclassNat withasingletonobjectZero andaclassforrepresentingsuccessors,Succ .objectZeroextendsNat{defisZero:boolean=truedefpred:Nat=thrownewError("Zero.pred")overridedeftoString:String="Zero"} classSucc(n:Nat)extendsNat{defisZero:boolean=falsedefpred:Nat=noverridedeftoString:String="Succ("+n+")"} TheSucc classillustratesadierencebetweentheclassdef-initionsyntaxofScalaandJava.InScala,constructorpa-rametersfollowtheclassname;noseparateclassconstructordenitionwithinthebodyofSucc isneeded.Thisconstruc-toriscalledtheprimaryconstructor;thewholebodyoftheclassisexecutedwhentheprimaryconstructoriscalledatthetimetheclassisinstantiated.Thereissyntaxforsec-ondaryconstructorsincasemorethanoneconstructorisdesired(seeSection5.2.1in[ 35 ]).TheZero objectandtheSucc classbothimplementthetwoabstractmethodsoftheirparentclass,Nat .TheyalsooverridethetoString methodwhichtheyinheritfromclassAny .Theoverride modierisrequiredinScalaformethodsthatoverrideaconcretemethodinsomeinheritedclass;itisoptionalformethodsthatimplementsomeabstractmethodintheirsuperclass.Themodiergivesusefulredundancytoprotectagainsttwocommonclassoferrors.Oneclassoferrorsareaccidentaloverrides,whereamethodinasub-classunintentionallyoverridesamethodinasuperclass.InthatcasetheScalacompilerwouldcomplainaboutamissingoverride modier.Theotherclassoferrorsarebrokenover-ridinglinks.Thesearisewhentheparametersofamethodinasuperclassarechanged,butoneforgetstochangetheparametersofanoverridingmethodinasubclass.Insteadofsilentlyconvertingtheoverridetoanoverloading,theScalacompilerwouldinthiscasecomplainthatthemethodinthesubclassoverridesnothing.Theabilitytohaveuser-denedinxoperatorsraisesthequestionabouttheirrelativeprecedenceandassociativ-ity.Onepossibilitywouldbetohavexity-declarationsinthestyleofHaskellorSML,whereuserscandeclarethesepropertiesofanoperatorindividually.However,suchdecla-rationstendtointeractbadlywithmodularprogramming.Scalaoptsforasimplerschemewithxedprecedencesandassociativities.Theprecedenceofaninxoperatorisdeter-minedbyitsrstcharacter;itcoincideswiththeoperatorprecedenceofJavaforthoseoperatorsthatstartwithanoperatorcharacterusedintheselanguages.Thefollowinglistsoperatorsinincreasingprecedence:(allletters)|^&&#x-520;=!:+­*/%(allotherspecialcharacters) Operatorsareusuallyleft-associative,i.e.x+y+z isinterpretedas(x+y)+z .Theonlyexceptiontothatruleareoperatorsendinginacolon.Thesearetreatedasright-associative.Anexampleisthelist-consingoperator:: .Here,x::y::zs isinterpretedasx::(y::zs) .Right-associativeoperatorsarealsotreateddierentlywithrespecttomethodlookup.Whereasnormaloperatorstaketheirleftoperandasreceiver,right-associativeoperatorstaketheirrightoperandasreceiver.Forinstance,thelist 4 Here,valx­xs isagenerator,whichproducesasequenceofvalues,and0x isalter,whicheliminatessomeoftheproducedvaluesfromconsideration.Thecomprehensionreturnsanothersequenceformedfromthevaluesproducedbytheyield part.Therecanbeseveralgeneratorsandltersinacomprehension.Forcomprehensionsaremappedtocombinationsinvolv-ingthehigher-ordermethodsmap ,flatMap ,andfilter .Forinstance,theformulationofthesqrts methodabovewouldbemappedtothepreviousimplementationofsqrts inSec-tion 4.4 .Thepowerofforcomprehensionscomesfromthefactthattheyarenottiedtoaparticulardatatype.Theycanbeconstructedoveranycarriertypethatdenesap-propriatemap ,flatMap ,andfilter methods.Thisincludesallsequencetypes 2 ,optionalvalues,databaseinterfaces,aswellasseveralothertypes.Scalausersmightapplyfor-comprehensionstotheirowntypes,aslongasthesedenetherequiredmethods.ForloopsaresimilartocomprehensionsinScala.Theyaremappedtocombinationsinvolvingmethodsforeach andfilter .Forinstance,theforloopfor(valarg­args)... inListing 1 ismappedtoargsforeach(arg=�...) 5AbstractionAnimportantissueincomponentsystemsishowtoabstractfromrequiredcomponents.Therearetwoprincipalformsofabstractioninprogramminglanguages:parameterizationandabstractmembers.Therstformistypicallyfunctionalwhereasthesecondformistypicallyobject-oriented.Tra-ditionally,Javasupportedfunctionalabstractionforvaluesandobject-orientedabstractionforoperations.ThenewJava5.0withgenericssupportsfunctionalabstractionalsofortypes.Scalasupportsbothstylesofabstractionuniformlyfortypesaswellasvalues.Bothtypesandvaluescanbepa-rameters,andbothcanbeabstractmembers.TherestofthissectionpresentsbothstylesandreviewsatthesametimealargepartofScala'stypesystem.5.1FunctionalAbstractionThefollowingclassdenescellsofvaluesthatcanbereadandwritten.classGenCell[T](init:T){privatevarvalue:T=initdefget:T=valuedefset(x:T):unit={value=x}} TheclassabstractsoverthevaluetypeofthecellwiththetypeparameterT .Wealsosay,classGenCell isgeneric.Likeclasses,methodscanalsohavetypeparameters.Thefollowingmethodswapsthecontentsoftwocells,whichmustbothhavethesamevaluetype.defswap[T](x:GenCell[T],y:GenCell[T]):unit={valt=x.get;x.set(y.get);y.set(t) 2Arraysdonotyetdeneallofsequencemethods,becausesomeofthemrequirerun-timetypes,whicharenotyetimplemented } Thefollowingprogramcreatestwocellsofintegersandthenswapstheircontents.valx:GenCell[int]=newGenCell[int](1)valy:GenCell[int]=newGenCell[int](2)swap[int](x,y) Actualtypeargumentsarewritteninsquarebrackets;theyreplacetheformalparametersofaclassconstructorormethod.Scaladenesasophisticatedtypeinferencesys-temwhichpermitstoomitactualtypeargumentsinbothcases.Typeargumentsofamethodorconstructorarein-ferredfromtheexpectedresulttypeandtheargumenttypesbylocaltypeinference[ 41 , 39 ].Hence,onecanequivalentlywritetheexampleabovewithoutanytypearguments:valx=newGenCell(1)valy=newGenCell(2)swap(x,y) Parameterbounds.ConsideramethodupdateMax whichsetsacelltothemaximumofthecell'scurrentvalueandagivenparametervalue.WewouldliketodeneupdateMax sothatitworksforallcellvaluetypeswhichadmitacompar-isonfunction denedintraitOrdered .Forthemomentassumethistraitisdenedasfollows(amorerenedversionisinthestandardScalalibrary).traitOrdered[T]{def(x:T):boolean} TheupdateMax methodcanbedenedinagenericwaybyusingboundedpolymorphism:defupdateMax[T:Ordered[T]](c:GenCell[T],x:T)=if(c.getx)c.set(x) Here,thetypeparameterclause[TOrdered[T]] intro-ducesaboundedtypeparameterT .ItrestrictsthetypeargumentsforT tothosetypesTthatareasubtypeofOrdered[T] .Therefore,the methodofclassOrdered canbeappliedtoargumentsoftypeT .Theexampleshowsthattheboundedtypeparametermayitselfappearaspartofthebound,i.e.ScalasupportsF-boundedpolymorphism[ 10 ].Variance.Thecombinationofsubtypingandgenericsinalanguageraisesthequestionhowtheyinteract.IfCisatypeconstructorandSisasubtypeofT,doesonealsohavethatC[S]isasubtypeofC[T]?Typeconstructorswiththispropertyarecalledcovariant.ThetypeconstructorGenCell shouldclearlynotbecovariant;otherwiseonecouldconstructthefollowingprogramwhichleadstoatypeerroratruntime.valx:GenCell[String]=newGenCell[String]("abc")valy:GenCell[Any]=x;//illegal!y.set(1)valz:String=y.get ItisthepresenceofamutablevariableinGenCell whichmakescovarianceunsound.Indeed,aGenCell[String] isnotaspecialinstanceofaGenCell[Any] sincetherearethingsonecandowithaGenCell[Any] thatonecannotdo 7 }} Thetop-levelclassSubjectObserver hastwomemberclasses:oneforsubjects,theotherforobservers.TheSubject classdenesmethodssubscribe andpublish .Itmaintainsalistofallregisteredobserversintheprivatevariableobservers .TheObserver traitonlydeclaresanabstractmethodnotify .NotethattheSubject andObserver classesdonotdi-rectlyrefertoeachother,sincesuchhardreferenceswouldpreventcovariantextensionsoftheseclassesinclientcode.Instead,SubjectObserver denestwoabstracttypesS andO whichareboundedbytherespectiveclasstypesSubject andObserver .Thesubjectandobserverclassesusetheseabstracttypestorefertoeachother.NotealsothatclassSubject carriesanexplicitrequires annotation:abstractclassSubjectrequiresS{... TheannotationexpressesthatSubject canonlybeinstanti-atedasapartofaclassthatalsoconformstoS .Here,S iscalledaself-typeofclassSubject .Whenaself-typeisgiven,itistakenasthetypeofthis insidetheclass(withoutaself-typeannotationthetypeofthis istakenasusualtobethetypeoftheclassitself).InclassSubject ,theself-typeisnecessarytorenderthecallobs.notify(this) type-correct.Self-typescanbearbitrary;theyneednothavearela-tionwiththeclassbeingdened.Typesoundnessisstillguaranteed,becauseoftworequirements:(1)theself-typeofaclassmustbeasubtypeoftheself-typesofallitsbaseclasses,(2)wheninstantiatingaclassinanew expression,itischeckedthattheselftypeoftheclassisasupertypeofthetypeoftheobjectbeingcreated.Themechanismdenedinthepublish/subscribepatterncanbeusedbyinheritingfromSubjectObserver ,deningapplicationspecicSubject andObserver classes.Anex-ampleistheSensorReader objectbelowthattakessensorsassubjectsanddisplaysasobservers.objectSensorReaderextendsSubjectObserver{typeS=SensortypeO=DisplayabstractclassSensorextendsSubject{vallabel:Stringvarvalue:double=0.0defchangeValue(v:double)={value=vpublish}}classDisplayextendsObserver{defprintln(s:String)=...defnotify(sub:Sensor)=println(sub.label+" has value "+sub.value)}} Inthisobject,typeS isboundtoSensor whereastypeO isboundtoDisplay .Hence,thetwoformerlyabstracttypesarenowdenedbyoverridingdenitions.Thistyingtheknotisalwaysnecessarywhencreatingaconcreteclassin-stance.Ontheotherhand,itwouldalsohavebeenpossibletodeneanabstractSensorReader classwhichcouldbere-nedfurtherbyclientcode.Inthiscase,thetwoabstract typeswouldhavebeenoverriddenagainbyabstracttypedenitions.classAbsSensorReaderextendsSubjectObserver{typeS:SensortypeO:Display...} ThefollowingprogramillustrateshowtheSensorReader ob-jectisused.objectTest{importSensorReader._vals1=newSensor{vallabel="sensor1"}vals2=newSensor{vallabel="sensor2"}defmain(args:Array[String])={vald1=newDisplay;vald2=newDisplays1.subscribe(d1);s1.subscribe(d2)s2.subscribe(d1)s1.changeValue(2);s2.changeValue(3)}} Notethepresenceofanimport clause,whichmakesthemembersofobjectSensorReader availablewithoutprextothecodeinobjectTest .ImportclausesinScalaaremoregeneralthanimportclausesinJava.Theycanbeusedanywhere,andcanimportmembersfromanyobject,notjustfromapackage.5.3ModelingGenericswithAbstractTypesThepresenceoftwotypeabstractionfacilitiesinonelan-guageraisesthequestionoflanguagecomplexitycouldwehavedonewithjustoneformalism?Inthissectionweshowthatfunctionaltypeabstraction(akagenerics)canindeedbemodeledbyobject-orientedtypeabstraction(akaabstracttypes).Theideaoftheencodingisasfollows.AssumeyouhaveaparameterizedclassCwithatypeparametert(theencodinggeneralizesstraightforwardlytomultipletypeparameters).Theencodinghasfourparts,whichaecttheclassdenitionitself,instancecreationsoftheclass,baseclassconstructorcalls,andtypeinstancesoftheclass. 1. TheclassdenitionofCisre-writtenasfollows.classC{typet/*restofclass*/} Thatis,parametersoftheoriginalclassaremodeledasabstractmembersintheencodedclass.Ifthetypeparameterthaslowerand/orupperbounds,thesecarryovertotheabstracttypedenitionintheencoding.Thevarianceofthetypeparameterdoesnotcarryover;variancesinuenceinsteadtheformationoftypes(seePoint4below). 2. EveryinstancecreationnewC[T] withtypeargumentTisrewrittento:newC{typet=T} 3. IfC[T] appearsasasuperclassconstructor,theinher-itingclassisaugmentedwiththedenition 10 class.Aclasswithincompletemembersmustbedeclaredabstractitself,andsubclassesofitcanbeinstantiatedonlyonceallmembersoverriddenbysuchincompletemembershavebeenredened.Callstosupermaybethreadedsothattheyfollowtheclasslinearization(thisisamajordierencebetweenScala'smixincompositionandmultipleinheritanceschemes).Forexample,consideranotherclasssimilartoSyncIterator whichprintsallreturnedelementsonstandardoutput.traitLoggedIterator[T]extendsAbsIterator[T]{abstractoverridedefnext:T={valx=super.next;System.out.println(x);x}} Onecancombinesynchronizedwithloggediteratorsinamixincomposition:classIter2extendsStringIterator(someString)withSyncIterator[char]withLoggedIterator[char] ThelinearizationofIter2 is{Iter2,LoggedIterator,SyncIterator,StringIterator,AbsIterator,AnyRef,Any} Therefore,classIter2 inheritsitsnext methodfromclassLoggedIterator ,thesuper.next callinthismethodreferstothenext methodinclassSyncIterator ,whosesuper.next callnallyreferstothenext methodinclassStringIterator .Ifloggingshouldbeincludedinthesynchronization,thiscanbeachievedbyreversingtheorderofthemixins:classIter2extendsStringIterator(someString)withLoggedIterator[char]withSyncIterator[char] Ineithercase,callstonext followviasuperthelinearizationofclassIter2 .6.1Service-OrientedComponentModelScala'sclassabstractionandcompositionmechanismcanbeseenasthebasisforaservice-orientedsoftwarecomponentmodel.Softwarecomponentsareunitsofcomputationthatprovideawell-denedsetofservices.Typically,asoftwarecomponentisnotself-contained;i.e.,itsserviceimplemen-tationsrelyonasetofrequiredservicesprovidedbyothercooperatingcomponents.InScala,softwarecomponentscorrespondtoclassesandtraits.Theconcretemembersofaclassortraitrepresenttheprovidedservices,deferredmemberscanbeseenastherequiredservices.Thecompositionofcomponentsisbasedonmixins,whichallowprogrammerstocreatebiggercom-ponentsfromsmallerones.Themixin-classcompositionmechanismofScalaiden-tiesserviceswiththesamename;forinstance,ade-ferredmethodmcanbeimplementedbyaclassCden-ingaconcretemethodmsimplybymixing-inC.Thus,thecomponentcompositionmechanismassociatesautomat-icallyrequiredwithprovidedservices.Togetherwiththerulethatconcreteclassmembersalwaysoverridedeferredones,thisprincipleyieldsrecursivelypluggablecomponents wherecomponentservicesdonothavetobewiredexplic-itly[ 48 ].Thisapproachsimpliestheassemblyoflargecompo-nentswithmanyrecursivedependencies.Itscaleswelleveninthepresenceofmanyrequiredandprovidedservices,sincetheassociationofthetwoisautomaticallyinferredbythecompiler.Themostimportantadvantageovertraditionalblack-boxcomponentsisthatcomponentsareextensibleen-tities:theycanevolvebysubclassingandoverriding.Theycanevenbeusedtoaddnewservicestootherexistingcom-ponents,ortoupgradeexistingservicesofothercompo-nents.Overall,thesefeaturesenableasmoothincrementalsoftwareevolutionprocess.7Decomposition7.1Object-OrientedDecompositionOftenprogrammershavetodealwithstructureddata.Inanobject-orientedlanguage,structureddatawouldtypicallybeimplementedbyasetofclassesrepresentingthevariousstructuralconstructs.Forinspectingstructureddata,apro-grammercansolelyrelyonvirtualmethodcallsofmethodsprovidedbysuchclasses.Supposewewanttoimplementasimpleevaluatorforalgebraictermsconsistingofnumbersandabinaryplusop-eration.Usinganobject-orientedimplementationscheme,wecandecomposetheevaluatoraccordingtothetermstruc-tureasfollows:abstractclassTerm{defeval:int}classNum(x:int)extendsTerm{defeval:int=x}classPlus(left:Term,right:Term)extendsTerm{defeval:int=left.eval+right.eval} ThegivenprogrammodelstermswiththeabstractclassTerm whichdenesadeferredeval method.Concretesub-classesofTerm modelthevarioustermvariants.Suchclasseshavetoprovideconcreteimplementationsformethodeval .Suchanobject-orienteddecompositionschemerequirestheanticipationofalloperationstraversingagivenstruc-ture.Asaconsequence,eveninternalmethodssometimeshavetobeexposedtosomedegree.Addingnewmethodsistediousanderror-prone,becauseitrequiresallclassestobeeitherchangedorsubclassed.Arelatedproblemisthatimplementationsofoperationsaredistributedoverallparticipatingclassesmakingitdiculttounderstandandchangethem.7.2PatternMatchingOverClassHierarchiesTheprogramaboveisagoodexampleforcaseswhereafunctionaldecompositionschemeismoreappropriate.Inafunctionallanguage,aprogrammertypicallyseparatesthedenitionofthedatastructurefromtheimplementationoftheoperations.Whiledatastructuresareusuallydenedusingalgebraicdatatypes,operationsonsuchdatatypesaresimplyfunctionswhichusepatternmatchingasthebasicdecompositionprinciple.Suchanapproachmakesitpos-sibletoimplementasingleeval functionwithoutexposing 13 articialauxiliaryfunctions.Scalaprovidesanaturalwayfortacklingtheabovepro-grammingtaskinafunctionalwaybysupplyingthepro-grammerwithamechanismforcreatingstructureddatarepresentationssimilartoalgebraicdatatypesandadecom-positionmechanismbasedonpatternmatching.Insteadofaddingalgebraictypestothecorelanguage,Scalaenhancestheclassabstractionmechanismtosimplifytheconstructionofstructureddata.Classestaggedwiththecase modierautomaticallydeneafactorymethodwiththesameargumentsastheprimaryconstructor.Fur-thermore,Scalaintroducespatternmatchingexpressionsinwhichitispossibletousesuchconstructorsofcaseclassesaspatterns.Usingcaseclasses,thealgebraictermexamplecanbeimplementedasfollows:abstractclassTermcaseclassNum(x:int)extendsTermcaseclassPlus(left:Term,right:Term)extendsTerm Giventhesedenitions,itisnowpossibletocreatethealge-braicterm1+2+3withoutusingthenew primitive,simplybycallingtheconstructorsassociatedwithcaseclasses:Plus(Plus(Num(1),Num(2)),Num(3)). Scala'spatternmatchingexpressionsprovideameansofde-compositionthatusestheseconstructorsaspatterns.Hereistheimplementationoftheeval functionusingpatternmatching:objectInterpreter{defeval(term:Term):int=termmatch{caseNum(x)=�xcasePlus(left,right)=�eval(left)+eval(right)}} Thematchingexpressionxmatch{casepat1�=e1 casepat2�=e2...} matchesvaluexagainstthepatternspat1,pat2,etc.inthegivenorder.TheprogramaboveusespatternsoftheformConstr(x1;:::;xn)whereConstrreferstoacaseclassconstructorandxidenotesavariable.Anob-jectmatchessuchapatternifitisaninstanceofthecorre-spondingcaseclass.Thematchingprocessalsoinstantiatesthevariablesoftherstmatchingpatternandexecutesthecorrespondingright-hand-side.Suchafunctionaldecompositionschemehastheadvan-tagethatnewfunctionscanbeaddedeasilytothesystem.Ontheotherhand,integratinganewcaseclassmightre-quirechangesinallpatternmatchingexpressions.Someap-plicationsmightalsoprotfromthepossibilityofdeningnestedpatterns,orpatternswithguards.Forinstance,thepatterncasePlus(x,y)ifx==y�=... matchesonlytermsoftheformt+t .Theequivalenceofthetwovari-ablesx andy inthepreviouspatternisestablishedwiththehelpoftheguardx==y .8XMLProcessingXMLisapopulardataformat.Scalaisdesignedtoeasecon-structionandmaintenanceofprogramsthatdealwithXML.ItprovidesadatamodelforXMLbymeansoftraitsandparticularsubclasses.ProcessingofXMLcanthenbedonebydeconstructingthedatausingScala'spatternmatchingmechanism. 8.1DataModelScala'sdatamodelforXMLisanimmutablerepresentationofanorderedunrankedtree.Insuchatreeeachnodehasalabel,asequenceofchildrennodes,andamapfromat-tributekeystoattributevalues.Thisisspeciedinthetraitscala.xml.Node whichadditionallycontainsequivalentsoftheXPathoperatorschildanddescendant-or-self,whicharewritten\ and\\ .Concretesubclassesexistforelements,textnodes,comments,processinginstructions,andentityreferences.XMLsyntaxcanbeuseddirectlyinaScalaprogram,e.g.,invaluedenitions.vallabPhoneBook=phonebook䘀descr䈀Phonenumbersofb㐀XML/b✀hackers./descr␀entry䈀name䀀Burak/name✀phonewhere="work"䜀+41216936867/phone phonewhere="mobile"䜀+41786015436/phone /entry /phonebook ; ThevaluelabPhoneBook isanXMLtree;oneofitsnodeshasthelabelphone ,achildsequenceconsistingofatextnodelabeledby+412.. ,andamapfromtheattributekeywhere tothevalue"work" .WithinXMLsyntaxitispossibletoes-capetoScalausingthebrackets{ and} (similartothecon-ventionusedinXQuery).Forexample,adate nodewithachildtextnodeconsistingofthecurrentdatecanbedenedbyÚte;df.format(newjava.util.Date())&#x/dat;} .8.2SchemaValidationTypesofXMLdocumentsaretypicallyspeciedbysocalledschemas.PopularschemaformalismsareDTDs(Docu-mentTypeDenitions)[ 7 ],XMLSchema[ 19 ],andRELAXNG[ 33 ].AtthismomentasimplesupportforDTDsisavailablethroughthedtd2scala tool.ItconvertsaDTDtoasetofclassdenitionswhichcanonlybeinstantiatedwithXMLdatathatisvalidwithrespecttotheDTD.ExistingXMLdocumentscanthenbevalidatedagainsttheDTDbyusingaspecialloadmethodwhichtriestoinstantiatethecorrespondingclasses(usingpatternmatching).Inthefu-ture,supportfortherichersetoftypesofXMLSchemaisplanned,includingstatictypecheckingthroughregulartypes.8.3SequenceMatchingXMLnodescanbedecomposedusingpatternmatching.ScalaallowstouseXMLsyntaxheretoo,albeitonlytomatchelements.Thefollowingexampleshowshowtoaddanentrytoaphonebook element.importscala.xml.Node;defadd(phonebook:Node,newEntry:Node):Node=phonebookmatch{casephonebook䘀{cs@_*}/phonebook␀=␀phonebook䘀{cs}{newEntry}/phonebook␀}valnewPhoneBook=add(scala.xml.XML.loadFile("savedPhoneBook"),entry䈀name䀀Sebastian/name✀phonewhere="work"䜀+41216936867/phone✀ 14 /entry ); Theadd functionperformsamatchonthephonebook ele-ment,bindingitschildsequencetothevariablecs (thepat-tern_* matchesanarbitrarysequence).Thenitconstructsanewphonebookelementwithchildsequencecs followedbythenodenewEntry .Sequencepatternsconsistingoforendingin_* extendconventionalalgebraicpatternsdiscussedinSection 7 .withthepossibilityofmatchingzerotoarbitrarymanyelementsofasequence.Theycanbeappliedtoanysequence,i.e.anyinstanceofSeq[A] andtocaseclassesthattakerepeatedparameters.Thefollowingexampleillustratestheiruse.deffindRest(z:Seq[Char]):Seq[Char]=zmatch{caseSeq('G','o','o','g','l','e',rest@_*)=�rest} Thispatternisusedtocheckthatastringstartswiththesequenceofletters"Google" .Iftheinputz matches,thenthefunctionreturnswhatremainsaftertheoccurrence,oth-erwiseitgeneratesaruntimeerror.ApreviousversionofScalasupportedgeneralregularexpressions,butitseemedthespecialcasedescribedabovesucesinmostreallifescenarios,andavoidsdetectionandtranslationoftop-downnon-deterministicregulartreepatterns,whichinteractbadlywithScala'srichpatternlanguage.8.4XMLQueriesthroughForComprehensionApatternmatchdeterminesatmostonematchofapattern.WhenqueryingXMLoneisofteninterestedinlocatingallmatchestoaquery.Scala'sexiblecomprehensionmecha-nismcanbeusedtoqueryXMLinaconciseandelegantstylethatcloselyresemblesXQuery.Inthefollowingexam-ple,weselectallentry elementsfromlabAddressbook andfromlabPhoneBook intothevariablesa andp ,respectively.Wheneverthenamecontentsoftwosuchentriescoincide,aresult elementisgeneratedwhichhasaschildrenthead-dressandphonenumber,takenfromtheappropriateentry.for(vala­labAddressBook\\"entry";valp­labPhoneBook\\"entry";a\"name"==p\"name")yieldresult䌀{a.child}{p\"phone"}/result␀ 9ComponentAdaptationEvencomponentsystemswithpowerfulconstructsforab-stractionandcompositionfaceaproblemwhenitcomestointegratingsub-systemsdevelopedbydierentgroupsatdierenttimes.Theproblemisthattheinterfaceofacom-ponentdevelopedbyonegroupisoftennotquiterightforclientswhowishtousethatcomponent.Forinstance,con-sideralibrarywithaclasslikeGenList fromSection 5 .Aclientofthislibrarymightwishtotreatsuchlistsassets,supportingoperationssuchasmemberinclusionorcontain-menttests.However,theprovideroftheclassmightnothavethoughtofthisusagescenario,andconsequentlymighthaveleftoutthesemethodsfromtheinterfaceofGenList .Onemightarguethatinheritancecanallowclientstotai-lorthesupportedmethodsofaclasstotheirrequirements;howeverthisisonlytrueifaclienthascontroloverallcre- ationsitesoftheclass.Ifthelibraryalsoreturnsanopera-tionsuchasdeffromArray(xs:Array[T]):GenList[T] theninheritancecannotbeusedtoturnaGenList intoaSetList afterithasbeenreturnedfrommethodfromArray .Onecancircumventthisrestrictiontosomedegreebyin-cludingfactorymethods[ 21 ]inlibraries.However,thisin-volvesfairlycomplicatedframeworkswhicharediculttolearnandinstantiate,anditfailsforlibrarycomponentsthatinheritfromclassesthatneedtobeextendedbyclients.Thisunsatisfactorysituationiscommonlycalledtheex-ternalextensibilityproblem.Ithasbeenarguedthatthisproblemholdsbackthedevelopmentofsoftwarecomponentstoamatureindustrywherecomponentsareindependentlymanufacturedanddeployed[ 28 ].Scalaintroducesanewconcepttosolvetheexternalex-tensibilityproblem:viewsallowonetoaugmentaclasswithnewmembersandsupportedtraits.Viewsareaspecialcaseofimplicitparameterswhicharethemselvesausefultoolfororganizingrichfunctionalityinsystems.ImplicitparametersletonewritegenericcodeanalogoustoHaskell'stypeclasses[ 12 ],or,inaC++con-text,toSiekandLumsdaine'sconcepts[ 43 ].Unlikewithtypeclasses,thescopeofanimplicitparametercanbecon-trolled,andcompetingimplicitparameterscancoexistindierentpartsofoneprogram.MotivationAsanexample,let'sstartwithanabstractclassofsemi-groupsthatsupportanunspeciedadd opera-tion.abstractclassSemiGroup[a]{defadd(x:a,y:a):a} Here'sasubclassMonoid ofSemiGroup whichaddsaunit element.abstractclassMonoid[a]extendsSemiGroup[a]{defunit:a} Herearetwoimplementationsofmonoids:objectMonoids{objectstringMonoidextendsMonoid[String]{defadd(x:String,y:String):String=x.concat(y)defunit:String=""}objectintMonoidextendsMonoid[int]{defadd(x:Int,y:Int):Int=x+ydefunit:Int=0}} Asum method,whichworksoverarbitrarymonoids,canbewritteninplainScalaasfollows.defsum[a](xs:List[a])(m:Monoid[a]):a=if(xs.isEmpty)m.unitelsem.add(xs.head,sum(xs.tail)(m)) Oneinvokesthissum methodbycodesuchas:sum(List("a","bc","def"))(Monoids.stringMonoid)sum(List(1,2,3))(Monoids.intMonoid) 15 Allthisworks,butitisnotverynice.Theproblemisthatthemonoidimplementationshavetobepassedintoallcodethatusesthem.Wewouldsometimeswishthatthesystemcouldgureoutthecorrectargumentsautomatically,similartowhatisdonewhentypeargumentsareinferred.Thisiswhatimplicitparametersprovide.ImplicitParameters:TheBasicsThefollowingslightrewriteofsum introducesm asanimplicitparameter.defsum[a](xs:List[a])(implicitm:Monoid[a]):a=if(xs.isEmpty)m.unitelsem.add(xs.head,sum(xs.tail)) Ascanbeseenfromtheexample,itispossibletocombinenormalandimplicitparameters.However,theremayonlybeoneimplicitparameterlistforamethodorconstructor,anditmustcomelast.implicit canalsobeusedasamodierfordenitionsanddeclarations.Examples:implicitobjectstringMonoidextendsMonoid[String]{defadd(x:String,y:String):String=x.concat(y)defunit:String=""}implicitobjectintMonoidextendsMonoid[int]{defadd(x:Int,y:Int):Int=x+ydefunit:Int=0} Theprincipalideabehindimplicitparametersisthatargumentsforthemcanbeleftoutfromamethodcall.Iftheargumentscorrespondingtoanimplicitparametersectionaremissing,theyareinferredbytheScalacompiler.TheactualargumentsthatareeligibletobepassedtoanimplicitparameteroftypeTareallidentiersthatdenoteanimplicitdenitionandwhichsatisfyeitheroneofthefollowingtwocriteria: 1. Theidentiercanbeaccessedatthepointofthemethodcallwithoutaprex.Thisincludesidentiersdenedlocallyorinsomeenclosingscope,aswellasidentiersinheritedfrombaseclassesorimportedfromotherobjectsbyanimport clause. 2. OrtheidentierisdenedinanobjectCwhichcomeswithaclasswiththesamenamewhichisabaseclassofthetypeparameter'stypeT(suchobjectiscalledacompanionobjectoftypeT).Thesecriteriaensureacertaindegreeoflocalityofimplicitarguments.Forinstance,clientscantailorthesetofavail-ableargumentsbyselectivelyimportingobjectswhichdenetheargumentstheywanttoseepassedtoimplicitparame-ters.Ifthereareseveraleligibleargumentswhichmatchtheimplicitparameter'stype,theScalacompilerwillchoseamostspecicone,usingthestandardrulesofstaticover-loadingresolution.Forinstance,assumethecallsum(List(1,2,3)) inacontextwherestringMonoid andintMonoid arevisible.Weknowthattheformaltypeparametera ofsum needstobeinstantiatedtoInt .TheonlyeligiblevaluewhichmatchestheimplicitformalparametertypeMonoid[Int] is intMonoid sothisobjectwillbepassedasimplicitparame-ter.Thisdiscussionalsoshowsthatimplicitparametersareinferredafteranytypeargumentsareinferred.Implicitmethodscanthemselveshaveimplicitparam-eters.Anexampleisthefollowingmethodfrommodulescala.List ,whichinjectslistsintothescala.Ordered class,providedtheelementtypeofthelistisalsoconvertibletothistype.implicitdeflist2ordered[a](x:List[a])(implicitelem2ordered:a=�Ordered[a]):Ordered[List[a]]=... Assumeinadditionamethodimplicitdefint2ordered(x:int):Ordered[int] thatinjectsintegersintotheOrdered class.Wecannowdeneasort methodoverorderedlists:defsort(xs:List[a])(implicita2ord:a=�Ordered[a])=... Wecanapplysort toalistoflistsofintegersyss:List[List[int]] asfollows:sort(yss) TheScalacompilerwillcompletethecallabovebypassingtwonestedimplicitarguments:sort(yss)((xs:List[int])=�list2ordered[int](xs)(int2ordered)). Thepossibilityofpassingimplicitargumentstoimplicitar-gumentsraisesthepossibilityofaninniterecursion.Forin-stance,onemighttrytodenethefollowingmethod,whichinjectseverytypeintotheOrdered class:defmagic[a](x:a)(implicita2ordered:a=�Ordered[a]):Ordered[a]=a2ordered(x) Thisfunctionisofcoursetoogoodtobetrue.Indeed,ifonetriedtoapplysort toanargumentarg ofatypethatdidnothaveanotherinjectionintotheOrdered class,onewouldobtainaninniteexpansion:sort(arg)(x=�magic(x)(x=�magic(x)(x=�...))) Topreventsuchinniteexpansions,werequirethateveryimplicitmethoddenitioniscontractive.Hereamethoddef-initioniscontractiveifthetypeofeveryimplicitparametertypeisproperlycontained[ 35 ]inthetypethatisobtainedbyremovingallimplicitparametersfromthemethodtypeandconvertingtheresttoafunctiontype.Forinstance,thetypeoflist2ordered is(List[a])(implicita=�Ordered[a]):Ordered[List[a]]. Thistypeiscontractive,becausethetypeoftheimplicitparameter,a�=Ordered[a] ,isproperlycontainedinthefunctiontypeofthemethodwithoutimplicitparameters,List[a]�=Ordered[List[a]] .Thetypeofmagic is(a)(implicita=�Ordered[a]):Ordered[a]. Thistypeisnotcontractive,becausethetypeoftheimplicitparameter,a�=Ordered[a] ,isthesameasthefunction 16 typeofthemethodwithoutimplicitparameters.ViewsViewsareimplicitconversionsbetweentypes.Theyaretypicallydenedtoaddsomenewfunctionalitytoapre-existingtype.Forinstance,assumethefollowingtraitifsimplegenericsets:traitSet[T]{definclude(x:T):Set[T]defcontains(x:T):boolean} AviewfromclassGenList toclassSet isintroducedbythefollowingmethoddenition.implicitdeflistToSet[T](xs:GenList[T]):Set[T]=newSet[T]{definclude(x:T):Set[T]=xsprependxdefcontains(x:T):boolean=!isEmpty&&(xs.head==x||(xs.tailcontainsx))} Hence,ifxs isaGenList[T] ,thenlistToSet(xs) wouldreturnaSet[T] .Theonlydierencewithrespecttoanormalmethoddenitionistheimplicit modier.Thismodiermakesviewscandidateargumentsforimplicitparameters,andalsocausesthemtobeinsertedautomaticallyasimplicitconver-sions.SayeisanexpressionoftypeT.Aviewisimplicitlyappliedtoeinoneoftwopossiblesituations:whentheexpectedtypeofeisnot(asupertypeof)T,orwhenamemberselectedfromeisnotamemberofT.Forinstance,assumeavaluexs oftypeGenList[T] whichisusedinthefollowingtwolines.vals:Set[T]=xs;xscontainsx Thecompilerwouldinsertapplicationsoftheviewdenedaboveintotheselinesasfollows:vals:Set[T]=listToSet(xs);listToSet(xs)containsx Whichviewsareavailableforinsertion?Scalausesthesamerulesasforargumentstoimplicitparameters.Aviewisavailableifitcanbeaccessedwithoutaprexoritisdenedinacompanionobjectofeitherthesourceorthetargettypeoftheconversion.Anavailableviewisapplicableifcanbeappliedtotheexpressionanditmapstothedesiredtype,ortoanytypecontainingthedesiredmember,inthecaseofaselection.Amongallapplicablecandidates,Scalapicksthemostspecicview.Here,specicityisinterpretedinthesamewayasforoverloadingresolutioninJavaandScala.Itisanerrorifnoviewisapplicable,oramongtheapplicableviewsnomostspeciconeexists.ViewsareusedfrequentlyintheScalalibrarytoupgradeJava'stypestosupportnewScalatraits.AnexampleisScala'straitOrdered whichdenesasetofcomparisonop-erations.ViewsfromallbasictypesaswellasclassString tothistypearedenedinamodulescala.Predef .SincethemembersofthismoduleareimportedimplicitlyintoeveryScalaprogram,theviewsarealwaysavailable.Fromauser's perspective,itisalmostasiftheJavaclassesareaugmentedbythenewtraits.ViewBoundsAspresentedsofar,viewmethodshavetobevisiblestati-callyatthepointoftheirinsertion.Viewsbecomeevenmoreusefulifonecanabstractovertheconcreteviewmethodtobeinserted.Thiscanbeexpressedbymakingtheviewanimplicitparameter.Anexampleisthefollowinggenericmaximum method,whichreturnsthemaximumelementofanon-emptylist.defmaximum[T](xs:List[T])(implicitt2ordered:T=�Ordered[T]):unit={varmx=xs.headfor(valx­xs.tail)if(mxx)mx=xmx} Thismaximum functioncanbeappliedtoanyargumentoftypeList[T] ,whereT isviewableasOrdered[T] .Inpartic-ular,wecanapplymaximum tolistsofbasictypesforwhichstandardOrdered viewsexist.Notethatmaximum usesacomparisonoperation(mxx) onvaluesmx andx oftypeT .ThetypeparameterT doesnothaveacomparisonoperation ,butthereistheim-plicitparametert2ordered whichmapsT intoatypewhichdoes.Therefore,thecomparisonoperationisrewrittento(t2ordered(mx)x) .Thesituationofassociatingagenericparameterwithim-plicitviewsissocommonthatScalahasspecialsyntaxforit.Aviewboundedtypeparametersuchas[TU] ex-pressesthatT mustcomeequippedwithaviewthatmapsitsvaluesintovaluesoftypeU .Usingviewbounds,themaximum functionabovecanbemoreconciselywrittenasfollows:defmaximum[T%Ordered[T]](xs:List[T]):unit=... Thiscodeisexpandedintopreciselythepreviouscodeformaximum .10RelatedWorkScala'sdesignisinuencedbymanydierentlanguagesandresearchpapers.Thefollowingenumerationofrelatedworkliststhemaindesigninuences.Ofcourse,ScalaadoptsalargepartoftheconceptsandsyntacticconventionsofJava[ 23 ]andC#[ 15 ].Scala'swaytoexpresspropertiesislooselymodelledafterSather[ 44 ].FromSmalltalk[ 22 ]comestheconceptofauniformob-jectmodel.FromBeta[ 30 ]comestheideathateverythingshouldbenestable,includingclasses.Scala'sdesignofmix-inscomesfromobject-orientedlinearmixins[ 6 ],butdenesmixincompositioninasymmetricway,similartowhatisfoundinmixinmodules[ 14 , 25 , 49 ]ortraits[ 42 ].Scala'sabstracttypeshavecloseresemblancestoabstracttypesofsignaturesinthemodulesystemsofML[ 24 ]andOCaml[ 29 ],generalizingthemtoacontextofrst-classcomponents.For-comprehensionsarebasedonHaskell'smonadcompre-hensions[ 46 ],eventhoughtheirsyntaxmorecloselyresem-blesXQuery[ 3 ].ViewshavebeeninuencedbyHaskell'stypeclasses[ 47 ].Theycanbeseenasanobject-orientedversionofparametrictypeclasses[ 38 ],buttheyaremoregeneralinthatinstancedeclarationscanbelocalandare 17 [6] G.BrachaandW.Cook.Mixin-BasedInheritance.InN.Meyrowitz,editor,ProceedingsofECOOP'90,pages303311,Ottawa,Canada,October1990.ACMPress. [7] T.Bray,J.Paoli,C.M.Sperberg-McQueen,E.Maler,andF.Yergeau,eds.ExtensibleMarkupLanguage(XML)1.0.W3Crecommendation,WorldWideWebConsortium,February2004.Availableonlinehttp://www.w3.org/TR/REC­xml­20040204/. [8] K.B.Bruce,M.Odersky,andP.Wadler.AStaticallySafeAlternativetoVirtualTypes.LectureNotesinComputerScience,1445,1998.Proc.ESOP1998. [9] K.B.Bruce,A.Schuett,andR.vanGent.PolyTOIL:AType-SafePolymorphicObject-OrientedLanguage.InPro-ceedingsofECOOP'95,LNCS952,pages2751,Aarhus,Denmark,August1995.Springer-Verlag. [10] P.Canning,W.Cook,W.Hill,W.Oltho,andJ.Mitchell.F-BoundedQuanticationforObject-OrientedProgram-ming.InProc.of4thInt.Conf.onFunctionalProgrammingandComputerArchitecture,FPCA'89,London,pages273280,NewYork,Sep1989.ACMPres. [11] L.Cardelli,S.Martini,J.C.Mitchell,andA.Scedrov.AnExtensionofSystemFwithSubtyping.InformationandComputation,109(12):456,1994. [12] K.Chen,P.Hudak,andM.Odersky.ParametricTypeClasses.InProc.ACMConf.onLispandFunctionalPro-gramming,pages170181,June1992. [13] C.Clifton,G.T.Leavens,C.Chambers,andT.Millstein.MultiJava:DesignRationale,CompilerImplementation,andUserExperience.TechnicalReport04-01,IowaStateUniversity,Dept.ofComputerScience,Jan2004. [14] D.Duggan.Mixinmodules.InProceedingsoftheACMSIG-PLANInternationalConferenceonFunctionalProgram-ming(ICFP'96),volume31(6),pages262273,1996. [15] ECMA.C#LanguageSpecication.TechnicalReportStan-dardECMA-334,2ndEdition,EuropeanComputerManu-facturersAssociation,December2002. [16] E.Ernst.Familypolymorphism.InProceedingsoftheEu-ropeanConferenceonObject-OrientedProgramming,pages303326,Budapest,Hungary,2001. [17] E.Ernst.Higher-OrderHierarchies.InL.Cardelli,editor,ProceedingsECOOP2003,LNCS2743,pages303329,Hei-delberg,Germany,July2003.Springer-Verlag. [18] M.O.et.al.AnintroductiontoScala.Technicalreport,EPFLLausanne,Switzerland,Mar.2006.Availableonlinehttp://scala.epfl.ch. [19] D.C.Fallside,editor.XMLSchema.W3Crecommendation,WorldWideWebConsortium,May2001.Availableonlinehttp://www.w3.org/TR/xmlschema­0/. [20] K.FisherandJ.H.Reppy.TheDesignofaClassMecha-nismforMoby.InSIGPLANConferenceonProgrammingLanguageDesignandImplementation,pages3749,1999. [21] E.Gamma,R.Helm,R.Johnson,andJ.Vlissides.DesignPatterns:ElementsofReusableObject-OrientedSoftware.AddisonWesley,Massachusetts,1994. [22] A.GoldbergandD.Robson.Smalltalk-80:TheLanguageandItsImplementation.Addison-Wesley,1983. [23] J.Gosling,B.Joy,G.Steele,andG.Bracha.TheJavaLan-guageSpecication.JavaSeries,SunMicrosystems,secondedition,2000. [24] R.HarperandM.Lillibridge.AType-TheoreticApproachtoHigher-OrderModuleswithSharing.InProc.21stACMSymposiumonPrinciplesofProgrammingLanguages,Jan-uary1994. [25] T.HirschowitzandX.Leroy.MixinModulesinaCall-by-ValueSetting.InEuropeanSymposiumonProgramming,pages620,2002. [26] A.IgarashiandM.Viroli.VariantParametricTypes:AFlexibleSubtypingSchemeforGenerics.InProceedingsoftheSixteenthEuropeanConferenceonObject-OrientedPro-gramming(ECOOP2002),pages441469,June2002. [27] M.P.Jones.Usingparameterizedsignaturestoexpressmod-ularstructure.InProceedingsofthe23rdACMSympo-siumonPrinciplesofProgrammingLanguages,pages6878.ACMPress,1996. [28] R.KellerandU.Hölzle.BinaryComponentAdaptation.InProceedingsECOOP,SpringerLNCS1445,pages307329,1998. [29] X.Leroy.ManifestTypes,ModulesandSeparateCompila-tion.InProc.21stACMSymposiumonPrinciplesofPro-grammingLanguages,pages109122,January1994. [30] O.L.MadsenandB.Moeller-Pedersen.VirtualClasses-APowerfulMechanismforObject-OrientedProgramming.InProc.OOPSLA'89,pages397406,October1989. [31] S.McDirmid,M.Flatt,andW.Hsieh.Jiazzi:New-ageComponentsforOld-FashionedJava.InProc.ofOOPSLA,October2001. [32] N.Nystrom,S.Chong,andA.Myers.ScalableExtensibilityviaNestedInheritance.InProc.OOPSLA,Oct2004. [33] Oasis.RELAXNG.Seehttp://www.oasis­open.org/. [34] M.Odersky.Scalabyexample.Technicalreport,EPFLLausanne,Switzerland,Mar.2006.Availableonlinehttp://scala.epfl.ch. [35] M.Odersky.TheScalaLanguageSpecication.Technicalreport,EPFLLausanne,Switzerland,Mar.2006.Availableonlinehttp://scala.epfl.ch. [36] M.Odersky,V.Cremet,C.Röckl,andM.Zenger.Anominaltheoryofobjectswithdependenttypes.InProc.ECOOP'03,SpringerLNCS2743,jul2003. [37] M.OderskyandP.Wadler.PizzaintoJava:Translatingtheoryintopractice.InProc.24thACMSymposiumonPrinciplesofProgrammingLanguages,pages146159,Jan-uary1997. [38] M.Odersky,P.Wadler,andM.Wehr.ASecondLookatOverloading.InProc.ACMConf.onFunctionalProgram-mingandComputerArchitecture,pages135146,June1995. [39] M.Odersky,C.Zenger,andM.Zenger.ColoredLocalTypeInference.InProceedingsofthe28thACMSymposiumonPrinciplesofProgrammingLanguages,pages4153,Lon-don,UK,January2001. [40] K.Ostermann.DynamicallyComposableCollaborationswithDelegationLayers.InProceedingsofthe16thEuro-peanConferenceonObject-OrientedProgramming,Malaga,Spain,2002. [41] B.C.PierceandD.N.Turner.LocalTypeInference.InProc.25thACMSymposiumonPrinciplesofProgrammingLanguages,pages252265,NewYork,NY,1998. 19 [42] N.Schärli,S.Ducasse,O.Nierstrasz,andA.Black.Traits:ComposableUnitsofBehavior.InProceedingsofthe17thEuropeanConferenceonObject-OrientedProgram-ming,Darmstadt,Germany,June2003. [43] J.SiekandA.Lumsdaine.EssentialLanguageSupportforgenericprogramming.InPLDI'05:ProceedingsoftheACMSIGPLAN2005conferenceonProgramminglanguagede-signandimplementation,pages7384,Jun2005. [44] D.StoutamireandS.M.Omohundro.TheSather1.0Spec-ication.TechnicalReportTR-95-057,InternationalCom-puterScienceInstitute,Berkeley,1995. [45] M.Torgersen,C.P.Hansen,E.Ernst,P.vodderAhé,G.Bracha,andN.Gafter.AddingWildcardstotheJavaProgrammingLanguage.InProceedingsSAC2004,Nicosia,Cyprus,March2004. [46] P.Wadler.TheEssenceofFunctionalProgramming.InProc.19thACMSymposiumonPrinciplesofProgrammingLanguages,pages114,January1992. [47] P.WadlerandS.Blott.Howtomakead-hocPolymorphismlessad-hoc.InProc.16thACMSymposiumonPrinciplesofProgrammingLanguages,pages6076,January1989. [48] M.Zenger.Type-SafePrototype-BasedComponentEvolu-tion.InProceedingsoftheEuropeanConferenceonObject-OrientedProgramming,Málaga,Spain,June2002. [49] M.Zenger.ProgrammingLanguageAbstractionsforEx-tensibleSoftwareComponents.PhDthesis,DepartmentofComputerScience,EPFL,Lausanne,March2004. 20

Related Contents


Next Show more