0 programming in haskell author: prof graham hutton functional programming lab school of computer...

Download 0 PROGRAMMING IN HASKELL Author: Prof Graham Hutton Functional Programming Lab School of Computer Science University of Nottingham, UK (Used with Permission)

Post on 19-Dec-2015

218 views

Category:

Documents

6 download

Embed Size (px)

TRANSCRIPT

  • Slide 1
  • 0 PROGRAMMING IN HASKELL Author: Prof Graham Hutton Functional Programming Lab School of Computer Science University of Nottingham, UK (Used with Permission)
  • Slide 2
  • 1 The > prompt means that the system is ready to evaluate an expression. For example: > 2+3*4 14 > (2+3)*4 20 > sqrt (3^2 + 4^2) 5.0
  • Slide 3
  • 2 The Standard Prelude The library file Prelude.hs provides a large number of standard functions. In addition to the familiar numeric functions such as + and *, the library also provides many useful functions on lists. zBecause of the predefinitions, GHCi may complain if you try to redefine something it already has a definition for. zSelect the first element of a list: zSingle line comments are preceded by ``--'' and continue to the end of the line. > head [1,2,3,4,5] 1
  • Slide 4
  • 3 zRemove the first element from a list: > tail [1,2,3,4,5] [2,3,4,5] zSelect the nth element of a list: > [1,2,3,4,5] !! 2 3 zSelect the first n elements of a list: > take 3 [1,2,3,4,5] [1,2,3]
  • Slide 5
  • 4 zRemove the first n elements from a list: > drop 3 [1,2,3,4,5] [4,5] zCalculate the length of a list: > length [1,2,3,4,5] 5 zCalculate the sum of a list of numbers: > sum [1,2,3,4,5] 15
  • Slide 6
  • 5 zCalculate the product of a list of numbers: > product [1,2,3,4,5] 120 zAppend two lists: > [1,2,3] ++ [4,5] [1,2,3,4,5] zReverse a list: > reverse [1,2,3,4,5] [5,4,3,2,1]
  • Slide 7
  • 6 Examples Mathematics Haskell f(x) f(x,y) f(g(x)) f(x,g(y)) f(x)g(y) f x f x y f (g x) f x (g y) f x * g y
  • Slide 8
  • 7 Haskell Scripts zAs well as the functions in the standard prelude, you can also define your own functions; zNew functions are defined within a script, a text file comprising a sequence of definitions; zBy convention, Haskell scripts usually have a.hs suffix on their filename. This is not mandatory, but is useful for identification purposes.
  • Slide 9
  • 8 My First Script double x = x + x quadruple x = double (double x) When developing a Haskell script, it is useful to keep two windows open, one running an editor for the script, and the other running GHCi. Start an editor, type in the following two function definitions, and save the script as test.hs:
  • Slide 10
  • 9 Leaving the editor open, click on the file to open ghci using that file: > quadruple 10 40 > take (double 2) [1,2,3,4,5,6] [1,2,3,4] Now both Prelude.hs and test.hs are loaded, and functions from both scripts can be used:
  • Slide 11
  • 10 factorial n = product [1..n] average ns = sum ns `div` length ns Leaving GHCi open, return to the editor, add the following two definitions, and resave. From within GHCi, enter :r (to reload the changed file) zThese functions are defined via an equation zdiv is enclosed in back quotes, not forward; zx `f` y is just syntactic sugar for f x y. Note:
  • Slide 12 factorial 10 3628800 > average [1,2,3,4,5] 3 GHCi does not automatically detect that the script has been changed, so "> factorial 10 3628800 > average [1,2,3,4,5] 3 GHCi does not automatically detect that the script has been changed, so a reload command must be executed before the new definitions can be used:"> factorial 10 3628800 > average [1,2,3,4,5] 3 GHCi does not automatically detect that the script has been changed, so " title="11 > :r Reading file "test.hs" > factorial 10 3628800 > average [1,2,3,4,5] 3 GHCi does not automatically detect that the script has been changed, so ">
  • 11 > :r Reading file "test.hs" > factorial 10 3628800 > average [1,2,3,4,5] 3 GHCi does not automatically detect that the script has been changed, so a reload command must be executed before the new definitions can be used:
  • Slide 13
  • 12 Naming Requirements zFunction and argument names must begin with a lower-case letter. For example: myFunfun1arg_2x zBy convention, list arguments usually have an s suffix on their name. For example: xsnsnss
  • Slide 14
  • 13 The Layout Rule In a sequence of definitions, each definition must begin in precisely the same column: a = 10 b = 20 c = 30 a = 10 b = 20 c = 30 a = 10 b = 20 c = 30
  • Slide 15
  • 14 means The layout rule avoids the need for explicit syntax to indicate the grouping of definitions. We can introduce local variables on the right hand side via a where clause. a = b + c where b = 1 c = 2 d = a * 2 a = b + c where {b = 1; c = 2} d = a * 2 implicit grouping explicit grouping
  • Slide 16
  • 15 Useful Commands in GHCi CommandMeaning :load nameload script name :reloadreload current script :edit nameedit script name :editedit current script :type exprshow type of expr :?show all commands :quitquit
  • Slide 17
  • 16 Exercises N = a div length xs where a = 10 xs = [1,2,3,4,5] Try out the examples of this lecture Fix the syntax errors in the program below, and test your solution. (1) (2)
  • Slide 18
  • 17 Show how the library function last that selects the last element of a list can be defined using the functions introduced in this lecture. (3) Similarly, show how the library function init that removes the last element from a list can be defined in two different ways. (5) Can you think of another possible definition for last? (4)
  • Slide 19
  • 18 PROGRAMMING IN HASKELL Types and Classes
  • Slide 20
  • 19 What is a Type? A type is a name for a collection of related values. For example, in Haskell the basic type TrueFalse Bool contains the two logical values:
  • Slide 21
  • Algebraic types zthere are still things we are missing such as yThe types for the months January December. yThe type whose elements are either a number or a string. (a house will either have a number or name, say) yA type of tree. zAll of these can be modeled as algebraic types. 20
  • Slide 22
  • The simplest form of an algebraic type is an enumerated type. data Season = Spring | Summer | Fall | Winter data Weather = Rainy | Hot | Cold data Color = Red | Blue| Green|Yellow deriving (Show,Eq,Ord) data Ordering = LT|EQ|GT -- built into the Ordering Class A more complicated algebraic type (the product type) allows for the type constructor to have types associated with it. data Student = USU String Int data Address = None | Addr String data Age = Years Int data Shape = Circle Float | Rectangle Float Float data Tree a = Branch (Tree a) (Tree a) | Leaf a data Point a = Pt a a Thus, Student is formed from a String (call it st) and an Int (call it x) and the element Student formed from them will be recognized as USU st x 21
  • Slide 23
  • The general form of the algebraic type is zdata TypeName z = Con 1 T 11.. T 1n | z Con 2 T 21..T 2m | Each Con i is a constructor which may be followed by zero or more types. We build elements of TypeName by applying this constsructor functions to arguments. 22
  • Slide 24
  • Algebraic types can also be recursive data Expr = Lit Int | Add Expr Expr | Sub Expr Expr data Tree = Nil | Node Int Tree Tree printBST:: Tree -> [Int] printBST Nil = [] printBST (Node x left right) = (printBST left) ++ [x]++ (printBST right) main> printBST (Node 5 (Node 3 Nil Nil) Nil) [3,5] 23
  • Slide 25
  • 24 Type Errors Applying a function to one or more arguments of the wrong type is called a type error. > 1 + False Error 1 is a number and False is a logical value, but + requires two numbers.
  • Slide 26
  • 25 Types in Haskell zIf evaluating an expression e would produce a value of type t, then e has type t, written e :: t zEvery well formed expression has a type, which can be automatically calculated at compile time using a process called type inference.
  • Slide 27
  • 26 zAll type errors are found at compile time, which makes programs safer and faster by removing the need for type checks at run time. zIn GHCi, the :type command calculates the type of an expression, without evaluating it: > not False True > :type not False not False :: Bool
  • Slide 28
  • 27 Basic Types Haskell has a number of basic types, including: Bool - logical values Char - single characters Integer - arbitrary-precision integers Float - floating-point numbers String - strings of characters Int - fixed-precision integers
  • Slide 29
  • 28 List Types [False,True,False] :: [Bool] [a,b,c,d] :: [Char] In general: A list is sequence of values of the same type: [t] is the type of lists with elements of type t.
  • Slide 30
  • 29 zThe type of a list says nothing about its length: [False,True] :: [Bool] [False,True,False] :: [Bool] [[a],[b,c]] :: [[Char]] Note: zThe type of the elements is unrestricted. For example, we can have lists of lists:
  • Slide 31
  • 30 Tuple Types (like a struct or record) A tuple is a sequence of values of different types: (False,True) :: (Bool,Bool) (False,a,True) :: (Bool,Char,Bool) In general: (t1,t2,,tn) is the type of n-tuples whose ith components have type ti for any i in 1n.
  • Slide 32
  • 31 zThe type of a tuple shows its size: (False,True) :: (Bool,Bool) (False,True,False) :: (Bool,Bool,Bool) (a,(False,b)) :: (Char,(Bool,Char)) (True,[a,b]) :: (Bool,[Char]) Note: zThe type of the components is unrestricted:
  • Slide 33