ebook img

Yet Another Haskell Tutorial PDF

193 Pages·2016·0.77 MB·English
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview Yet Another Haskell Tutorial

Yet Another Haskell Tutorial Revision 2 Hal Daume III http://www.isi.edu/~hdaume/htut/ Copyright (c) Hal Daume III, 2002−2006. The preprint version of this tutorial is intended to be available to the entire Haskell community, so we grant permission to copy and distribute it for any purpose, provided that it is reproduced in its entirety, including this notice. Modified versions may not be distributed without prior consent of the authfreeor, and must still maintain a copy of this notice. The author retains the right to change or modify this copyright at any time, as well as to make the book no longer free of charge. ii About This Report The goal of the Yet Another Haskell Tutorial is to providea completeintoductionto theHaskellprogramminglanguage.ItassumesnoknowledgeoftheHaskelllanguage or familiarity with functionalprogrammingin general. However, general familiarity withprogrammingconcepts(suchasalgorithms)willbehelpful. Thisisnotintended to be an introductionto programmingin general; rather, to programmingin Haskell. Suf(cid:2)cient familiarity with your operating system and a text editor is also necessary (thisreportonlydiscussesinstallationoncon(cid:2)gurationonWindowsand*Nixsystem; otheroperatingsystemsmaybesupported(cid:150)consultthedocumentationofyourchosen compilerformoreinformationoninstallingonotherplatforms). What is Haskell? Haskell is called a lazy, purefunctionalprogramminglanguage. It is called lazy be- causeexpressionswhicharenotneededtodeterminetheanswertoaproblemarenot evaluated. The opposize of lazy is strict, which is the evaluation strategry of most commonprogramminglanguages(C,C++,Java,evenML).Astrictlanguageisonein whicheveryexpressionisevaluated,whethertheresultofitscomputationisimportant ornot. (Thisisprobablynotentirelytrueasoptimizingcompilersforstrictlanguages oftendowhat’scalled(cid:147)deadcodeelmination(cid:148)(cid:150)thisremovesunusedexpressionsfrom the program.) It is called pure because it does not allow side effects (A side effect is somethingthataffectsthe(cid:147)state(cid:148)oftheworld. Forinstance, afunctionthatprints somethingtothescreenissaidtobeside-effecting,asisafunctionwhichaffectsthe valueofaglobalvariable.) (cid:150)ofcourse,aprogramminglanguagewithoutsideeffects wouldbehorriblyuseless;Haskellusesasystemofmonadstoisolateallimpurecom- putationsfromtherestoftheprogramandperformtheminthesafeway(seeChapter9 fora discussionof monadsproperor Chapter 5 forhow to do input/outputin a pure language). Haskell is called a functional language because the evaluation of a program is equivalentto evaluatinga functionin the pure mathematicalsense. This also differs from standard languages (like C and Java) which evaluate a sequence of statements, oneaftertheother(thisistermedanimperativelangauge). iii iv The History of Haskell ThehistoryofHaskellisbestdescribedusingthewordsoftheauthors. Thefollowing textisquotedfromthepublishedversionoftheHaskell98Report: InSeptemberof1987ameetingwasheldattheconferenceonFunctional ProgrammingLanguagesandComputerArchitecture(FPCA’87)inPort- land, Oregon, to discuss an unfortunate situation in the functional pro- grammingcommunity:therehadcomeintobeingmorethanadozennon- strict,purelyfunctionalprogramminglanguages,allsimilarinexpressive powerandsemanticunderpinnings. Therewasastrongconsensusatthis meetingthatmorewidespreaduseofthisclassoffunctionallanguageswas beinghamperedbythelackofacommonlanguage. Itwasdecidedthata committeeshouldbeformedto designsucha language,providingfaster communicationofnewideas,astablefoundationforrealapplicationsde- velopment, and a vehicle through which others would be encouraged to usefunctionallanguages.Thisdocumentdescribestheresultofthatcom- mittee’sefforts:apurelyfunctionalprogramminglanguagecalledHaskell, namedafterthelogicianHaskellB.Currywhoseworkprovidesthelogical basisformuchofours. Thecommittee’sprimarygoalwastodesignalanguagethatsatis(cid:2)edthese constraints: 1. Itshouldbesuitableforteaching,research,andapplications,includ- ingbuildinglargesystems. 2. It should be completely described via the publication of a formal syntaxandsemantics. 3. Itshouldbefreelyavailable. Anyoneshouldbepermittedtoimple- mentthelanguageanddistributeittowhomevertheyplease. 4. Itshouldbebasedonideasthatenjoyawideconsensus. 5. It should reduce unnecessary diversity in functional programming languages. The committee intended that Haskell would serve as a basis for future researchinlanguagedesign,andhopedthatextensionsorvariantsofthe languagewouldappear,incorporatingexperimentalfeatures. Haskellhasindeedevolvedcontinuouslysinceitsoriginalpublication.By themiddleof1997,therehadbeenfouriterationsofthelanguagedesign (thelatestatthatpointbeingHaskell1.4).Atthe1997HaskellWorkshop inAmsterdam,itwasdecidedthatastablevariantofHaskellwasneeded; this stable language is the subject of this Report, and is called (cid:147)Haskell 98(cid:148). Haskell 98 was conceived as a relatively minor tidy-up of Haskell 1.4, makingsomesimpli(cid:2)cations,andremovingsomepitfallsfortheunwary. v Itisintendedtobea(cid:147)stable(cid:148)languageinsensetheimplementorsarecom- mitted to supporting Haskell 98 exactly as speci(cid:2)ed, for the foreseeable future. The original Haskell Report covered only the language, together with a standardlibrarycalledthePrelude.BythetimeHaskell98wasstabilised, ithadbecomeclearthatmanyprogramsneedaccesstoalargersetofli- brary functions (notably concerning input/output and simple interaction withtheoperatingsystem). Iftheseprogramweretobeportable,asetof librarieswouldhaveto bestandardisedtoo. Aseparateeffortwas there- forebegunbyadistinct(butoverlapping)committeeto(cid:2)xtheHaskell98 Libraries. Why Use Haskell? Clearlyyou’reinterestedinHaskellsinceyou’rereadingthistutorial. Therearemany motivations for using Haskell. My personal reason for using Haskell is that I have foundthat I write more bug-freecode in less time using Haskell than any other lan- guage.Ialso(cid:2)nditveryreadableandextensible. Perhapsmostimportantly,however,IhaveconsistentlyfoundtheHaskellcommu- nity to be incredibly helpful. The language is constantly evolving (that’s not to say it’s instable; ratherthat thereare numerousextensionsthat havebeenaddedto some compilerswhichI(cid:2)ndveryuseful)andusersuggestionsareoftenheededwhennew extensionsaretobeimplemented. Why Not Use Haskell? Mytwobiggestcomplaints,andthecomplaintsofmostHaskellersIknow,are:(1)the generatedcodetendstobeslowerthanequivalentprogramswritteninalanguagelike C;and(2)ittendstobedif(cid:2)culttodebug. Thesecondproblemtendsnotbetoaverybigissue: mostofthecodeI’vewritten isnotbuggy,asmostofthecommonsourcesofbugsinotherlanguagessimplydon’t existinHaskell. The(cid:2)rstissue certainlyhascomeupafewtimes inmyexperience; however,CPU time is almost always cheaperthan programmertime and if I haveto wait a little longer for my results after having saved a few days programming and debugging. Of course, this isn’t the case of all applications. Some people may (cid:2)nd that the speedhittakenforusingHaskellisunbearable. However,Haskellhasastandardized foreign-functioninterfacewhichallowyoutolinkincodewritteninotherlanguages, for when you need to get the most speed out of your code. If you don’t (cid:2)nd this suf(cid:2)cient, I would suggest taking a look at the language O’Caml, which often out- performsevenC++,yetalsohasmanyofthebene(cid:2)tsofHaskell. vi Target Audience TherehavebeenmanybooksandtutorialswrittenaboutHaskell; fora(nearly)com- pletelist,visitthehttp://haskell.org/bookshelf(HaskellBookshelf)atthe Haskellhomepage.Abriefsurveyofthetutorialsavailableyields: A Gentle Introduction to Haskell is an introduction to Haskell, given that the (cid:15) readerisfamiliarwithfunctionalprogrammingenlarge. HaskellCompanionisashortreferenceofcommonconceptsandde(cid:2)nitions. (cid:15) OnlineHaskellCourseisashortcourse(inGerman)forbeginningwithHaskell. (cid:15) Two Dozen Short Lessons in Haskell is the draft of an excellent textbook that (cid:15) emphasizesuserinvolvement. Haskell Tutorial is based on a course given at the 3rd International Summer (cid:15) SchoolonAdvancedFunctionalProgramming. HaskellforMirandaProgrammersassumesknowledgeofthelanguageMiranda. (cid:15) PLEAC-HaskellisatutorialinthestyleofthePerlCookbook. (cid:15) Thoughall of these tutorials is excellent, they are on their own incomplete: The (cid:147)GentleIntroduction(cid:148)isfartooadvancedforbeginningHaskellersandtheotherstend toendtooearly,ornotcovereverything.Haskellisfullofpitfallsfornewprogrammers and experienced non-functional programmers alike, as can be witnessed by reading throughthearchivesoftheHaskellmailinglist. Itbecameclearthatthereisastrongneedforatutorialwhichisintroductoryinthe sensethatitdoesnotassumeknowledgeoffunctionalprogramming,butwhichisad- vancedinthesensethatitdoesassumesomebackgroundinprogramming.Moreover, noneoftheknowntutorialsintroduceinput/outputanditeractivitysoonenough(Paul Hudak’sbookisanexceptioninthatitdoesintroduceIObypage35,thoughthefocus andaimofthatbookandthistutorialareverydifferent).Thistutorialisnotforbegin- ningprogrammers;someexperienceandknowledgeofprogrammingandcomputersis assumed(thoughtheappendixdoescontainsomebackgroundinformation). TheHaskelllanguageunderwentastandardizationprocessandtheresultiscalled Haskell 98. The majority of this book will cover the Haskell 98 standard. Any de- viations from the standard will be noted (for instance, many compilers offer certain extensionstothestandardwhichareuseful;someofthesemaybediscussed). Thegoalsofthistutorialare: tobepracticalaboveallelse (cid:15) toprovideacomprehensive,freeintroductiontotheHaskelllanguage (cid:15) topointoutcommonpitfallsandtheirsolutions (cid:15) toprovideagoodsenseofhowHaskellcanbeusedintherealworld (cid:15) vii Additional Online Sources of Information AShortIntroductiontoHaskell : http://haskell.org/aboutHaskell.html HaskellWiki : http://haskell.org/hawiki/ Haskell-Tutorial : ftp://ftp.geoinfo.tuwien.ac.at/navratil/HaskellTutorial. pdf TouroftheHaskellPrelude : http://www.cs.uu.nl/(cid:152)afie/haskell/tourofprelude.html CoursesinHaskell : http://haskell.org/classes/ Acknowledgements It wouldbe inappropriatenot to givecredit also to the originaldesigners ofHaskell. Thoseare: Arvind,LennartAugustsson,DaveBarton, Brian Boutel, WarrenBurton, Jon Fairbairn, Joseph Fasel, Andy Gordon, Maria Guzman, Kevin Hammond, Ralf Hinze,PaulHudak,JohnHughes,ThomasJohnsson,MarkJones,DickKieburtz,John Launchbury,ErikMeijer, RishiyurNikhil,JohnPeterson,SimonPeytonJones,Mike Reeve,AlastairReid,ColinRunciman,PhilipWadler,DavidWise,JonathanYoung. Finally, I would like to speci(cid:2)cally thank Simon Peyton Jones, Simon Marlow, JohnHughes, Alastair Reid, KoenClassen, ManuelChakravarty,SigbjornFinneand SvenPanne,allofwhomhavemademylifelearningHaskellallthemoreenjoyableby alwaysbeingsupportive. Thereweredoubtlessotherswhohelpedandarenotlisted, butthesearethosewhocometomind. Alsothankstothemanypeoplewhohavereported(cid:147)bugs(cid:148)inthe(cid:2)rstedition. -HalDaume·III viii Contents 1 Introduction 3 2 GettingStarted 5 2.1 Hugs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 2.1.1 Wheretogetit . . . . . . . . . . . . . . . . . . . . . . . . . 6 2.1.2 Installationprocedures . . . . . . . . . . . . . . . . . . . . . 6 2.1.3 Howtorunit . . . . . . . . . . . . . . . . . . . . . . . . . . 6 2.1.4 Programoptions . . . . . . . . . . . . . . . . . . . . . . . . 7 2.1.5 Howtogethelp . . . . . . . . . . . . . . . . . . . . . . . . . 7 2.2 GlasgowHaskellCompiler . . . . . . . . . . . . . . . . . . . . . . . 7 2.2.1 Wheretogetit . . . . . . . . . . . . . . . . . . . . . . . . . 7 2.2.2 Installationprocedures . . . . . . . . . . . . . . . . . . . . . 8 2.2.3 Howtorunthecompiler . . . . . . . . . . . . . . . . . . . . 8 2.2.4 Howtoruntheinterpreter . . . . . . . . . . . . . . . . . . . 8 2.2.5 Programoptions . . . . . . . . . . . . . . . . . . . . . . . . 9 2.2.6 Howtogethelp . . . . . . . . . . . . . . . . . . . . . . . . . 9 2.3 NHC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 2.3.1 Wheretogetit . . . . . . . . . . . . . . . . . . . . . . . . . 9 2.3.2 Installationprocedures . . . . . . . . . . . . . . . . . . . . . 9 2.3.3 Howtorunit . . . . . . . . . . . . . . . . . . . . . . . . . . 9 2.3.4 Programoptions . . . . . . . . . . . . . . . . . . . . . . . . 9 2.3.5 Howtogethelp . . . . . . . . . . . . . . . . . . . . . . . . . 9 2.4 Editors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 3 LanguageBasics 11 3.1 Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 3.2 Pairs,TriplesandMore . . . . . . . . . . . . . . . . . . . . . . . . . 14 3.3 Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 3.3.1 Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 3.3.2 SimpleListFunctions . . . . . . . . . . . . . . . . . . . . . 18 3.4 SourceCodeFiles . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 3.5 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 3.5.1 LetBindings . . . . . . . . . . . . . . . . . . . . . . . . . . 27 3.5.2 In(cid:2)x . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 ix x CONTENTS 3.6 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 3.7 Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 3.8 Interactivity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 4 TypeBasics 37 4.1 SimpleTypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37 4.2 PolymorphicTypes . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 4.3 TypeClasses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 4.3.1 Motivation . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 4.3.2 EqualityTesting . . . . . . . . . . . . . . . . . . . . . . . . 41 4.3.3 TheNumClass . . . . . . . . . . . . . . . . . . . . . . . . . 41 4.3.4 TheShowClass. . . . . . . . . . . . . . . . . . . . . . . . . 41 4.4 FunctionTypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 4.4.1 LambdaCalculus . . . . . . . . . . . . . . . . . . . . . . . . 42 4.4.2 Higher-OrderTypes . . . . . . . . . . . . . . . . . . . . . . 42 4.4.3 ThatPeskyIOType. . . . . . . . . . . . . . . . . . . . . . . 44 4.4.4 ExplicitTypeDeclarations . . . . . . . . . . . . . . . . . . . 45 4.4.5 FunctionalArguments . . . . . . . . . . . . . . . . . . . . . 46 4.5 DataTypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 4.5.1 Pairs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 4.5.2 MultipleConstructors . . . . . . . . . . . . . . . . . . . . . 49 4.5.3 RecursiveDatatypes . . . . . . . . . . . . . . . . . . . . . . 51 4.5.4 BinaryTrees . . . . . . . . . . . . . . . . . . . . . . . . . . 51 4.5.5 EnumeratedSets . . . . . . . . . . . . . . . . . . . . . . . . 52 4.5.6 TheUnittype . . . . . . . . . . . . . . . . . . . . . . . . . . 53 4.6 ContinuationPassingStyle . . . . . . . . . . . . . . . . . . . . . . . 53 5 BasicInput/Output 57 5.1 TheRealWorldSolution . . . . . . . . . . . . . . . . . . . . . . . . 57 5.2 Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 5.3 TheIOLibrary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62 5.4 AFileReadingProgram . . . . . . . . . . . . . . . . . . . . . . . . 64 6 Modules 67 6.1 Exports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67 6.2 Imports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 6.3 HierarchicalImports . . . . . . . . . . . . . . . . . . . . . . . . . . 70 6.4 LiterateVersusNon-Literate . . . . . . . . . . . . . . . . . . . . . . 71 6.4.1 Bird-scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . 71 6.4.2 LaTeX-scripts. . . . . . . . . . . . . . . . . . . . . . . . . . 72 7 AdvancedFeatures 73 7.1 SectionsandIn(cid:2)xOperators . . . . . . . . . . . . . . . . . . . . . . 73 7.2 LocalDeclarations . . . . . . . . . . . . . . . . . . . . . . . . . . . 74 7.3 PartialApplication . . . . . . . . . . . . . . . . . . . . . . . . . . . 76 7.4 PatternMatching . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80

Description:
The goal of the Yet Another Haskell Tutorial is to provide a complete intoduction tothe Haskell programming language. It assumes no knowledge of the Haskell languageor familiarity with functional programming in general. However, general familiaritywith programming concepts (such as algorithms) will
See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.