Sie sind auf Seite 1von 12

21/4/2016

6PredefinedTypesandClasses

Chapter6
PredefinedTypesandClasses
TheHaskellPreludecontainspredefinedclasses,types,andfunctionsthatareimplicitlyimportedinto
everyHaskellprogram.Inthischapter,wedescribethetypesandclassesfoundinthePrelude.Most
functionsarenotdescribedindetailhereastheycaneasilybeunderstoodfromtheirdefinitionsas
giveninChapter9.Otherpredefinedtypessuchasarrays,complexnumbers,andrationalsaredefined
inPartII.

6.1StandardHaskellTypes
ThesetypesaredefinedbytheHaskellPrelude.NumerictypesaredescribedinSection6.4.When
appropriate,theHaskelldefinitionofthetypeisgiven.Somedefinitionsmaynotbecompletelyvalid
onsyntacticgroundsbuttheyfaithfullyconveythemeaningoftheunderlyingtype.
6.1.1Booleans
dataBool=False|Truederiving
(Read,Show,Eq,Ord,Enum,Bounded)

ThebooleantypeBoolisanenumeration.Thebasicbooleanfunctionsare&&(and),||(or),andnot.
ThenameotherwiseisdefinedasTruetomakeguardedexpressionsmorereadable.
6.1.2CharactersandStrings
ThecharactertypeCharisanenumerationwhosevaluesrepresentUnicodecharacters[2].Thelexical
syntaxforcharactersisdefinedinSection2.6characterliteralsarenullaryconstructorsinthe
datatypeChar.TypeCharisaninstanceoftheclassesRead,Show,Eq,Ord,Enum,andBounded.The
toEnumandfromEnumfunctions,standardfunctionsfromclassEnum,mapcharacterstoandfromtheInt
type.
NotethatASCIIcontrolcharacterseachhaveseveralrepresentationsincharacterliterals:numeric
escapes,ASCIImnemonicescapes,andthe\^Xnotation.Inaddition,therearethefollowing
equivalences:\aand\BEL,\band\BS,\fand\FF,\rand\CR,\tand\HT,\vand\VT,and\nand\LF.
Astringisalistofcharacters:
typeString=[Char]

StringsmaybeabbreviatedusingthelexicalsyntaxdescribedinSection2.6.Forexample,"Astring"
abbreviates['A','','s','t','r','i','n','g']
6.1.3Lists
data[a]=[]|a:[a]deriving(Eq,Ord)

Listsareanalgebraicdatatypeoftwoconstructors,althoughwithspecialsyntax,asdescribedin
Section3.7.Thefirstconstructoristhenulllist,written[](nil),andthesecondis:(cons).
ThemodulePreludeList(seeSection9.1)definesmanystandardlistfunctions.Arithmeticsequences
andlistcomprehensions,twoconvenientsyntaxesforspecialkindsoflists,aredescribedin
https://www.haskell.org/onlinereport/haskell2010/haskellch6.html#x131350006.4

1/12

21/4/2016

6PredefinedTypesandClasses

Sections3.10and3.11,respectively.ListsareaninstanceofclassesRead,Show,Eq,Ord,Monad,
Functor,andMonadPlus.
6.1.4Tuples
Tuplesarealgebraicdatatypeswithspecialsyntax,asdefinedinSection3.8.Eachtupletypehasa
singleconstructor.AlltuplesareinstancesofEq,Ord,Bounded,Read,andShow(provided,ofcourse,
thatalltheircomponenttypesare).
Thereisnoupperboundonthesizeofatuple,butsomeHaskellimplementationsmayrestrictthesize
oftuples,andlimittheinstancesassociatedwithlargertuples.However,everyHaskell
implementationmustsupporttuplesuptosize15,togetherwiththeinstancesforEq,Ord,Bounded,
Read,andShow.ThePreludeandlibrariesdefinetuplefunctionssuchaszipfortuplesuptoasizeof7.
Theconstructorforatupleiswrittenbyomittingtheexpressionssurroundingthecommasthus(x,y)
and(,)xyproducethesamevalue.Thesameholdsfortupletypeconstructorsthus,(Int,Bool,Int)
and(,,)IntBoolIntdenotethesametype.
Thefollowingfunctionsaredefinedforpairs(2tuples):fst,snd,curry,anduncurry.Similar
functionsarenotpredefinedforlargertuples.
6.1.5TheUnitDatatype
data()=()deriving(Eq,Ord,Bounded,Enum,Read,Show)

Theunitdatatype()hasonenonmember,thenullaryconstructor().SeealsoSection3.9.
6.1.6FunctionTypes
Functionsareanabstracttype:noconstructorsdirectlycreatefunctionalvalues.Thefollowingsimple
functionsarefoundinthePrelude:id,const,(.),flip,($),anduntil.
6.1.7TheIOandIOErrorTypes
TheIOtypeservesasatagforoperations(actions)thatinteractwiththeoutsideworld.TheIOtypeis
abstract:noconstructorsarevisibletotheuser.IOisaninstanceoftheMonadandFunctorclasses.
Chapter7describesI/Ooperations.
IOErrorisanabstracttyperepresentingerrorsraisedbyI/Ooperations.ItisaninstanceofShowand
Eq.ValuesofthistypeareconstructedbythevariousI/Ofunctionsandarenotpresentedinany

furtherdetailinthisreport.ThePreludecontainsafewI/Ofunctions(definedinSection9.3),and
PartIIcontainsmanymore.
6.1.8OtherTypes
dataMaybea=Nothing|Justaderiving(Eq,Ord,Read,Show)
dataEitherab=Lefta|Rightbderiving(Eq,Ord,Read,Show)
dataOrdering=LT|EQ|GTderiving
(Eq,Ord,Bounded,Enum,Read,Show)

TheMaybetypeisaninstanceofclassesFunctor,Monad,andMonadPlus.TheOrderingtypeisusedby
compareintheclassOrd.ThefunctionsmaybeandeitherarefoundinthePrelude.

https://www.haskell.org/onlinereport/haskell2010/haskellch6.html#x131350006.4

2/12

21/4/2016

6PredefinedTypesandClasses

6.2StrictEvaluation
FunctionapplicationinHaskellisnonstrictthatis,afunctionargumentisevaluatedonlywhen
required.Sometimesitisdesirabletoforcetheevaluationofavalue,usingtheseqfunction:
seq::a>b>b

Thefunctionseqisdefinedbytheequations:
seqb=
seqab=b,ifa
seqisusuallyintroducedtoimproveperformancebyavoidingunneededlaziness.Strictdatatypes(see
Section4.2.1)aredefinedintermsofthe$!operator.However,theprovisionofseqhasimportant

semanticconsequences,becauseitisavailableateverytype.Asaconsequence,isnotthesameas
\x>,sinceseqcanbeusedtodistinguishthem.Forthesamereason,theexistenceofseqweakens
Haskellsparametricityproperties.
Theoperator$!isstrict(callbyvalue)application,andisdefinedintermsofseq.ThePreludealso
definesthe$operatortoperformnonstrictapplication.
infixr0$,$!
($),($!)::(a>b)>a>b
f$x=fx
f$!x=xseqfx

Thenonstrictapplicationoperator$mayappearredundant,sinceordinaryapplication(fx)means
thesameas(f$x).However,$haslow,rightassociativebindingprecedence,soitsometimes
allowsparenthesestobeomittedforexample:
f$g$hx=f(g(hx))

Itisalsousefulinhigherordersituations,suchasmap($0)xs,orzipWith($)fsxs.

6.3StandardHaskellClasses
Figure6.1showsthehierarchyofHaskellclassesdefinedinthePreludeandthePreludetypesthatare
instancesoftheseclasses.

https://www.haskell.org/onlinereport/haskell2010/haskellch6.html#x131350006.4

3/12

21/4/2016

6PredefinedTypesandClasses

Figure6.1:StandardHaskellClasses
Defaultclassmethoddeclarations(Section4.3)areprovidedformanyofthemethodsinstandard
classes.AcommentwitheachclassdeclarationinChapter9specifiesthesmallestcollectionof
methoddefinitionsthat,togetherwiththedefaultdeclarations,provideareasonabledefinitionforall
theclassmethods.Ifthereisnosuchcomment,thenallclassmethodsmustbegiventofullyspecify
aninstance.
6.3.1TheEqClass
classEqawhere
(==),(/=)::a>a>Bool

x/=y=not(x==y)
x==y=not(x/=y)

TheEqclassprovidesequality(==)andinequality(/=)methods.Allbasicdatatypesexceptfor
functionsandIOareinstancesofthisclass.InstancesofEqcanbederivedforanyuserdefined
datatypewhoseconstituentsarealsoinstancesofEq.
Thisdeclarationgivesdefaultmethoddeclarationsforboth/=and==,eachbeingdefinedintermsof
theother.IfaninstancedeclarationforEqdefinesneither==nor/=,thenbothwillloop.Ifoneis
defined,thedefaultmethodfortheotherwillmakeuseoftheonethatisdefined.Ifbotharedefined,
neitherdefaultmethodisused.
6.3.2TheOrdClass
class(Eqa)=>Ordawhere
compare::a>a>Ordering
(<),(<=),(>=),(>)::a>a>Bool
max,min::a>a>a

comparexy|x==y=EQ
https://www.haskell.org/onlinereport/haskell2010/haskellch6.html#x131350006.4

4/12

21/4/2016

6PredefinedTypesandClasses

|x<=y=LT
|otherwise=GT

x<=y=comparexy/=GT
x<y=comparexy==LT
x>=y=comparexy/=LT
x>y=comparexy==GT

Notethat(minxy,maxxy)=(x,y)or(y,x)

maxxy|x<=y=y
|otherwise=x
minxy|x<=y=x
|otherwise=y

TheOrdclassisusedfortotallyordereddatatypes.Allbasicdatatypesexceptforfunctions,IO,and
IOError,areinstancesofthisclass.InstancesofOrdcanbederivedforanyuserdefineddatatype
whoseconstituenttypesareinOrd.Thedeclaredorderoftheconstructorsinthedatadeclaration
determinestheorderinginderivedOrdinstances.TheOrderingdatatypeallowsasinglecomparisonto
determinethepreciseorderingoftwoobjects.
ThedefaultdeclarationsallowausertocreateanOrdinstanceeitherwithatypespecificcompare
functionorwithtypespecific==and<=functions.
6.3.3TheReadandShowClasses
typeReadSa=String>[(a,String)]
typeShowS=String>String

classReadawhere
readsPrec::Int>ReadSa
readList::ReadS[a]
...defaultdeclforreadListgiveninPrelude

classShowawhere
showsPrec::Int>a>ShowS
show::a>String
showList::[a]>ShowS

showsPrec_xs=showx++s
showx=showsPrec0x""
...defaultdeclforshowListgiveninPrelude

TheReadandShowclassesareusedtoconvertvaluestoorfromstrings.TheIntargumentto
showsPrecandreadsPrecgivestheoperatorprecedenceoftheenclosingcontext(seeSection11.4).
showsPrecandshowListreturnaStringtoStringfunction,toallowconstanttimeconcatenationofits
resultsusingfunctioncomposition.Aspecialisedvariant,show,isalsoprovided,whichuses
precedencecontextzero,andreturnsanordinaryString.ThemethodshowListisprovidedtoallow

theprogrammertogiveaspecialisedwayofshowinglistsofvalues.Thisisparticularlyusefulforthe
Chartype,wherevaluesoftypeStringshouldbeshownindoublequotes,ratherthanbetweensquare
brackets.
DerivedinstancesofReadandShowreplicatethestyleinwhichaconstructorisdeclared:infix
constructorsandfieldnamesareusedoninputandoutput.StringsproducedbyshowsPrecareusually
readablebyreadsPrec.
AllPreludetypes,exceptfunctiontypesandIOtypes,areinstancesofShowandRead.(Ifdesired,a
programmercaneasilymakefunctionsandIOtypesinto(vacuous)instancesofShow,byprovidingan
instancedeclaration.)
https://www.haskell.org/onlinereport/haskell2010/haskellch6.html#x131350006.4

5/12

21/4/2016

6PredefinedTypesandClasses

Forconvenience,thePreludeprovidesthefollowingauxiliaryfunctions:
reads::(Reada)=>ReadSa
reads=readsPrec0

shows::(Showa)=>a>ShowS
shows=showsPrec0

read::(Reada)=>String>a
reads=case[x|(x,t)<readss,("","")<lext]of
[x]>x
[]>error"PreludeText.read:noparse"
_>error"PreludeText.read:ambiguousparse"
showsandreadsuseadefaultprecedenceof0.Thereadfunctionreadsinputfromastring,which

mustbecompletelyconsumedbytheinputprocess.
Thefunctionlex::ReadSString,usedbyread,isalsopartofthePrelude.Itreadsasinglelexeme
fromtheinput,discardinginitialwhitespace,andreturningthecharactersthatconstitutethelexeme.
Iftheinputstringcontainsonlywhitespace,lexreturnsasinglesuccessfullexemeconsistingofthe
emptystring.(Thuslex""=[("","")].)Ifthereisnolegallexemeatthebeginningoftheinput
string,lexfails(i.e.returns[]).
6.3.4TheEnumClass
classEnumawhere
succ,pred::a>a
toEnum::Int>a
fromEnum::a>Int
enumFrom::a>[a][n..]
enumFromThen::a>a>[a][n,n'..]
enumFromTo::a>a>[a][n..m]
enumFromThenTo::a>a>a>[a][n,n'..m]

DefaultdeclarationsgiveninPrelude

ClassEnumdefinesoperationsonsequentiallyorderedtypes.Thefunctionssuccandpredreturnthe
successorandpredecessor,respectively,ofavalue.ThefunctionsfromEnumandtoEnummapvalues
fromatypeinEnumtoandfromInt.TheenumFrom...methodsareusedwhentranslatingarithmetic
sequences(Section3.10).
InstancesofEnummaybederivedforanyenumerationtype(typeswhoseconstructorshavenofields)
seeChapter11.
ForanytypethatisaninstanceofclassBoundedaswellasEnum,thefollowingshouldhold:
ThecallssuccmaxBoundandpredminBoundshouldresultinaruntimeerror.
fromEnumandtoEnumshouldgivearuntimeerroriftheresultvalueisnotrepresentableinthe
resulttype.Forexample,toEnum7::Boolisanerror.
enumFromandenumFromThenshouldbedefinedwithanimplicitbound,thus:
enumFromx=enumFromToxmaxBound
enumFromThenxy=enumFromThenToxybound
where
bound|fromEnumy>=fromEnumx=maxBound
|otherwise=minBound

ThefollowingPreludetypesareinstancesofEnum:
Enumerationtypes:(),Bool,andOrdering.Thesemanticsoftheseinstancesisgivenby
https://www.haskell.org/onlinereport/haskell2010/haskellch6.html#x131350006.4

6/12

21/4/2016

6PredefinedTypesandClasses

Chapter11.Forexample,[LT..]isthelist[LT,EQ,GT].
Char:theinstanceisgiveninChapter9,basedontheprimitivefunctionsthatconvertbetweena
CharandanInt.Forexample,enumFromTo'a''z'denotesthelistoflowercaselettersin
alphabeticalorder.
Numerictypes:Int,Integer,Float,Double.Thesemanticsoftheseinstancesisgivennext.
Forallfournumerictypes,succadds1,andpredsubtracts1.TheconversionsfromEnumandtoEnum
convertbetweenthetypeandInt.InthecaseofFloatandDouble,thedigitsafterthedecimalpoint
maybelost.ItisimplementationdependentwhatfromEnumreturnswhenappliedtoavaluethatistoo
largetofitinanInt.
ForthetypesIntandInteger,theenumerationfunctionshavethefollowingmeaning:
ThesequenceenumFrome1isthelist[e1,e1+1,e1+2,].
ThesequenceenumFromThene1e2isthelist[e1,e1+i,e1+2i,],wheretheincrement,i,ise2
e1.Theincrementmaybezeroornegative.Iftheincrementiszero,allthelistelementsare
thesame.
ThesequenceenumFromToe1e3isthelist[e1,e1+1,e1+2,e3].Thelistisemptyife1>e3.
ThesequenceenumFromThenToe1e2e3isthelist[e1,e1+i,e1+2i,e3],wheretheincrement,i,
ise2e1.Iftheincrementispositiveorzero,thelistterminateswhenthenextelementwould
begreaterthane3thelistisemptyife1>e3.Iftheincrementisnegative,thelistterminates
whenthenextelementwouldbelessthane3thelistisemptyife1<e3.
ForFloatandDouble,thesemanticsoftheenumFromfamilyisgivenbytherulesforIntabove,except
thatthelistterminateswhentheelementsbecomegreaterthane3+i2forpositiveincrementi,or
whentheybecomelessthane3+i2fornegativei.
ForallfourofthesePreludenumerictypes,alloftheenumFromfamilyoffunctionsarestrictinalltheir
arguments.
6.3.5TheFunctorClass
classFunctorfwhere
fmap::(a>b)>fa>fb

TheFunctorclassisusedfortypesthatcanbemappedover.Lists,IO,andMaybeareinthisclass.
InstancesofFunctorshouldsatisfythefollowinglaws:
fmapid
fmap(f.g)

= id
= fmapf.fmapg

AllinstancesofFunctordefinedinthePreludesatisfytheselaws.
6.3.6TheMonadClass
classMonadmwhere
(>>=)::ma>(a>mb)>mb
(>>)::ma>mb>mb
return::a>ma
fail::String>ma

m>>k=m>>=\_>k
fails=errors
https://www.haskell.org/onlinereport/haskell2010/haskellch6.html#x131350006.4

7/12

21/4/2016

6PredefinedTypesandClasses

TheMonadclassdefinesthebasicoperationsoveramonad.SeeChapter7formoreinformationabout
monads.
doexpressionsprovideaconvenientsyntaxforwritingmonadicexpressions(seeSection3.14).The
failmethodisinvokedonpatternmatchfailureinadoexpression.
InthePrelude,lists,Maybe,andIOareallinstancesofMonad.Thefailmethodforlistsreturnsthe
emptylist[],forMaybereturnsNothing,andforIOraisesauserexceptionintheIOmonad(see
Section7.3).
InstancesofMonadshouldsatisfythefollowinglaws:
returna>>=k
m>>=return
m>>=(\x>kx>>=h)

= ka
= m
= (m>>=k)>>=h

InstancesofbothMonadandFunctorshouldadditionallysatisfythelaw:
fmapfxs = xs>>=return.f
AllinstancesofMonaddefinedinthePreludesatisfytheselaws.
ThePreludeprovidesthefollowingauxiliaryfunctions:
sequence::Monadm=>[ma]>m[a]
sequence_::Monadm=>[ma]>m()
mapM::Monadm=>(a>mb)>[a]>m[b]
mapM_::Monadm=>(a>mb)>[a]>m()
(=<<)::Monadm=>(a>mb)>ma>mb

6.3.7TheBoundedClass
classBoundedawhere
minBound,maxBound::a

TheBoundedclassisusedtonametheupperandlowerlimitsofatype.Ordisnotasuperclassof
Boundedsincetypesthatarenottotallyorderedmayalsohaveupperandlowerbounds.ThetypesInt,
Char,Bool,(),Ordering,andalltuplesareinstancesofBounded.TheBoundedclassmaybederivedfor
anyenumerationtypeminBoundisthefirstconstructorlistedinthedatadeclarationandmaxBoundis
thelast.Boundedmayalsobederivedforsingleconstructordatatypeswhoseconstituenttypesarein
Bounded.

6.4Numbers
Haskellprovidesseveralkindsofnumbersthenumerictypesandtheoperationsuponthemhavebeen
heavilyinfluencedbyCommonLispandScheme.Numericfunctionnamesandoperatorsareusually
overloaded,usingseveraltypeclasseswithaninclusionrelationshowninFigure6.1.TheclassNumof
numerictypesisasubclassofEq,sinceallnumbersmaybecomparedforequalityitssubclassRealis
alsoasubclassofOrd,sincetheothercomparisonoperationsapplytoallbutcomplexnumbers
(definedintheComplexlibrary).TheclassIntegralcontainsintegersofbothlimitedandunlimited
rangetheclassFractionalcontainsallnonintegraltypesandtheclassFloatingcontainsall
floatingpointtypes,bothrealandcomplex.
ThePreludedefinesonlythemostbasicnumerictypes:fixedsizedintegers(Int),arbitraryprecision
integers(Integer),singleprecisionfloating(Float),anddoubleprecisionfloating(Double).Other
numerictypessuchasrationalsandcomplexnumbersaredefinedinlibraries.Inparticular,thetype
https://www.haskell.org/onlinereport/haskell2010/haskellch6.html#x131350006.4

8/12

21/4/2016

6PredefinedTypesandClasses

RationalisaratiooftwoIntegervalues,asdefinedintheRatiolibrary.

ThedefaultfloatingpointoperationsdefinedbytheHaskellPreludedonotconformtocurrent
languageindependentarithmetic(LIA)standards.Thesestandardsrequireconsiderablymore
complexityinthenumericstructureandhavethusbeenrelegatedtoalibrary.Some,butnotall,
aspectsoftheIEEEfloatingpointstandardhavebeenaccountedforinPreludeclassRealFloat.
ThestandardnumerictypesarelistedinTable6.1.ThefiniteprecisionintegertypeIntcoversatleast
therange[229,2291].AsIntisaninstanceoftheBoundedclass,maxBoundandminBoundcanbe
usedtodeterminetheexactIntrangedefinedbyanimplementation.Floatisimplementationdefined
itisdesirablethatthistypebeatleastequalinrangeandprecisiontotheIEEEsingleprecisiontype.
Similarly,DoubleshouldcoverIEEEdoubleprecision.Theresultsofexceptionalconditions(suchas
overfloworunderflow)onthefixedprecisionnumerictypesareundefinedanimplementationmay
chooseerror(,semantically),atruncatedvalue,oraspecialvaluesuchasinfinity,indefinite,etc.
Type

Class

Description
Integer
Integral
Arbitraryprecisionintegers
Int
Integral
Fixedprecisionintegers
(Integrala)=>Ratioa
RealFrac
Rationalnumbers
Float
RealFloat Realfloatingpoint,singleprecision
Double
RealFloat Realfloatingpoint,doubleprecision
(RealFloata)=>Complexa Floating
Complexfloatingpoint
Table6.1:StandardNumericTypes
ThestandardnumericclassesandothernumericfunctionsdefinedinthePreludeareshownin
Figures6.26.3.Figure6.1showstheclassdependenciesandbuiltintypesthatareinstancesofthe
numericclasses.
class(Eqa,Showa)=>Numawhere
(+),(),()::a>a>a
negate::a>a
abs,signum::a>a
fromInteger::Integer>a

class(Numa,Orda)=>Realawhere
toRational::a>Rational

class(Reala,Enuma)=>Integralawhere
quot,rem,div,mod::a>a>a
quotRem,divMod::a>a>(a,a)
toInteger::a>Integer

class(Numa)=>Fractionalawhere
(/)::a>a>a
recip::a>a
fromRational::Rational>a

class(Fractionala)=>Floatingawhere
pi::a
exp,log,sqrt::a>a
(),logBase::a>a>a
sin,cos,tan::a>a
asin,acos,atan::a>a
sinh,cosh,tanh::a>a
asinh,acosh,atanh::a>a
https://www.haskell.org/onlinereport/haskell2010/haskellch6.html#x131350006.4

9/12

21/4/2016

6PredefinedTypesandClasses

Figure6.2:StandardNumericClassesandRelatedOperations,Part1
class(Reala,Fractionala)=>RealFracawhere
properFraction::(Integralb)=>a>(b,a)
truncate,round::(Integralb)=>a>b
ceiling,floor::(Integralb)=>a>b

class(RealFraca,Floatinga)=>RealFloatawhere
floatRadix::a>Integer
floatDigits::a>Int
floatRange::a>(Int,Int)
decodeFloat::a>(Integer,Int)
encodeFloat::Integer>Int>a
exponent::a>Int
significand::a>a
scaleFloat::Int>a>a
isNaN,isInfinite,isDenormalized,isNegativeZero,isIEEE
::a>Bool
atan2::a>a>a

gcd,lcm::(Integrala)=>a>a>a
(^)::(Numa,Integralb)=>a>b>a
(^^)::(Fractionala,Integralb)=>a>b>a

fromIntegral::(Integrala,Numb)=>a>b
realToFrac::(Reala,Fractionalb)=>a>b

Figure6.3:StandardNumericClassesandRelatedOperations,Part2
6.4.1NumericLiterals
ThesyntaxofnumericliteralsisgiveninSection2.5.Anintegerliteralrepresentstheapplicationof
thefunctionfromIntegertotheappropriatevalueoftypeInteger.Similarly,afloatingliteralstands
foranapplicationoffromRationaltoavalueoftypeRational(thatis,RatioInteger).Giventhe
typings:
fromInteger::(Numa)=>Integer>a
fromRational::(Fractionala)=>Rational>a

integerandfloatingliteralshavethetypings(Numa)=>aand(Fractionala)=>a,respectively.
Numericliteralsaredefinedinthisindirectwaysothattheymaybeinterpretedasvaluesofany
appropriatenumerictype.SeeSection4.3.4foradiscussionofoverloadingambiguity.
6.4.2ArithmeticandNumberTheoreticOperations
Theinfixclassmethods(+),(),(),andtheunaryfunctionnegate(whichcanalsobewrittenasa
prefixminussignseesection3.4)applytoallnumbers.Theclassmethodsquot,rem,div,andmod
applyonlytointegralnumbers,whiletheclassmethod(/)appliesonlytofractionalones.Thequot,
rem,div,andmodclassmethodssatisfytheselawsifyisnonzero:
(xquoty)y+(xremy)==x
(xdivy)y+(xmody)==x
quotisintegerdivisiontruncatedtowardzero,whiletheresultofdivistruncatedtowardnegative
infinity.ThequotRemclassmethodtakesadividendandadivisorasargumentsandreturnsa(quotient,
https://www.haskell.org/onlinereport/haskell2010/haskellch6.html#x131350006.4

10/12

21/4/2016

6PredefinedTypesandClasses

remainder)pairdivModisdefinedsimilarly:
quotRemxy=(xquoty,xremy)
divModxy=(xdivy,xmody)

Alsoavailableonintegralnumbersaretheevenandoddpredicates:
evenx=xrem2==0
odd=not.even

Finally,therearethegreatestcommondivisorandleastcommonmultiplefunctions.gcdxyisthe
greatest(positive)integerthatdividesbothxandyforexamplegcd(3)6=3,gcd(3)(6)=3,
gcd04=4.gcd00raisesaruntimeerror.
lcmxyisthesmallestpositiveintegerthatbothxandydivide.

6.4.3ExponentiationandLogarithms
Theoneargumentexponentialfunctionexpandthelogarithmfunctionlogactonfloatingpoint
numbersandusebasee.logBaseaxreturnsthelogarithmofxinbasea.sqrtreturnstheprincipal
squarerootofafloatingpointnumber.Therearethreetwoargumentexponentiationoperations:(^)
raisesanynumbertoanonnegativeintegerpower,(^^)raisesafractionalnumbertoanyinteger
power,and()takestwofloatingpointarguments.Thevalueofx^0orx^^0is1foranyx,including
zero0yis1ifyis1,and0otherwise.
6.4.4MagnitudeandSign
Anumberhasamagnitudeandasign.Thefunctionsabsandsignumapplytoanynumberandsatisfy
thelaw:
absxsignumx==x

Forrealnumbers,thesefunctionsaredefinedby:
absx|x>=0=x
|x<0=x

signumx|x>0=1
|x==0=0
|x<0=1

6.4.5TrigonometricFunctions
ClassFloatingprovidesthecircularandhyperbolicsine,cosine,andtangentfunctionsandtheir
inverses.Defaultimplementationsoftan,tanh,logBase,,andsqrtareprovided,butimplementors
arefreetoprovidemoreaccurateimplementations.
ClassRealFloatprovidesaversionofarctangenttakingtworealfloatingpointarguments.Forreal
floatingxandy,atan2yxcomputestheangle(fromthepositivexaxis)ofthevectorfromtheorigin
tothepoint(x,y).atan2yxreturnsavalueintherange[pi,pi].ItfollowstheCommonLisp
semanticsfortheoriginwhensignedzeroesaresupported.atan2y1,withyinatypethatis
RealFloat,shouldreturnthesamevalueasatany.Adefaultdefinitionofatan2isprovided,but
implementorscanprovideamoreaccurateimplementation.
TheprecisedefinitionoftheabovefunctionsisasinCommonLisp,whichinturnfollowsPenfields
proposalforAPL[12].Seethesereferencesfordiscussionsofbranchcuts,discontinuities,and
https://www.haskell.org/onlinereport/haskell2010/haskellch6.html#x131350006.4

11/12

21/4/2016

6PredefinedTypesandClasses

implementation.
6.4.6CoercionsandComponentExtraction
Theceiling,floor,truncate,androundfunctionseachtakearealfractionalargumentandreturnan
integralresult.ceilingxreturnstheleastintegernotlessthanx,andfloorx,thegreatestintegernot
greaterthanx.truncatexyieldstheintegernearestxbetween0andx,inclusive.roundxreturnsthe
nearestintegertox,theevenintegerifxisequidistantbetweentwointegers.
ThefunctionproperFractiontakesarealfractionalnumberxandreturnsapair(n,f)suchthatx=n+
f,and:nisanintegralnumberwiththesamesignasxandfisafractionfwiththesametypeandsign
asx,andwithabsolutevaluelessthan1.Theceiling,floor,truncate,androundfunctionscanbe
definedintermsofproperFraction.
TwofunctionsconvertnumberstotypeRational:toRationalreturnstherationalequivalentofitsreal
argumentwithfullprecisionapproxRationaltakestworealfractionalargumentsxandandreturns
thesimplestrationalnumberwithinofx,wherearationalpqinreducedformissimplerthananother
pqif|p||p|andqq.Everyrealintervalcontainsauniquesimplestrationalinparticular,notethat
01isthesimplestrationalofall.
TheclassmethodsofclassRealFloatallowefficient,machineindependentaccesstothecomponents
ofafloatingpointnumber.ThefunctionsfloatRadix,floatDigits,andfloatRangegivethe
parametersofafloatingpointtype:theradixoftherepresentation,thenumberofdigitsofthisradix
inthesignificand,andthelowestandhighestvaluestheexponentmayassume,respectively.The
functiondecodeFloatappliedtoarealfloatingpointnumberreturnsthesignificandexpressedasan
Integerandanappropriatelyscaledexponent(anInt).IfdecodeFloatxyields(m,n),thenxisequal
invaluetombn,wherebisthefloatingpointradix,andfurthermore,eithermandnarebothzeroor
elsebd1|m|<bd,wheredisthevalueoffloatDigitsx.encodeFloatperformstheinverseofthis
transformation.Thefunctionssignificandandexponenttogetherprovidethesameinformationas
decodeFloat,butratherthananInteger,significandxyieldsavalueofthesametypeasx,scaledto
lieintheopeninterval(1,1).exponent0iszero.scaleFloatmultipliesafloatingpointnumberbyan
integerpoweroftheradix.
ThefunctionsisNaN,isInfinite,isDenormalized,isNegativeZero,andisIEEEallsupportnumbers
representedusingtheIEEEstandard.FornonIEEEfloatingpointnumbers,thesemayallreturnfalse.
Alsoavailablearethefollowingcoercionfunctions:
fromIntegral::(Integrala,Numb)=>a>b
realToFrac::(Reala,Fractionalb)=>a>b

https://www.haskell.org/onlinereport/haskell2010/haskellch6.html#x131350006.4

12/12

Das könnte Ihnen auch gefallen