introduction to programming in haskell
Post on 19-Mar-2016
Embed Size (px)
DESCRIPTIONIntroduction to Programming in Haskell. Koen Lindström 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... ...as you learn a completely new way to program - PowerPoint PPT Presentation
Introduction to Programming in HaskellKoen Lindstrm Claessen
ProgrammingExciting subject at the heart of computingNever programmed?Learn to make the computer obey you!Programmed before?Lucky you! Your knowledge will help a lot......as you learn a completely new way to programEveryone will learn a great deal from this course!
Goal of the CourseStart from the basics, after Datorintroduktion
Learn to write small-to-medium sized programs in Haskell
Introduce basic concepts of computer science
The FlowYou preparein advanceI explainin lectureYou learnwith exercisesYou put to practicewith lab assignmentsTuesdays,FridaysMondays/TuesdaysSubmit end of each weekDo not break the flow!
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
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!
Getting HelpWeekly group sessionspersonal help to understand materialLab supervisionspecific questions about programming assignment at handDiscussion forumgeneral questions, worries, discussions
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
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
Course HomepageThe course homepage will have ALL up-to-date information relevant for the courseScheduleLab assignmentsExercisesLast-minute changes(etc.)
http://www.cs.chalmers.se/Cs/Grundutb/Kurser/funht/Or Google for chalmers introduction functional programming
SoftwareSoftware = Programs + Data
DataData is any kind of storable information. Examples:
NumbersLettersEmail messagesSongs on a CDMapsVideo clipsMouse clicksPrograms
ProgramsPrograms compute new data from old data.
Example: Baldurs Gate computes a sequence of screen images and sounds from a sequence of mouse clicks.
Building Software SystemsA large system may contain many millions of lines of code.
Software systems are among the most complex artefacts ever made.
Systems are built by combining existing components as far as possible.Volvo buys engines from Mitsubishi.Bonnier buys Quicktime Video from Apple.
Programming LanguagesPrograms are written in programming languages.
There are hundreds of different programming languages, each with their strengths and weaknesses.
A large system will often contain components in many different languages.
Programming Language Featurespolymorphismhigher-order functionsstatically typedparameterized typesoverloadingtype classesobject orientedreflectionmeta-programmingcompilervirtual machineinterpreterpure functionslazyhigh performancetype inferencedynamically typedimmutable datastructuresconcurrencydistributionreal-timeHaskellunificationbacktrackingJavaC
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!
Industrial Uses of Functional LanguagesIntel (microprocessor verification)Hewlett Packard (telecom event correlation)Ericsson (telecommunications)Carlstedt Research & Technology (air-crew scheduling)Hafnium (Y2K tool)Shop.com (e-commerce)Motorola (test generation)Thompson (radar tracking)Microsoft (SDV)Jasper (hardware verification)
Why Haskell?Haskell is a very high-level language (many details taken care of automatically).
Haskell is expressive and concise (can achieve a lot with a little effort).
Haskell is good at handling complex data and combining components.
Haskell is not a high-performance language (prioritise programmer-time over computer-time).
A Haskell DemoStart the GHCi Haskell interpreter:
> ghci ___ ___ _ / _ \ /\ /\/ __(_) / /_\// /_/ / / | | GHC Interactive, version 6.6.1, for Haskell 98./ /_\\/ __ / /___| | http://www.haskell.org/ghc/\____/\/ /_/\____/|_| Type :? for help.
Loading package base ... linking ... done.Prelude>The prompt. GHCi is ready for input.
GHCi as a CalculatorPrelude> 2+24Prelude> 2-20Prelude> 2*36Prelude> 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
Binding and BracketsPrelude> 2+2*38
Prelude> (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
QuizWhat is the value of this expression?Prelude> 1+2/3+4
QuizWhat is the value of this expression?Prelude> 1+2/3+45.66666666666667
Example: Currency ConversionSuppose we want to buy a game costing 53 from a foreign web site.Prelude> 53*9.16642485.82026Exchange rate: 1 = 9.16642 SEKPrice in SEKBoring to type 9.16642 every time we convert a price!
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.> 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
Creating the DefinitionGive the name euroRate to the value 9.16642variable
Using the DefinitionPrelude> :l ExamplesMain> euroRate9.16642Main> 53*euroRate485.82026Main> 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.
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
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
Using the FunctionMain> :rMain> 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
Binding and Brackets againMain> sek 53485.82026Main> sek 50 + 3461.321Main> sek (50+3)485.82026Main> Different!This is (sek 50) + 3.Functions bind most tightly of all.Use brackets to recover sek 53.No stranger than writingsin and sin ( + )
Converting Back Again-- convert SEK to euroseuro x = x/euroRateMain> :rMain> euro 485.8202653.0Main> euro (sek 49)49.0Main> sek (euro 217)217.0 Testing the program: trying it out to see if does the right thing.
Automating TestingWhy compare the result myself, when I have a computer?Main> 2 == 2TrueMain> 2 == 3False Main> 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.
Defining the PropertyDefine a function to perform the test for usprop_EuroSek x = euro (sek x) == xMain> prop_EuroSek 53TrueMain> prop_EuroSek 49True Performs the same tests as before but now we need only remember the function name!
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!
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.
Running TestsMain> quickCheck prop_EuroSekFalsifiable, after 10 tests:3.75
Main> sek 3.7534.374075Main> euro 34.3740753.75
Runs 100 randomly chosen testsIts not true!The value for which the test fails.Looks OK
The ProblemThere is a very tiny difference between the initial and final values
Calculations are only performed to about 15 significant figuresThe property is wrong!Main> euro (sek 3.75) - 3.754.44089209850063e-016e means
- Fixing the ProblemThe result should be nearly the sameThe difference should be small say 2 3