User-defined DatatypesUser-defined Datatypesldots User-defined Datatypesldots User-defined Datatypesldots User-defined Datatypesldots User-defined Datatypesldots Acknowledgements520—Spring 2005—18CSc 520Principles of ProgrammingLanguages18: Haskell — Data TypesChristian [email protected] of Computer ScienceUniversity of ArizonaCopyrightc 2005 Christian Collberg[1]520—Spring 2005—18User-defined DatatypesHaskell allows the definition of new datatypes :data Datatype a1...an= constr1| ...| constrmwhere1.Datatype is the name of a new type constructor ofarity n ≥ 0,2.a1, ..., anare distinct type variables representing thearguments ofDatatypeName and3.constr1, ..., constrm(m ≥ 1) describe the way in whichelements of the new datatype are constructed.[2]520—Spring 2005—18User-defined Datatypes...Each constr can take one of two forms:1.Name type1...typerwhere Name is a previouslyunused constructor function name (i.e. an identifierbeginning with a capital letter). This declarationintroducesName as a new constructor function oftype:type1→ . . . → typer→ Datatype a1. . . an2. type1⊕ type2where ⊕ is a previously unusedconstructor function operator (i.e. an operatorsymbol beginning with a colon). This declarationintroduces(⊕) as a new constructor function of type:type1→ type2→ Datatype a1. . . an[3]520—Spring 2005—18User-defined Datatypes...The following definition introduces a new type Day withelements Sun, Mon, Tue,...:data Day = Sun|Mon|Tue|Wed|Thu|Fri|SatSimple functions manipulating elements of type Daycan be defined using pattern matching:what_shall_I_do Sun = "relax"what_shall_I_do Sat = "go shopping"what_shall_I_do _ = "go to work"[4]520—Spring 2005—18User-defined Datatypes...Another example uses a pair of constructors to providea representation for temperatures which may be givenusing either of the centigrade or fahrenheit scales:data Temp = Centigrade Float |Fahrenheit Floatfreezing :: Temp -> Boolfreezing (Centigrade temp) = temp <= 0.0freezing (Fahrenheit temp) = temp <= 32.0[5]520—Spring 2005—18User-defined Datatypes...Datatype definitions may also be recursive.The following example defines a type representingbinary trees with values of a particular type at theirleaves:data Tree a = Lf a | Tree a :ˆ: Tree aFor example,(Lf 12 :ˆ: (Lf 23 :ˆ: Lf 13)) :ˆ: Lf 10has type Tree Int and represents the binary tree:10132312[6]520—Spring 2005—18User-defined Datatypes...Calculate the list of elements at the leaves of a treetraversing the branches of the tree from left to right.leaves :: Tree a -> [a]leaves (Lf l) = [l]leaves (l:ˆ:r) = leaves l ++ leaves rUsing the binary tree above as an example:? leaves ((Lf 12:ˆ:(Lf 23:ˆ:Lf 13)):ˆ:Lf 10)[12, 23, 13, 10](24 reductions, 73 cells)[7]520—Spring 2005—18AcknowledgementsThese slides were derived directly from the Gofermanual.Functional programming environment, Version2.20c Copyright Mark P. Jones 1991.A copy of the Gofer manual can be found
View Full Document