1 / 94

Introduction to Programming in Haskell

Introduction 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

aleta
Download Presentation

Introduction to Programming in Haskell

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Introduction to Programming in Haskell Koen Lindström Claessen

  2. 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 • Everyone will learn a great deal from this course!

  3. Goal of the Course • Start from the basics, after Datorintroduktion • Learn to write small-to-medium sized programs in Haskell • Introduce basic concepts of computer science

  4. Do not break the flow! The Flow You prepare in advance I explain in lecture Tuesdays,Fridays You learn with exercises Mondays/Tuesdays You put to practice with lab assignments Submit end of each week

  5. Exercise Sessions • Mondays or Tuesdays • Depending on what group you are in • Come prepared • Work on exercises together • Discuss and get help from tutor • Personal help • Make sure you understand this week’s things before you leave

  6. Lab Assignments • Work in pairs • (Almost) no exceptions! • Lab supervision • Book a time in advance • One time at a time! • Start working on lab when you have understood the matter • Submit end of each week • Feedback • Return: The tutor has something to tell you; fix and submit again • OK: You are done even this week!

  7. Getting Help • Weekly group sessions • personal help to understand material • Lab supervision • specific questions about programming assignment at hand • Discussion forum • general questions, worries, discussions

  8. Assessment • Written exam (3 credits) • Consists of small programming problems to solve on paper • You need Haskell ”in your fingers” • Course work (2 credits) • Complete all labs successfully

  9. A Risk • 7 weeks is a short time to learn programming • So the course is fast paced • Each week we learn a lot • Catching up again is hard • So do keep up! • Read the text book each week • Make sure you can solve the problems • Go to the weekly exercise sessions • From the beginning

  10. Course Homepage • The course homepage will have ALL up-to-date information relevant for the course • Schedule • Lab assignments • Exercises • Last-minute changes • (etc.) Or Google for ”chalmers introduction functional programming” http://www.cs.chalmers.se/Cs/Grundutb/Kurser/funht/

  11. Software Software = Programs + Data

  12. Data • Data is any kind of storable information. Examples: • Numbers • Letters • Email messages • Songs on a CD • Maps • Video clips • Mouse clicks • Programs

  13. Programs Programs compute new data from old data. Example: Baldur’s Gate computes a sequence of screen images and sounds from a sequence of mouse clicks.

  14. Building Software Systems A 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. Bonnier buys Quicktime Video from Apple. Volvo buys engines from Mitsubishi.

  15. Programming Languages Programs 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.

  16. which language should we teach? Programming Languages Scheme C Lisp BASIC C++ Haskell Java C# ML Python JavaScript csh Curry Perl O’CaML bash Erlang Ruby Prolog Lustre Mercury PostScript VHDL Esterel PDF SQL Verilog

  17. Programming Language Features dynamically typed pure functions higher-order functions statically typed type inference real-time immutable datastructures polymorphism overloading concurrency high performance distribution parameterized types lazy virtual machine Java reflection type classes object oriented compiler interpreter meta-programming Haskell unification C backtracking

  18. Teaching Programming • Give you a broad basis • Easy to learn more programming languages • Easy to adapt to new programming languages • Haskell is defining state-of-the-art in programming language development • Appreciate differences between languages • Become a better programmer!

  19. Industrial Uses of Functional Languages Intel (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)

  20. 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).

  21. A Haskell Demo • Start 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.

  22. GHCi as a Calculator Type in expressions, and ghci calculates and prints their value. Prelude> 2+2 4 Prelude> 2-2 0 Prelude> 2*3 6 Prelude> 2/3 0.666666666666667 Multiplication and division look a bit unfamiliar – we cannot omit multiplication, or type horizontal lines. X 2 3

  23. Binding and Brackets Prelude> 2+2*3 8 Prelude> (2+2)*3 12 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 write 1+2 3+4

  24. Quiz • What is the value of this expression? Prelude> 1+2/3+4

  25. Quiz • What is the value of this expression? Prelude> 1+2/3+4 5.66666666666667

  26. Example: Currency Conversion • Suppose we want to buy a game costing €53 from a foreign web site. Prelude> 53*9.16642 485.82026 Exchange rate: €1 = 9.16642 SEK Price in SEK Boring to type 9.16642 every time we convert a price!

  27. Naming a Value • We 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.hs Do this in a separate window, so you can edit and run hugs simultaneously. Haskell files end in .hs The UNIX prompt, not the ghci one!

  28. Creating the Definition Give the name euroRate to the value 9.16642 variable

  29. Using the Definition Load the file Examples.hs into ghci – make the definition available. The prompt changes – we have now loaded a program. Prelude> :l Examples Main> euroRate 9.16642 Main> 53*euroRate 485.82026 Main> We are free to make use of the definition.

  30. Functional Programming is based on Functions • A function is a way of computing a result from its arguments • A functional program computes its output as a function of its input • E.g. Series of screen images from a series of mouse clicks • E.g. Price in SEK from price in euros

  31. A Function to convert Euros to SEK A definition – placed in the file Examples.hs A comment – to help us understand the program -- convert euros to SEK sek x = x*euroRate Function name – the name we are defining. Expression to compute the result Name for the argument

  32. Using the Function Reload the file to make the new definition available. Main> :r Main> sek 53 485.82026 Call the function Notation: no brackets! C.f. sin 0.5, log 2, not f(x). sek x = x*euroRate x = 53 While we evaluate the right hand side 53*euroRate

  33. Binding and Brackets again Different! This is (sek 50) + 3. Functions bind most tightly of all. Main> sek 53 485.82026 Main> sek 50 + 3 461.321 Main> sek (50+3) 485.82026 Main> Use brackets to recover sek 53. No stranger than writing sin and sin ( + )

  34. Converting Back Again -- convert SEK to euros euro x = x/euroRate Main> :r Main> euro 485.82026 53.0 Main> euro (sek 49) 49.0 Main> sek (euro 217) 217.0 Testing the program: trying it out to see if does the right thing.

  35. Automating Testing • Why compare the result myself, when I have a computer? The operator == tests whether two values are equal Main> 2 == 2 True Main> 2 == 3 False Main> euro (sek 49) == 49 True Yes they are No they aren’t Note:two equal signs are an operator. One equal sign makes a definition. Let the computer check the result.

  36. Defining the Property • Define a function to perform the test for us prop_EuroSek x = euro (sek x) == x Main> prop_EuroSek 53 True Main> prop_EuroSek 49 True Performs the same tests as before – but now we need only remember the function name!

  37. Writing Properties in Files • Functions with names beginning ”prop_” are properties – they should always return True • Writing properties in files • Tells us how functions should behave • Tells us what has been tested • Lets us repeat tests after changing a definition • Properties help us get programs right!

  38. Automatic Testing • Testing account for more than half the cost of a software project • We will use a tool for automatic testing import Test.QuickCheck Capital letters must appear exactly as they do here. Add first in the file of definitions – makes QuickCheck available.

  39. Running Tests Runs 100 randomly chosen tests Main> quickCheck prop_EuroSek Falsifiable, after 10 tests: 3.75 Main> sek 3.75 34.374075 Main> euro 34.374075 3.75 It’s not true! The value for which the test fails. Looks OK

  40. The Problem • There is a very tiny difference between the initial and final values • Calculations are only performed to about 15 significant figures • The property is wrong! Main> euro (sek 3.75) - 3.75 4.44089209850063e-016 e means £ 10 -16

  41. Fixing the Problem • The result should be nearly the same • The difference should be small – say <0.000001 Main> 2<3 True Main> 3<2 False We can use < to see whether one number is less than another

  42. Defining ”Nearly Equal” • We can define new operators with names made up of symbols x ~== y = x-y < 0.000001 With arguments x and y Which returns True if the difference between x and y is less than 0.000001 Define a new operator ~==

  43. Testing ~== Main> 3 ~== 3.0000001 True Main> 3~==4 True OK What’s wrong? x ~== y = x-y < 0.000001

  44. Fixing the Definition • A useful function Main> abs 3 3 Main> abs (-3) 3 Absolute value x ~== y = abs (x-y) < 0.000001 Main> 3 ~== 4 False

  45. Fixing the Property prop_EuroSek x = euro (sek x) ~== x Main> prop_EuroSek 3 True Main> prop_EuroSek 56 True Main> prop_EuroSek 2 True

  46. Name the Price • Let’s define a name for the price of the game we want price = 53 Main> sek price ERROR - Type error in application *** Expression : sek price *** Term : price *** Type : Integer *** Does not match : Double

  47. Every Value has a Type • The :i command prints information about a name Integer (whole number) is the type of price Main> :i price price :: Integer Main> :i euroRate euroRate :: Double Double is the type of real numbers Funny name, but refers to double the precision that computers originally used

  48. More Types The type of truth values, named after the logician Boole Main> :i True True :: Bool -- data constructor Main> :i False False :: Bool -- data constructor Main> :i sek sek :: Double -> Double Main> :i prop_EuroSek prop_EuroSek :: Double -> Bool The type of a function Type of the result Type of the result Type of the argument

  49. Types Matter • Types determine how computations are performed Specify which type to use Main> 123456789*123456789 :: Double 1.52415787501905e+016 Main> 123456789*123456789 :: Integer 15241578750190521 Correct to 15 figures The exact result – 17 figures (but must be an integer) Hugs must know the type of each expression before computing it.

  50. Type Checking • Infers (works out) the type of every expression • Checks that all types match – before running the program

More Related