Parametric Type Classes
Total Page:16
File Type:pdf, Size:1020Kb
Parametric Typ e Classes Extended Abstract Kung Chen Paul Hudak Martin Odersky Yale University Department of Computer Science BoxYale Station New Haven CT ACM Conf on LISP and Functional Programming June tradeo in cho osing one of these representations lists sup Abstract p ort the ecient addition of new elements whereas vectors supp ort ecient random includin g parallel access Cur We prop ose a generalizati on to Haskells typ e classes where rently the choice b etween representations is made at the pro a class can havetyp e parameters b esides the placeholder gramming language level Most functional languages pro variable We show that this generalizatio n is essential to vide lists as the core data structure often with sp ecial represent container classes with overloaded data constructor syntax to supp ort them relegating arrays to somewhat of and selector op erations We also show that the resulting a secondclass status Other languages such as Sisal and typ e system has principal typ es and present unication and Nial reverse this choice and provide sp ecial syntax for ar typ e reconstruction algorithms rays instead of lists this often reects their bias toward parallel andor scientic computation Intro duction Of course it is p ossible to design a language which places equal emphasis on b oth container structures However anaive approach faces the problem that every function on Haskells type classes provide a structured waytointro duce sequences has to b e implemented twice once for lists and overloaded functions and are p erhaps the most innovative once for arrays The obvious cure for this namespace p ol and somewhat controversial asp ect of the language design lution and duplicated co de is overloading In our context HJW Typ e classes p ermit the denition of overloaded that means sp ecifying the notion of a sequence as a type op erators in a rigorous and fairly general manner that inte class with at least lists and vectors as instance typ es Us grates well with the underlying HindleyMiln er typ e system ing Haskelllike notation this would amounttothefollowing As a result op erators that are monomorphic in other typ ed declarations languages can b e given a more general typ e Examples in clude the numeric op erators reading and writing of arbi trary datatyp es and comparison op erators such as equality class Sequence a s ordering etc whereconsass nth s Int a ven to b e quite useful Most Haskells typ e classes have pro len s Int notably missing however are overloaded functions for data selection and construction Suchoverloaded functions are instance Sequence a List a quite useful but the currentHaskell typ e system is not ex where cons pressive enough to supp ort them of course no other lan nth guage that weknow if is capable of supp orting them in a len typ esafe way either instance Sequence a Vector a where cons vecCons A Motivating Example nth vecNth len vecLen As a simple example consider the concept of a sequence a linearly ordered collection of elements all of the same This denes the overloaded constructor consoverloaded in typ e There are at least two reasonable implementations of dexing selector nth and a length function len Note the sequences linked lists and vectors There is an eciency resemblance to a container class in ob jectoriented pro This researchwas supp orted byDARPA through ONR contracts gramming NC and NJ The only problem with this co de is that it is not valid Haskell since Haskells typ e classes are p ermitted to con strain only one typ e thus ruling out a declaration suchas class Sequence a s In essence this restriction forces overloaded constructors and selectors to b e monomorphic which makes them fairly useless Through a simple enco ding scheme we showthatpara Even if this restriction did not exist there is another prob metric typ e classes are able to capture the notion of lem with the currenttyp e class mechanism whichcanbe typ e constructor variables thus p ermitting the def demonstrated through the typing of len inition of overloaded op erators suchas map Sequence a s s Int Parametric typ e classes are a conservative extension of Haskells typ e system If all classes are parameterless Even if multiargumenttyp e classes were allowed this qual the two systems are equivalent ied typ e would still not b e valid Haskell since it is am We prove that our system is decidable and provide an biguousTyp e variable a o ccurs in the context Sequence a eectivetyp e inference algorithm s but not in the typ epart prop er sInt Ambiguous typ es need to b e rejected since they haveseveral p ossibly As a concrete demonstration of the p ower and practi conicting implementation s cality of the system we formulate classes monad and A related but harder problem arises if we extend our exam monad that allow us to generalize the concept of list ple to include an overloaded map function Having sucha comprehensions to monads This is done using the function is attractive since together with join and filter standard translation rules for list comprehensions no it allows us to generalize ie overload the notion of a list sp ecial syntax is needed comprehension to include al l instances of Sequence not just lists In Section we elab orate on this extending it Related Work further to comprehensions for arbitrary instances of class monad such as bags and lists This seems quite natural since after all the domain of sets is where the compre Wadler and Blott WB intro duced typ e classes and pre hension notation came from However a problem b ecomes sented an extension of the HindleyMil ner typ e system that evident assoonaswe attempt to giveatyp e for map incorp orates them They prop osed a new form of typ e called a predicatedtypetospecifythetyp es of overloaded functions A quite similar notion was used under the name map Sequence a sa Sequence b sb of category in the Scratchpad I I system for symb olic compu a b sa sb tation JT Also related are Kaes work on parametric overloading Kae Fb ounded p olymorphism in ob ject This typ e is to o general since it would admit also imple oriented programming CCH and Rou The typ e mentations that take one sequence typ e eg a list and as quickly taken up in the design of Haskell Its class idea w ector Generality is costly in this return another eg a v theoretical foundation however to ok some time to develop context since it again leads to ambiguityFor instance the The initial approach of WB enco ded Haskells source function comp osition map f map g would b e ambigu level syntax in a typ e system that was more p owerful than ous the typ e of map g which do es not app ear in the typ e Haskell itself since it could accommo date classes over multi of the enclosing expression can b e either a list or a vector ple typ es This increased expressiveness can however lead What is needed is some way to sp ecify that map returns the to undecidabil i ty as has b een investigated byVolpano and same kind of sequence as its argument but with a p ossibly Smith VS Indeed the system published in WB is dierent elementtyp e A nice way to notate this typ e would apparently undecidable be The sourcelevel syntax of Haskell on the other hand has a sucientnumb er of static constraints to guarantee de map Sequence s a a b s a s b cidabili ty This was shown in NS where Nipkowand Snelting mo deled typ e classes in a threelevel system of val where s is a variable which ranges over typ e constructors ues typ es and partially ordered sorts In their system instead of typ es To accommo date this Sequence should classes corresp ond to sorts and typ es are sorted accord now b e viewed as a typ e constructor class instead of a typ e ing the class hierarchy Ordersorted unication MGS class However b ecause the instance relationship s are now is used to resolveoverloading in typ e reconstruction The expressed at the functorlevel there is the danger as has use of an ordersorted approach is mathematically elegant b een conjectured in Lil that second order unication yet we argue that the ordering relation b etween classes is a is needed to reconstruct typ es thus rendering the system syntactic mechanism and thus not necessary for developing undecidable atyp e system for typ e classes Furthermore it is not obvi ous how to extend their system to incorp orate our prop osed extensions Our Contributions Work was also done to extend the typ e class concept to pred icates over multiple typ es Volpano and Smith VS lo oked To solve these problems weintro duce the notion of para into mo dications of the original system in WB to ensure metric type classes as a signicant generalization of Haskells decidabili tyoftyp e reconstruction and to get a sharp er no typ e classes Our contributions can b e summarized as fol tion of welltyp ed expressions Jones Jon Jonb gave lows a general framework for qualiedtypes His use of predicate sets is at rst sight quite similar to our contextconstrained Parametric typ e classes can havetyp e arguments in instance theory The main dierence b etween the two ap addition to the constrained typ e variable and thus proaches lies in our use of normal forms Jones do es not ad are able to express classes suchasSequence dened dress this issue and our distinction b etween constrained and earlier dep endentvariables This distinction allows us to solvethe predicates and the restrictions on instance declarations The ambiguity problems previously encountered in denitions of typ e reconstruction algorithm enforces consistency in this container classes situation by unifying a and b The