Introduction to Programming in Haskell

Download Introduction to Programming in Haskell

Post on 30-Dec-2015

30 views

Category:

Documents

6 download

DESCRIPTION

Introduction to Programming in Haskell. Chalmers & GU Emil Axelsson and John Hughes (with thanks to Koen Lindstrm Claessen ). Programming. Exciting subject at the heart of computing Never programmed? Learn to make the computer obey you! Programmed before? - PowerPoint PPT Presentation

TRANSCRIPT

Introduction to Programming in Haskell

Introduction to Programming in HaskellChalmers & GU

Emil Axelsson and John Hughes(with thanks to Koen Lindstrm Claessen)1Welcome to the functional programming course very exciting subject at the heart of CS.Many have never programmed before: in for a treat, learning how to make the computer do what you sayMany have already done some programming: much use for knowledge, but will learn to program in a completely new way.All will learn a great deal from this course.

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!2Goal of the CourseStart from the basics, after Datorintroduktion

Learn to write small-to-medium sized programs in Haskell

Introduce basic concepts of computer science3The FlowYou preparein advanceI explainin lectureYou learnwith exercisesYou put to practicewith lab assignmentsTuesdays,FridaysMondaysSubmit end of each weekDo not break the flow!4Exercise SessionsMondaysGroup roomsCome preparedWork on exercises togetherDiscuss and get help from tutorPersonal helpMake sure you understand this weeks things before you leave

5Lab 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 matterSubmit end of each weekFeedbackReturn: The tutor has something to tell you; fix and submit againOK: You are doneeven this week!bring pen and paper6Getting HelpWeekly group sessionspersonal help to understand materialLab supervisionspecific questions about programming assignment at handDiscussion forumgeneral questions, worries, discussions7AssessmentWritten exam (4.5 credits)Consists of small programming problems to solve on paperYou need Haskell in your fingersCourse work (3 credits)Complete all labs successfully8A 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 lecture notes each weekMake sure you can solve the problemsGo to the weekly exercise sessionsFrom the beginning9Course HomepageThe course homepage will have ALL up-to-date information relevant for the courseScheduleLab assignmentsExercisesLast-minute changes(etc.)

http://www.cse.chalmers.se/edu/course/TDA555/Or go via the student portal10SoftwareSoftware = Programs + Data11DataData is any kind of storable information. Examples:

NumbersLettersEmail messagesSongs on a CDMapsVideo clipsMouse clicksPrograms12ProgramsPrograms compute new data from old data.

Example: Starcraft II computes a sequence of screen images and sounds from a sequence of mouse clicks.13Building 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.Facebook buys video player from Adobe14Programming 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.15Programming LanguagesCHaskellJavaMLOCaMLC++C#PrologPerlPythonRubyPostScriptSQLErlangPDFbashJavaScriptLispSchemeBASICcshVHDLVerilogLustreEsterelMercuryCurrywhich language should we teach?1616Programming Language Featurespolymorphismhigher-order functionsstatically typedparameterized typesoverloadingtype classesobject orientedreflectionmeta-programmingcompilervirtual machineinterpreterpure functionslazyhigh performancetype inferencedynamically typedimmutable datastructuresconcurrencydistributionreal-timeHaskellunificationbacktrackingJavaC1717Teaching 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!18Functional ProgrammingFunctions are the basic building blocks of programsFunctions are used to compose these building blocks into larger programs

A (pure) function computes results from arguments consistently the same19Industrial Uses of Functional LanguagesIntel (microprocessor verification)Hewlett Packard (telecom event correlation)Ericsson (telecommunications)Jeppesen (air-crew scheduling)Facebook (chat engine)Credit Suisse (finance)Barclays Capital (finance)Hafnium (automatic transformation tools)Shop.com (e-commerce)Motorola (test generation)Thompson (radar tracking)Microsoft (F#)Jasper (hardware verification)And many more!20

Computer Sweden, 201021Keynotes at Developer ConferencesEclipse Summit Europ 2009Taking Functional Programming into the MainstreamYOW! 2011, AustraliaEscape From the Ivory Tower: The Haskell JourneyQcon 2012, San FranciscoTesting the Hard Stuff and Staying Sane

John Hughes

Simon Peyton Jones

Don SymeWhy 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 particularly high-performance language (prioritise programmer-time over computer-time).23Cases and Recursion24Example: The squaring functionExample: a function to compute

-- sq x returns the square of xsq :: Integer -> Integersq x = x * x2525Evaluating 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 * x2626Example: Absolute ValueFind the absolute value of a number-- absolute x returns the absolute value of xabsolute :: Integer -> Integerabsolute x = undefined2727Example: 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 -> Integerabsolute x | x > 0 = undefinedabsolute x | x < 0 = undefinedPrograms must often choose between alternativesThink of the cases! These are guards2828Example: 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 -> Integerabsolute x | x > 0 = xabsolute x | x < 0 = -xFill in the result in each case2929Example: Absolute ValueFind the absolute value of a numberCorrect the code-- absolute x returns the absolute value of xabsolute :: Integer -> Integerabsolute x | x >= 0 = xabsolute x | x < 0 = -x>= is greater than or equal, 3030Evaluating GuardsEvaluate absolute (-5)We have two equations to use!Substituteabsolute (-5) | -5 >= 0 = -5absolute (-5) | -5 < 0 = -(-5)absolute x | x >= 0 = xabsolute x | x < 0 = -x3131Evaluating GuardsEvaluate absolute (-5)We have two equations to use!Evaluate the guardsabsolute (-5) | False = -5absolute (-5) | True = -(-5)absolute x | x >= 0 = xabsolute x | x < 0 = -xDiscard this equationKeep this one3232Evaluating GuardsEvaluate absolute (-5)We have two equations to use!Erase the True guardabsolute (-5) = -(-5)absolute x | x >= 0 = xabsolute x | x < 0 = -x3333Evaluating GuardsEvaluate absolute (-5)We have two equations to use!Compute the resultabsolute (-5) = 5absolute x | x >= 0 = xabsolute x | x < 0 = -x3434NotationWe can abbreviate repeated left hand sides

Haskell also has if then elseabsolute x | x >= 0 = xabsolute x | x < 0 = -xabsolute x | x >= 0 = x | x < 0 = -xabsolute x = if x >= 0 then x else -x3535Example: Computing PowersCompute (without using built-in x^n)

3636Example: Computing PowersCompute (without using built-in x^n)Name the function

power3737Example: Computing PowersCompute (without using built-in x^n)Name the inputs

power x n = undefined3838Example: Computing PowersCompute (without using built-in x^n)Write a comment

-- power x n returns x to the power npower x n = undefined3939Example: Computing PowersCompute (without using built-in x^n)Write a type signature

-- power x n returns x to the power npower :: Integer -> Integer -> Integerpower x n = undefined4040How to Compute power?We cannot writepower x n = x * * xn times4141A Table of PowersEach row is x* the previous oneDefine power x n to compute the nth rownpower x n011x2x*x3x*x*x4242A Definition?Testing:Main> power 2 2ERROR - stack overflowpower x n = x * power x (n-1)Why?4343A Definition?Testing:Main> power 2 2Program error: pattern match failure: power 2 0power x n | n > 0 = x * power x (n-1)4444A Definition?Testing:Main> power 2 24power x 0 = 1power x n | n > 0 = x * power x (n-1)First row of the tableThe BASE CASE4545RecursionFirst example of a recursive functionDefined in terms of itself!

Why does it work? Calculate:power 2 2 = 2 * power 2 1power 2 1 = 2 * power 2 0power 2 0 = 1power x 0 = 1power x n | n > 0 = x * power x (n-1)4646RecursionFirst example of a recursive functionDefined in terms of itself!

Why does it work? Calculate:power 2 2 = 2 * power 2 1power 2 1 = 2 * 1power 2 0 = 1power x 0 = 1power x n | n > 0 = x * power x (n-1)4747RecursionFirst example of a recursive functionDefined in terms of itself!

Why does it work? Calculate:power 2 2 = 2 * 2power 2 1 = 2 * 1power 2 0 = 1power x 0 = 1power x n | n > 0 = x * power x (n-1)No circularity!4848RecursionFirst example of a recursive functionDefined in terms of itself!

Why does it work? Calculate:power 2 2 = 2 * power 2 1power 2 1 = 2 * power 2 0power 2 0 = 1power x 0 = 1power x n | n > 0 = x * power x (n-1)The STACK4949RecursionReduce a problem (e.g. power x n) to a smaller problem of the same kindSo that we eventually reach a smallest base caseSolve base case separatelyBuild up solutions from smaller solutionsPowerful problem solving strategyin any programming language!5050ReplicationReplicate a given word n timesrepli :: Integer -> String -> Stringrepli ...GHCi> repli 3 apaapaapaapa51An Answerrepli :: Integer -> String -> Stringrepli 1 s = srepli n s | n > 1 = s ++ repli (n-1) srepli :: Integer -> String -> Stringrepli 0 s = repli n s | n > 0 = s ++ repli (n-1) srepli :: Integer -> String -> Stringrepli 1 s = srepli n s | n > 1 = s ++ repli (n-1) smake base case as simple as possible!52Counting the regionsn lines. How many regions?remove one line ...problem is easier!when do we stop?53A SolutionDon't forget a base caseregions :: Integer -> Integerregions 1 = 2regions n | n > 1 = regions (n-1) + n54A Better SolutionAlways pick the base case as simple as possible!regions :: Integer -> Integerregions 0 = 1regions n | n > 0 = regions (n-1) + n55GroupDivide up a string into groups of length ngroup :: ...group n s = ...LIVE CODING!!!56TypesWhat are the types of repli and group?repli :: Integer -> String -> Stringgroup :: Integer -> String -> [String]repli :: Integer -> [a] -> [a]group :: Integer -> [a] -> [[a]]57How many ways are there to choose k of n elements?e.g.2 of 4?6!LIVE CODING!!!There is no book!If you want a book anyway, try:The Craft of Functional Programming, by Simon Thompson. Available at Cremona.59Course Web PagesURL:http://www.cse.chalmers.se/edu/course/TDA555/Updated almost daily!These slidesSchedulePractical informationAssignmentsDiscussion board60