Introduction to Programming in Haskell

Download Introduction to Programming in Haskell

Post on 19-Mar-2016




1 download

Embed Size (px)


Introduction to Programming in Haskell. Koen Lindstrm Claessen. Programming. Exciting subject at the heart of computing Never programmed? Learn to make the computer obey you! Programmed before? Lucky you! Your knowledge will help a lot... you learn a completely new way to program - PowerPoint PPT Presentation


<ul><li><p>Introduction to Programming in HaskellKoen Lindstrm Claessen</p></li><li><p>ProgrammingExciting subject at the heart of computingNever programmed?Learn to make the computer obey you!Programmed before?Lucky you! Your knowledge will help a you learn a completely new way to programEveryone will learn a great deal from this course!</p></li><li><p>Goal of the CourseStart from the basics, after Datorintroduktion</p><p>Learn to write small-to-medium sized programs in Haskell</p><p>Introduce basic concepts of computer science</p></li><li><p>The FlowYou preparein advanceI explainin lectureYou learnwith exercisesYou put to practicewith lab assignmentsTuesdays,FridaysMondays/TuesdaysSubmit end of each weekDo not break the flow!</p></li><li><p>Exercise SessionsMondays or TuesdaysDepending on what group you are inCome preparedWork on exercises togetherDiscuss and get help from tutorPersonal helpMake sure you understand this weeks things before you leave</p></li><li><p>Lab AssignmentsWork in pairs(Almost) no exceptions!Lab supervisionBook a time in advanceOne time at a time!Start working on lab when you have understood the matter Submit end of each weekFeedbackReturn: The tutor has something to tell you; fix and submit againOK: You are doneeven this week!</p></li><li><p>Getting HelpWeekly group sessionspersonal help to understand materialLab supervisionspecific questions about programming assignment at handDiscussion forumgeneral questions, worries, discussions</p></li><li><p>Assessment Written exam (3 credits)Consists of small programming problems to solve on paperYou need Haskell in your fingersCourse work (2 credits)Complete all labs successfully</p></li><li><p>A Risk7 weeks is a short time to learn programmingSo the course is fast pacedEach week we learn a lotCatching up again is hardSo do keep up!Read the text book each weekMake sure you can solve the problemsGo to the weekly exercise sessionsFrom the beginning</p></li><li><p>Course HomepageThe course homepage will have ALL up-to-date information relevant for the courseScheduleLab assignmentsExercisesLast-minute changes(etc.)</p><p> Google for chalmers introduction functional programming</p></li><li><p>SoftwareSoftware = Programs + Data</p></li><li><p>DataData is any kind of storable information. Examples:</p><p>NumbersLettersEmail messagesSongs on a CDMapsVideo clipsMouse clicksPrograms</p></li><li><p>ProgramsPrograms compute new data from old data.</p><p>Example: Baldurs Gate computes a sequence of screen images and sounds from a sequence of mouse clicks.</p></li><li><p>Building Software SystemsA large system may contain many millions of lines of code.</p><p>Software systems are among the most complex artefacts ever made.</p><p>Systems are built by combining existing components as far as possible.Volvo buys engines from Mitsubishi.Bonnier buys Quicktime Video from Apple.</p></li><li><p>Programming LanguagesPrograms are written in programming languages.</p><p>There are hundreds of different programming languages, each with their strengths and weaknesses.</p><p>A large system will often contain components in many different languages.</p></li><li><p>Programming LanguagesCHaskellJavaMLOCaMLC++C#PrologPerlPythonRubyPostScriptSQLErlangPDFbashJavaScriptLispSchemeBASICcshVHDLVerilogLustreEsterelMercuryCurrywhich language should we teach?</p></li><li><p>Programming Language Featurespolymorphismhigher-order functionsstatically typedparameterized typesoverloadingtype classesobject orientedreflectionmeta-programmingcompilervirtual machineinterpreterpure functionslazyhigh performancetype inferencedynamically typedimmutable datastructuresconcurrencydistributionreal-timeHaskellunificationbacktrackingJavaC</p></li><li><p>Teaching ProgrammingGive you a broad basisEasy to learn more programming languagesEasy to adapt to new programming languagesHaskell is defining state-of-the-art in programming language developmentAppreciate differences between languagesBecome a better programmer!</p></li><li><p>Industrial Uses of Functional LanguagesIntel (microprocessor verification)Hewlett Packard (telecom event correlation)Ericsson (telecommunications)Carlstedt Research &amp; Technology (air-crew scheduling)Hafnium (Y2K tool) (e-commerce)Motorola (test generation)Thompson (radar tracking)Microsoft (SDV)Jasper (hardware verification)</p></li><li><p>Why Haskell?Haskell is a very high-level language (many details taken care of automatically).</p><p>Haskell is expressive and concise (can achieve a lot with a little effort).</p><p>Haskell is good at handling complex data and combining components.</p><p>Haskell is not a high-performance language (prioritise programmer-time over computer-time).</p></li><li><p>A Haskell DemoStart the GHCi Haskell interpreter:</p><p>&gt; ghci ___ ___ _ / _ \ /\ /\/ __(_) / /_\// /_/ / / | | GHC Interactive, version 6.6.1, for Haskell 98./ /_\\/ __ / /___| |\____/\/ /_/\____/|_| Type :? for help.</p><p>Loading package base ... linking ... done.Prelude&gt;The prompt. GHCi is ready for input.</p></li><li><p>GHCi as a CalculatorPrelude&gt; 2+24Prelude&gt; 2-20Prelude&gt; 2*36Prelude&gt; 2/30.666666666666667Type in expressions, and ghci calculates and prints their value.Multiplication and division look a bit unfamiliar we cannot omit multiplication, or type horizontal lines.23X</p></li><li><p>Binding and BracketsPrelude&gt; 2+2*38</p><p>Prelude&gt; (2+2)*312</p><p>Prelude&gt; (1+2)/(3+4)0.428571428571429 Multiplication and division bind more tightly than addition and subtraction so this means 2+6, not 4*3.We use brackets to change the binding (just as in mathematics), so this is 4*3.This is how we write1+23+4</p></li><li><p>QuizWhat is the value of this expression?Prelude&gt; 1+2/3+4</p></li><li><p>QuizWhat is the value of this expression?Prelude&gt; 1+2/3+45.66666666666667</p></li><li><p>Example: Currency ConversionSuppose we want to buy a game costing 53 from a foreign web site.Prelude&gt; 53*9.16642485.82026Exchange rate: 1 = 9.16642 SEKPrice in SEKBoring to type 9.16642 every time we convert a price!</p></li><li><p>Naming a ValueWe give a name to a value by making a definition.Definitions are put in a file, using a text editor such as emacs.&gt; emacs Examples.hsThe UNIX prompt, not the ghci one!Do this in a separate window, so you can edit and run hugs simultaneously.Haskell files end in .hs</p></li><li><p>Creating the DefinitionGive the name euroRate to the value 9.16642variable</p></li><li><p>Using the DefinitionPrelude&gt; :l ExamplesMain&gt; euroRate9.16642Main&gt; 53*euroRate485.82026Main&gt; Load the file Examples.hs into ghci make the definition available.The prompt changes we have now loaded a program.We are free to make use of the definition.</p></li><li><p>Functional Programming is based on FunctionsA function is a way of computing a result from its argumentsA functional program computes its output as a function of its inputE.g. Series of screen images from a series of mouse clicksE.g. Price in SEK from price in euros</p></li><li><p>A Function to convert Euros to SEK-- convert euros to SEKsek x = x*euroRateFunction name the name we are defining.Name for the argumentExpression to compute the resultA definition placed in the file Examples.hsA comment to help us understand the program</p></li><li><p>Using the FunctionMain&gt; :rMain&gt; sek 53485.82026Reload the file to make the new definition available.Call the functionNotation: no brackets!C.f. sin 0.5, log 2, not f(x).sek x = x*euroRatex = 53While we evaluate the right hand side53*euroRate</p></li><li><p>Binding and Brackets againMain&gt; sek 53485.82026Main&gt; sek 50 + 3461.321Main&gt; sek (50+3)485.82026Main&gt; Different!This is (sek 50) + 3.Functions bind most tightly of all.Use brackets to recover sek 53.No stranger than writingsin and sin ( + )</p></li><li><p>Converting Back Again-- convert SEK to euroseuro x = x/euroRateMain&gt; :rMain&gt; euro 485.8202653.0Main&gt; euro (sek 49)49.0Main&gt; sek (euro 217)217.0 Testing the program: trying it out to see if does the right thing.</p></li><li><p>Automating TestingWhy compare the result myself, when I have a computer?Main&gt; 2 == 2TrueMain&gt; 2 == 3False Main&gt; euro (sek 49) == 49True The operator == tests whether two values are equalYes they areNo they arentLet the computer check the result.Note: two equal signs are an operator.One equal sign makes a definition.</p></li><li><p>Defining the PropertyDefine a function to perform the test for usprop_EuroSek x = euro (sek x) == xMain&gt; prop_EuroSek 53TrueMain&gt; prop_EuroSek 49True Performs the same tests as before but now we need only remember the function name!</p></li><li><p>Writing Properties in FilesFunctions with names beginning prop_ are properties they should always return TrueWriting properties in filesTells us how functions should behaveTells us what has been testedLets us repeat tests after changing a definitionProperties help us get programs right!</p></li><li><p>Automatic TestingTesting account for more than half the cost of a software projectWe will use a tool for automatic testingimport Test.QuickCheckAdd first in the file of definitions makes QuickCheck available.Capital letters must appear exactly as they do here.</p></li><li><p>Running TestsMain&gt; quickCheck prop_EuroSekFalsifiable, after 10 tests:3.75</p><p>Main&gt; sek 3.7534.374075Main&gt; euro 34.3740753.75</p><p>Runs 100 randomly chosen testsIts not true!The value for which the test fails.Looks OK</p></li><li><p>The ProblemThere is a very tiny difference between the initial and final values</p><p>Calculations are only performed to about 15 significant figuresThe property is wrong!Main&gt; euro (sek 3.75) - 3.754.44089209850063e-016e means</p><p> 10-16</p></li><li>Fixing the ProblemThe result should be nearly the sameThe difference should be small say 2 3</li><li><p>Defining Nearly EqualWe can define new operators with names made up of symbolsx ~== y = x-y &lt; 0.000001Define a new operator ~==With arguments x and yWhich returns True if the difference between x and y is less than 0.000001</p></li><li><p>Testing ~==Main&gt; 3 ~== 3.0000001TrueMain&gt; 3~==4True OKWhats wrong?x ~== y = x-y &lt; 0.000001</p></li><li><p>Fixing the DefinitionA useful functionMain&gt; abs 33Main&gt; abs (-3)3 Absolute valuex ~== y = abs (x-y) &lt; 0.000001Main&gt; 3 ~== 4False </p></li><li><p>Fixing the Propertyprop_EuroSek x = euro (sek x) ~== xMain&gt; prop_EuroSek 3True Main&gt; prop_EuroSek 56TrueMain&gt; prop_EuroSek 2True</p></li><li><p>Name the PriceLets define a name for the price of the game we wantprice = 53Main&gt; sek priceERROR - Type error in application*** Expression : sek price*** Term : price*** Type : Integer*** Does not match : Double</p></li><li><p>Every Value has a TypeThe :i command prints information about a nameMain&gt; :i priceprice :: Integer</p><p>Main&gt; :i euroRateeuroRate :: Double</p><p>Integer (whole number) is the type of priceDouble is the type of real numbersFunny name, but refers to double the precision that computers originally used</p></li><li><p>More TypesMain&gt; :i TrueTrue :: Bool -- data constructor</p><p>Main&gt; :i FalseFalse :: Bool -- data constructor</p><p>Main&gt; :i seksek :: Double -&gt; Double</p><p>Main&gt; :i prop_EuroSekprop_EuroSek :: Double -&gt; Bool The type of truth values, named after the logician BooleThe type of a functionType of the argumentType of the resultType of the result</p></li><li><p>Types MatterTypes determine how computations are performedMain&gt; 123456789*123456789 :: Double1.52415787501905e+016</p><p>Main&gt; 123456789*123456789 :: Integer15241578750190521Correct to 15 figuresSpecify which type to useThe exact result 17 figures(but must be an integer)Hugs must know the type of each expression before computing it.</p></li><li><p>Type CheckingInfers (works out) the type of every expressionChecks that all types match before running the program</p></li><li><p>Our ExampleMain&gt; :i priceprice :: Integer</p><p>Main&gt; :i seksek :: Double -&gt; Double</p><p>Main&gt; sek priceERROR - Type error in application*** Expression : sek price*** Term : price*** Type : Integer*** Does not match : Double </p></li><li><p>Why did it work before?Main&gt; sek 53485.82026Main&gt; 53 :: Integer53Main&gt; 53 :: Double53.0Main&gt; price :: Integer53Main&gt; price :: DoubleERROR - Type error in type annotation*** Term : price*** Type : Integer*** Does not match : DoubleCertainly works to say 53What is the type of 53?53 can be used with several types it is overloadedGiving it a name fixes the type</p></li><li><p>Fixing the ProblemDefinitions can be given a type signature which specifies their typeprice :: Doubleprice = 53Main&gt; :i priceprice :: Double</p><p>Main&gt; sek price485.82026 </p></li><li><p>Always Specify Type Signatures!They help the reader (and you) understand the programThe type checker can find your errors more easily, by checking that definitions have the types you sayType error messages will be easier to understandSometimes they are necessary (as for price)</p></li><li><p>Example with Type SignatureseuroRate :: DoubleeuroRate = 9.16642</p><p>sek, euro :: Double -&gt; Doublesek x = x*euroRateeuro x = x/euroRate</p><p>prop_EuroSek :: Double -&gt; Boolprop_EuroSek x = euro (sek x) ~== x</p></li><li><p>What is the type of 53?Main&gt; :i 53Unknown reference `53'Main&gt; :t sek 53sek 53 :: Double Main&gt; :t 5353 :: Num a =&gt; a</p><p>Main&gt; :i *infixl 7 *(*) :: Num a =&gt; a -&gt; a -&gt; a -- class member :i only works for namesBut :t gives the type (only) of any expressionIf a is a numeric typeThen 53 can have type aIf a is a numeric typeThen * can have type a-&gt;a-&gt;a</p></li><li><p>What is Num exactly?Main&gt; :i Num-- type class...class (Eq a, Show a) =&gt; Num a where (+) :: a -&gt; a -&gt; a (-) :: a -&gt; a -&gt; a (*) :: a -&gt; a -&gt; a...-- instances:instance Num Intinstance Num Integerinstance Num Floatinstance Num Doubleinstance Integral a =&gt; Num (Ratio a) A class of typesWith these operationsTypes which belong to this class</p></li><li><p>ExamplesMain&gt; 2 + 3.55.5</p><p>Main&gt; True + 3ERROR - Cannot infer instance*** Instance : Num Bool*** Expression : True + 32, +, and 3.5 can all work on DoubleSure enough, Bool is not in the Num class</p></li><li><p>A Tricky One!Main&gt; sek (-10)-91.6642Main&gt; sek -10ERROR - Cannot infer instance*** Instance : Num (Double -&gt; Double)*** Expression : sek - 10Whats going on?</p></li><li><p>Operators AgainMain&gt; :i +infixl 6 +(+) :: Num a =&gt; a -&gt; a -&gt; a -- class member</p><p>Main&gt; :i *infixl 7 *(*) :: Num a =&gt; a -&gt; a -&gt; a -- class memberThe binding power (or precedence) of an operator * binds tighter than + because 7 is greater than 6 </p></li><li><p>Giving ~== a PrecedenceMain&gt; 1/2000000 ~== 0ERROR - Cannot infer instance*** Instance : Fractional Bool*** Expression : 1 / 2000000 ~== 0Wrongly interpreted as1 / (2000000 ~== 0)Instead of(1/2000000) ~== 0</p></li><li><p>Giving ~== a Precedence~== should bind the same way as ==Main&gt; :i ==infix 4 ==(==) :: Eq a =&gt; a -&gt; a -&gt; Bool -- class member Main&gt; 1/2000000 ~== 0True infix 4 ~==x ~== y = abs (x-y) &lt; 0.000001</p></li><li><p>SummaryThink about the properties of your program... and write them downIt helps you understandingthe problem you are solvingthe program you are writingIt helps others understanding what you didco-workerscustomersyou in 1 year from now</p></li><li><p>Cases and Recursion</p></li><li><p>Example: The squaring functionExample: a function to compute</p><p>-- sq x returns the square of xsq :: Integer -&gt; Integersq x = x * x</p></li><li><p>Evaluating FunctionsTo evaluate sq 5:Use the definitionsubstitute 5 for x throughoutsq 5 = 5 * 5Continue evaluating expressionssq 5 = 25Just like working out mathematics on papersq x = x * x</p></li><li><p>Example: Absolute ValueFind the absolute value of a number-- absolute x returns the absolute value of xabsolute :: Integer -&gt; Integerabsolute x = undefined</p></li><li><p>Example: Absolute ValueFind the absolute value of a numberTwo cases!If x is positive, result is xIf x is negative, result is -x-- absolute x returns the absolute value of xabsolute :: Integer -&gt; Integerabsolute x | x &gt; 0 = undefinedabsolute x | x &lt; 0 = undefinedPrograms must often choose between alternat...</p></li></ul>