Welcome to Scribd, the world's digital library. Read, publish, and share books and documents. See more ➡
Download
Standard view
Full view
of .
Add note
Save to My Library
Sync to mobile
Look up keyword or section
Like this
1Activity
×
P. 1
haskell-98-tutorial

haskell-98-tutorial

Ratings: (0)|Views: 1,910|Likes:
Published by Riccardo Ricci
Haskell 98 Tutorial
Haskell 98 Tutorial

More info:

Published by: Riccardo Ricci on Oct 02, 2011
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See More
See less

10/02/2011

pdf

text

original

 
AGentleIntroductiontoHaskell98
PaulHudakYaleUniversityDepartmentofComputerScienceJohnPetersonYaleUniversityDepartmentofComputerScienceJosephH.FaselUniversityofCaliforniaLosAlamosNationalLaboratoryOctober,1999Copyright
©
1999PaulHudak,JohnPetersonandJosephFaselPermissionisherebygranted,freeofcharge,toanypersonobtainingacopyof"AGentleIntroductiontoHaskell"(theText),todealintheTextwithoutrestriction,includingwithoutlimitationtherightstouse,copy,modify,merge,publish,distribute,sublicense,and/orsellcopiesoftheText,andtopermitpersonstowhomtheTextisfurnishedtodoso,subjecttothefollowingcondition:TheabovecopyrightnoticeandthispermissionnoticeshallbeincludedinallcopiesorsubstantialportionsoftheText.
1Introduction
Ourpurposeinwritingthistutorialisnottoteachprogramming,noreventoteachfunctionalprogramming.Rather,itisintendedtoserveasasupplementtotheHaskellReport[4],whichisotherwisearatherdensetechnicalexposition.OurgoalistoprovideagentleintroductiontoHaskellforsomeonewhohasexperiencewithatleastoneotherlanguage,preferablyafunctionallanguage(evenifonlyan"almost-functional"languagesuchasMLorScheme).
If
thereaderwishestolearnmoreaboutthefunctionalprogrammingstyle,wehighlyrecommendBird'stext
IntroductiontoFunctionalProgramming
[1]orDavie's
AnIntroductiontoFunctionalProgrammingSystemsUsingHaskell
[2].Forausefulsurveyoffunctionalprogramminglanguagesandtechniques,includingsomeofthelanguagedesignprinciplesusedinHaskell,see[3].TheHaskelllanguagehasevolvedsignificantlysinceitsbirthin1987.ThistutorialdealswithHaskell98.Olderversionsofthelanguagearenowobsolete;HaskellusersareencouragedtouseHaskell98.TherearealsomanyextensionstoHaskell98thathavebeenwidelyimplemented.ThesearenotyetaformalpartoftheHaskelllanguageandarenotcoveredinthistutorial.Ourgeneralstrategyforintroducinglanguagefeaturesisthis:motivatetheidea,definesometerms,givesomeexamples,andthenpointtotheReportfordetails.Wesuggest,however,thatthereadercompletelyignorethedetailsuntilthe
GentleIntroduction
hasbeencompletelyread.Onthe
1
 
2
2VALUES,TYPES,ANDOTHERGOODIES
otherhand,Haskell'sStandardPrelude(inAppendixAoftheReportandthestandardlibraries(foundintheLibraryReport[5])containlotsofusefulexamplesofHaskellcode;weencourageathoroughreadingoncethistutorialiscompleted.ThiswillnotonlygivethereaderafeelforwhatrealHaskellcodelookslike,butwillalsofamiliarizeherwithHaskell'sstandardsetofpredefinedfunctionsandtypes.Finally,theHaskellwebsite,
http://haskell.~rg,
hasawealthofinformationabouttheHaskelllanguageanditsimplementations.[Wehavealsotakenthecourseofnotlayingoutaplethoraoflexicalsyntaxrulesattheoutset.Rather,weintroducethemincrementallyasourexamplesdemand,andenclosetheminbrackets,aswiththisparagraph.ThisisinstarkcontrasttotheorganizationoftheReport,althoughtheReportremainstheauthoritativesourcefordetails(referencessuchas"§2.1"refertosectionsintheReport).JHaskellisa
typeful
programminglanguage.!typesarepervasive,andthenewcomerisbestoffbecomingwellawareofthefullpowerandcomplexityofHaskell'stypesystemfromtheoutset.Forthosewhoseonlyexperienceiswithrelatively"untypeful"languagessuchasPerl,Tel,orScheme,thismaybeadifficultadjustment;forthosefamiliarwithJava,C,Modula,orevenML,theadjustmentshouldbeeasierbutstillnotinsignificant,sinceHaskell'stypesystemisdifferentandsomewhatricherthanmost.Inanycase,"typefulprogramming"ispartoftheHaskellprogrammingexperience,andcannotbeavoided.
2Values,Types,andOtherGoodies
BecauseHaskellisapurelyfunctionallanguage,allcomputationsaredoneviatheevaluationof
expressions
(syntacticterms)toyield
values
(abstractentitiesthatweregardasanswers).Everyvaluehasanassociated
type.
(Intuitively,wecanthinkoftypesassetsofvalues.)Examplesofexpressionsincludeatomicvaluessuchastheinteger5,thecharacter'a',andthefunction
\x
->
x+1,
aswellasstructuredvaluessuchasthelist
[1,2,3]
andthepair
('b',4).
Justasexpressionsdenotevalues,typeexpressionsaresyntactictermsthatdenotetypevalues(orjust
types).
Examplesoftypeexpressionsincludetheatomictypes
Integer
(infinite-precisionintegers),
Char
(characters),
Integer->Integer
(functionsmapping
Integer
to
Integer),
aswellasthestructuredtypes
[Integer]
(homogeneouslistsofintegers)and
(Char,Integer)
(character,integerpairs).AllHaskellvaluesare"first-class"-theymaybepassedasargumentstofunctions,returnedasresults,placedindatastructures,etc.Haskelltypes,ontheotherhand,are
not
first-class.Typesinasensedescribevalues,andtheassociationofavaluewithitstypeiscalleda
typing.
Usingtheexamplesofvaluesandtypesabove,wewritetypingsasfollows:
5
IntegerCharInteger->Integer[Integer](Char,Integer)
'a'
inc
[1,2,3]
('b',4)
lCoined
by
LucaCardelli.
 
2.1PolymorphicTypes
3
The"::"canberead"hastype."FunctionsinHaskellarenormallydefinedbyaseriesof
equations.
Forexample,thefunction
inc
canbedefinedbythesingleequation:
incn
=
n+1
Anequationisanexampleofa
declaration.
Anotherkindofdeclarationisa
typesignaturedecla-ration
(§4.4.1),withwhichwecandeclareanexplicittypingfor
inc:inc::Integer-)Integer
WewillhavemuchmoretosayaboutfunctiondefinitionsinSection3.Forpedagogicalpurposes,whenwewishtoindicatethatanexpression
el
evaluates,or"re-duces,"toanotherexpressionorvalue
e2,
wewillwrite:Forexample,notethat:
inc(inc
3)
5
Haskell'sstatictypesystemdefinestheformalrelationshipbetweentypesandvalues(§4.1.3).ThestatictypesystemensuresthatHaskellprogramsare
typesafe;
thatis,thattheprogrammerhasnotmismatchedtypesinsomeway.Forexample,wecannotgenerallyaddtogethertwocharacters,sotheexpression
'a'+'b'
isill-typed.Themainadvantageofstaticallytypedlanguagesiswell-known:Alltypeerrorsaredetectedatcompile-time.Notallerrorsarecaughtbythetypesystem;anexpressionsuchas1/0istypablebutitsevaluationwillresultinanerroratexecutiontime.Still,thetypesystemfindsmanyprogramerrorsatcompiletime,aidstheuserinreasoningaboutprograms,andalsopermitsacompilertogeneratemoreefficientcode(forexample,norun-timetypetagsortestsarerequired).Thetypesystemalsoensuresthatuser-suppliedtypesignaturesarecorrect.Infact,Haskell'stypesystemispowerfulenoughtoallowustoavoidwritinganytypesignaturesatall;2wesaythatthetypesystem
infers
thecorrecttypesforus.Nevertheless,judiciousplacementoftypesignaturessuchasthatwegavefor
inc
isagoodidea,sincetypesignaturesareaveryeffectiveformofdocumentationandhelpbringprogrammingerrorstolight.[Thereaderwillnotethatwehavecapitalizedidentifiersthatdenotespecifictypes,suchas
Integer
and
Char,
butnotidentifiersthatdenotevalues,suchas
inc.
Thisisnotjustaconvention:itisenforcedbyHaskell'slexicalsyntax.Infact,thecaseoftheothercharactersmatters,too:foo,fOo,andfOOarealldistinctidentifiers.]
2.1PolymorphicTypes
Haskellalsoincorporates
polymorphic
types-typesthatareuniversallyquantifiedinsomewayoveralltypes.Polymorphictypeexpressionsessentiallydescribefamiliesoftypes.Forexample,
(Va)[a]
isthefamilyoftypesconsistingof,foreverytype
a,
thetypeoflistsof
a.
Listsof
2Withafewexceptionstobedescribedlater.

You're Reading a Free Preview

Download
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->